From 1940fe95d92981fbf17e3b61c77e4666ba9fce52 Mon Sep 17 00:00:00 2001 From: pasta Date: Tue, 27 Oct 2026 19:27:28 +0000 Subject: [PATCH 01/26] feat(contracts): board and card types in forge-meta (UPDATE-3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds `board` (a board's definition) and `card` (a member's placement of one issue or PR on a board) behind a new UPDATE-3 flag `boards` in build.py, as docs/design/boards.md §3 specifies. Like UPDATE-2's vaultEntry they are defined in forge-community, moved to forge-meta by META_TYPES and built with the four-contract layout only. Both are mutable, never deleted (state 2 is the delete) and gated like label: a forge-core maintainer of the home repo, or a writer whose role is the claimed r, re-checked on every replace. board: r = 1, unique byKey (repoId, key, $ownerId), noPlain/hasName, enc 29-5120. card: r 1-2, item refersTo a forge-collab issue or patch, unique onItem (item, repoId, board, $ownerId) and recent (repoId, board, $updatedAt), noPlain, enc 29-2560. With mainnet_pinned_gates the role claims are rules (rClaim). forge-meta grows 7,684 -> 10,842 B (create transition 10,948 B, 9,532 B of room). contract-validate accepts it as an update of the registered testnet forge-meta and of testnet's version 2; testnet's registration lists `boards` under `since`. The vectors (U3), the update guards, an offline-chain test of the gate and an `--update meta` deploy test cover it; deploy-v2 already substituted forge-collab's id on an update, and its self-test now checks a forge-meta with cards names it. The clients' layout maps learn both types (META_ONLY_TYPES: no three-contract home). Nothing is broadcast. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + crates/forge-core/src/layout.rs | 32 +- docs/contracts/forge-v2.md | 13 +- docs/deploying-to-a-network.md | 2 +- docs/limits.md | 2 + docs/security/private-repos.md | 6 +- .../contracts/mainnet/forge-meta.json | 349 ++++++++++++++++++ forge-contracts/schema/build.py | 98 ++++- forge-contracts/schema/vectors.py | 101 ++++- forge-contracts/scripts/deploy-v2.mjs | 10 +- forge-contracts/scripts/deploy-v2.test.mjs | 23 ++ .../scripts/lib/offline-chain.test.mjs | 44 ++- forge-contracts/scripts/lib/seed-io.mjs | 12 +- forge-contracts/scripts/lib/seed-io.test.mjs | 10 +- .../vectors/rc1/forge-community.indices.json | 12 + forge-web/lib/layout.test.ts | 9 +- forge-web/lib/layout.ts | 19 +- forge-web/lib/repo/contract.ts | 4 + 18 files changed, 715 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16c2c3f68..8d5a56b7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ What a version number promises before 1.0 is described in [docs/VERSIONING.md](d ## [Unreleased] +### Added + +- **Board contract types.** forge-meta gains `board` and `card` (UPDATE-3, [boards design](docs/design/boards.md) §3), written only by the home repository's members; testnet gets them by an in-place update of forge-meta (version 3), which is not applied yet. + ### Fixed - **InstantSend proofs on testnet.** Creating or topping up an identity, in the web app or with `dg auth new`, waited on `getislocks` at `trpc.digitalcash.dev`, which no longer follows testnet, so every lock fell back to a slower chain-lock proof. The InstantSend lock now comes off DAPI `subscribeToTransactionsWithProofs` feeds on three evonodes, opened before the asset lock is broadcast, as in govhub and mainnet-bridge. `--islock-rpc` and `islock_rpc` still add an RPC of your choice, but none is set by default. diff --git a/crates/forge-core/src/layout.rs b/crates/forge-core/src/layout.rs index eab615e57..5e8e6b747 100644 --- a/crates/forge-core/src/layout.rs +++ b/crates/forge-core/src/layout.rs @@ -7,7 +7,8 @@ //! //! DESIGN rev 4.1 D44 adds a fourth contract, forge-meta, registered last: `repoKey`, `ban`, //! `label`, `topic`, `packMirror`, `profile` and `follow` ([`META_TYPES`]) move there, and -//! `vaultEntry` (UPDATE-2, the passkey vault) exists there only. The +//! `vaultEntry` (UPDATE-2, the passkey vault), `board` and `card` (UPDATE-3, boards) exist there +//! only ([`META_ONLY_TYPES`]). The //! deployment record says which layout a network has (`v2.forgeMeta` present, //! [`ForgeIds::meta`]), so one build serves sakura's three-contract set and four-contract sets: //! [`ForgeIds::contract_of`] is the layout-aware map, [`ForgeContract::of`] the three-contract @@ -87,10 +88,10 @@ pub const COMMUNITY_TYPES: [&str; 12] = [ /// The types forge-meta holds on a four-contract set (D44). On a three-contract set they stay /// in [`CORE_TYPES`] (`label`, `topic`, `packMirror`), [`COLLAB_TYPES`] (`repoKey`, `ban`) and /// [`COMMUNITY_TYPES`] (`profile`, `follow`). None of them is read by a rule, total or derived -/// index of its old contract, so the move changes no consensus rule. `vaultEntry` (UPDATE-2) is -/// the exception: `build.py` builds it with the four-contract layout only, so it has no -/// three-contract home and [`ForgeContract::of`] knows no contract for it. -pub const META_TYPES: [&str; 8] = [ +/// index of its old contract, so the move changes no consensus rule. [`META_ONLY_TYPES`] are the +/// exception: `build.py` builds them with the four-contract layout only, so they have no +/// three-contract home and [`ForgeContract::of`] knows no contract for them. +pub const META_TYPES: [&str; 10] = [ "repoKey", "ban", "label", @@ -99,8 +100,15 @@ pub const META_TYPES: [&str; 8] = [ "profile", "follow", "vaultEntry", + "board", + "card", ]; +/// The [`META_TYPES`] no three-contract set has: `vaultEntry` (UPDATE-2, the passkey vault) and +/// `board` and `card` (UPDATE-3, `docs/design/boards.md` §3). On a network without forge-meta +/// [`ForgeIds::contract_of`] answers `None` for them. +pub const META_ONLY_TYPES: [&str; 3] = ["vaultEntry", "board", "card"]; + /// The listed types a contract build may leave out: RC2's fused star (C1, a `build.py` flag) /// drops `starBeat`, whose count the star's own `byWeek` index takes over. Clients read the /// shape from the loaded contract (`Collab::fused_star`), so both builds work. `packMirror` and @@ -419,8 +427,18 @@ mod tests { assert_eq!(four.contract_id_of(t), Some("META"), "{t}"); assert_eq!(four.home(t), "META", "{t}"); assert_ne!(three.contract_id_of(t), Some("META"), "{t}"); - // (vaultEntry, UPDATE-2, is a four-contract type: no home in the three-contract set) - assert_eq!(three.contract_id_of(t).is_some(), t != "vaultEntry", "{t}"); + // (vaultEntry, board and card are four-contract types: no home in the three-contract set) + assert_eq!( + three.contract_id_of(t).is_some(), + !META_ONLY_TYPES.contains(&t), + "{t}" + ); + } + for t in META_ONLY_TYPES { + assert!(META_TYPES.contains(&t), "{t}"); + assert_eq!(ForgeContract::of(t), None, "{t}"); + assert_eq!(three.contract_of(t), None, "{t}"); + assert_eq!(four.contract_of(t), Some(ForgeContract::Meta), "{t}"); } for (t, old) in [ ("repoKey", "COLLAB"), diff --git a/docs/contracts/forge-v2.md b/docs/contracts/forge-v2.md index ee6fdcfec..57bb0e358 100644 --- a/docs/contracts/forge-v2.md +++ b/docs/contracts/forge-v2.md @@ -126,6 +126,15 @@ The mainnet forge-core also gains `pushGrant` (B1, §9.1): a maintainer's grant Size: forge-meta serializes to 7,684 B (6,870 B without it), its create transition to 7,790 B (6,976 B), which leaves 12,690 B of room; the fee schedule's registration fee for the contract goes from 0.36 to 0.39 DASH (one more type and one more index; the per-byte part is not in that figure). **Estimated fees** (not measured on Forge; scaled from Yappr's sakura measurements of the same document shape, to be re-measured by the live test): a first entry about 46 to 50 M credits (about 0.0005 DASH), a later entry about 28 to 31 M, a re-seal about 2 to 3 M, a delete refunds about 23 to 35 M, and a sign-in reads only, so it is free. Forge's 256 B ciphertext is 80 to 160 B larger than Yappr's, which adds about 2 to 4 M credits at 27,400 credits per byte ([economics.md](../economics.md)). All of it comes out of the signed-in key's budget. +**`board` and `card` (UPDATE-3, boards; [docs/design/boards.md](../design/boards.md) §3).** Two more types no other layout has: a board's definition, and a member's placement of one issue or PR on it. `build.py` defines them in forge-community (flag `boards`, in `UPDATE3_FLAGS`) and `META_TYPES` moves them to forge-meta, built with the four-contract layout only, as `vaultEntry`. Their gate is `label`'s: `ownerRefersTo` a forge-core `maintainer` of `repoId`, or a `writer` with `where {"role": "r"}`. A `deletableDocument` found by `findBy` is asked again on every replace (book `contract-keywords/owner-refers-to.md` "On replace"), so a removed member cannot touch their old documents and a role change holds from the next write. `card.item` refers to forge-collab's `issue` or `patch` (`FORGE_COLLAB_CONTRACT_ID`, no `where`: any repository's item), so forge-meta now names forge-collab as well as forge-core. Both are mutable and **never deleted** (`canBeDeleted: false`), one document per member: a member's later write replaces their own, and readers take the newest across members by (`$updatedAt`, `$id`). A delete would silently bring the previous member's document back, which no poll of `$updatedAt` sees, so `state` 2 stands for it. Every index key and both timestamps are `required` (an unrequired `$updatedAt` is never recorded, and a unique index holds no document that lacks a key part). No rule or total of another type reads them, and protocol 14 lets an update add them (new types with their own indexes, §9.1). + +| Type | Gate (create) | Mutable | Deletable | Notes | +|---|---|---|---|---| +| `board` | M or W1 (`r` 1, `rClaim` `r = 1`) | yes; `repoId`, `key` immutable | **no** (`state` 2 is the delete) | `key` u32 1–4294967295, the board (random, chosen at creation); `name` 1–63 characters, ≤ 252 B, a visible character (`TITLE`); `spec` ≤ 4,096 B, the definition (JSON `v: 1`, boards.md §2); `state` 0 open, 1 closed, 2 deleted; `enc` 29–5,120 B (its own bound, inline: `$defs.enc` is label's 1,536 B) with `epoch` (`dependentRequired`); a private repo's clients seal `name` and `spec` together in it (a client rule: nothing at consensus ties `enc` to the repo's visibility, as on `label`). `noPlain`: with `enc`, neither `name` nor `spec`; `hasName`: without `enc`, both. Unique `byKey (repoId, key, $ownerId)`; its `repoId` prefix lists a repo's boards. A writer may close or delete a maintainer's board, as with labels (the newest wins) | +| `card` | M or W2 (`r` 1..2, `rClaim`) | yes; `repoId`, `board`, `item` immutable | **no** (`state` 2 is "removed") | `board` u32 1–4294967295 (the board's key); `item` → collab `issue` or `patch`, any repository, required, so a card always names an item; `col` 0–255 (0 none); `rank` 1–63 characters, `^[0-9A-Za-z]*[1-9A-Za-z]$` (base-62, never ending in `0`, boards.md §2.6); `f` ≤ 2,048 B (JSON field values); `state` 0 active, 1 archived, 2 removed, plaintext in every repo; `enc` 29–2,560 B with `epoch` (`dependentRequired`); a private repo's clients seal `col`, `rank` and `f` in it (a client rule, as on `board`), and `noPlain` refuses them in plaintext beside `enc`. Unique `onItem (item, repoId, board, $ownerId)` (one card per member, item and board; its `item` prefix answers "which boards is this on") and `recent (repoId, board, $updatedAt)` (load a board, and poll it for what changed since) | + +Fixed by this registration, since an update can never add an `ownerRefersTo` operand or a reference: only the home repository's members place cards (a member of the item's repository who is not one of the home repo's cannot), a card always names an issue or a PR, and triage defines no board. With `mainnet_pinned_gates` each claim is restated as a rule (`rClaim`), so an update raising `r`'s maximum opens nothing. Size: forge-meta serializes to 10,842 B (7,684 B without them), its create transition to 10,948 B, which leaves 9,532 B of room; the fee schedule's registration fee for the contract goes from 0.39 to 0.46 DASH (two more types, three more indexes). A three-contract network has neither (the clients' layout answers "no contract holds it"). + A devnet may run the three-contract set (devnet sakura did until it moved to the four-contract set on 2026-10-17), and clients take the layout from the deployment record: `v2.forgeMeta` present means four contracts, and the seven types are read and written there; absent, they stay in their old homes. One build serves both (phase M-B: `forge-core::layout` `ForgeIds::contract_of` and `home`, forge-web `lib/layout.ts` `contractKindOfType` and `lib/repo/source.ts` `contractOf`, the seed scripts' `contractOn`). The cost previews follow: a signer's first write to forge-meta pays its contract nonce even when it has written the type's old home, and a key bound to forge-meta alone is a wallet grant of its own ("labels, topics and profiles"). Shared shapes (`id`, `hid`, `oid`, `h32`, `refName`, `branch`, `title`, `body`, `enc`, `vis`, `member`, …) are in `schemaDefs` and referenced with `$ref`. A document type may use each `$defs` entry **once**: rs-dpp's depth walker treats a second `$ref` to the same definition in one type as a cycle (`InvalidJsonSchemaRefError`). That is why `packHash` uses `hid`, an identical copy of `id`. The same goes for the `integer` shape of a key id named by `encryptedFor` or `keyIdProperty`, which must be inline (the parser's `is_key_id_schema` resolves `$ref` against the document schema, which has no `$defs`). Repeats are inlined for these reasons. Every `enc` is at least 29 bytes (INV-11: the smallest envelope). @@ -734,7 +743,7 @@ cargo +1.98.1 run -q --locked --manifest-path tools/contract-validate/Cargo.toml - Results go to the `v2` section of `deployments/.json` (`devnet-.json` for a devnet). Each step's nonce (masked to its low 40 bits, as rs-dpp does), contract id, group id derived from that same nonce, and pre-broadcast balance are written before broadcasting. A rerun that finds the contract on chain completes the record (status, cost, owner) rather than skipping it; one whose reserved nonce never landed takes the chain's next nonce and re-derives both ids from it. It never registers a second copy unless told to. Each record also carries `schemaHash`, the sha256 of the schema JSON (after placeholder substitution, compactly re-serialized) it was registered from; a rerun that finds a recorded contract whose hash differs from the current schema warns and leaves it as is. A dry run's forge-core step is not checked against a leftover record. - `--force-new` without `--only` supersedes the set when the recorded forge-core was registered from a different schema: forge-core's record moves to `v2.forgeCoreSuperseded`, the group to `v2.contractGroupSuperseded`, forge-collab and forge-community (whose schemas name forge-core's id) to `v2.forgeCollabSuperseded` / `v2.forgeCommunitySuperseded`, and a new forge-core (registering a new group), forge-collab and forge-community are registered. A rerun after success registers nothing. - `--only collab` / `--only community` registers that contract alone, against the forge-core and group already recorded and found on chain; it never registers forge-core or the other one. With `--force-new --same-group` it registers a new one when the recorded one is registered from a different schema (its `schemaHash` differs, or it predates the field): the old record moves to `v2.forgeCollabSuperseded` (or `v2.forgeCommunitySuperseded`), and the new one takes the next nonce and so a new id. A recorded contract from the current schema, or one still `broadcasting` (an interrupted run, which is completed or retried instead), is never superseded, so rerunning the same command registers nothing. This is how a schema change the update rules refuse ships. Documents written under the old contract stay under its id. -- **forge-meta** (four-contract sets, §2): registered fourth, after forge-community, with forge-core's id substituted for `FORGE_CORE_CONTRACT_ID`; its create transition enrols it in the group, whose description then names all four ("Dash Forge v2: forge-core, forge-collab, forge-community and forge-meta"; `tools/contract-validate` sizes the same string). `--only meta` registers it alone against the recorded forge-core and group, and `--update meta` updates it in place. Its record is `v2.forgeMeta`. `--self-test --contracts ` checks that forge-meta names forge-core and that nothing registered before it names forge-meta. +- **forge-meta** (four-contract sets, §2): registered fourth, after forge-community, with forge-core's id substituted for `FORGE_CORE_CONTRACT_ID` and, since UPDATE-3 (`card.item`), forge-collab's for `FORGE_COLLAB_CONTRACT_ID`; its create transition enrols it in the group, whose description then names all four ("Dash Forge v2: forge-core, forge-collab, forge-community and forge-meta"; `tools/contract-validate` sizes the same string). `--only meta` registers it alone against the recorded forge-core and group, and `--update meta` updates it in place. Its record is `v2.forgeMeta`. `--self-test --contracts ` checks that forge-meta names forge-core (and forge-collab, when it has cards) and that nothing registered before it names forge-meta. - **Scratch sets.** `--contracts ` registers the JSON in `` instead of `forge-contracts/contracts`, and then needs `--record `: the deployment record the run reads and writes. No file under `forge-contracts/deployments/` (any network's record, the snapshots under `deployments/contracts/`) is accepted as a `--record`, compared by real path and without case; a scratch record that names the network's own forge-core or contract group is refused, and a contract in it registered from another schema stops the run instead of being reused. So a scratch run (phase M-C's throwaway set) never touches or extends the live deployment or the web's snapshot. Without `--addresses` it takes the DAPI addresses from the scratch record, else (read only) from the network's record. - **Named sets and the live testnet/mainnet record.** `--set devnet` (the default on a devnet) is `forge-contracts/contracts`, `--set mainnet` the committed four-contract set `forge-contracts/contracts/mainnet`; testnet and mainnet always need `--set mainnet`, and `--set` excludes `--contracts`. A record keeps the set it was registered from (`v2.contractsSet`; an older record is inferred: a forge-meta means `mainnet`, else `devnet`), and a run naming another set is refused, so a four-contract record can never be updated from the three-contract files. On a devnet, `--force-new` without `--only` moves a record to the named set instead: every recorded contract and the group are superseded and a new set is registered in a new group, with the ledger kept (devnet sakura moved to `--set mainnet` this way on 2026-10-17). `--set mainnet --record ` registers the committed set as a scratch rehearsal. Registering into the live testnet or mainnet record refuses, before anything is broadcast, unless the set's files match git HEAD, HEAD is on a branch of origin (so the recorded commit can be fetched), `build.py --check` passes, `--expect-sha256 ` matches every file of the set (sha256sum lines; `--print-sha256`, and every `--dry-run`, print them), every create transition leaves at least 2,000 B under 20,480 B (D44), and the chain id is proved (a DPNS proof that agrees with the node's status) and is the network's (`dash-testnet-` or `evo1`, dashmate's genesis ids); a preflight pass sizes all of them first. A devnet only warns. The set's files are read once, so the sums checked and recorded are of the bytes registered. Testnet and mainnet are reached by SDK discovery only (`--addresses` is refused), and `--devnet-name` is lower-case letters, digits and dashes, so a devnet run never names another network's record. `--force-new` there also needs `--abandon-live-set `: it supersedes the set every client reads. A record of another chain (`chainId`) stops the run; `--replay` then registers the same ids again ("Same-id restore after a Platform reset" below), or `--force-new --abandon-live-set` supersedes every recorded contract and archives the old ledger in `v2.nonceLedgerSuperseded`. - **What the record keeps.** Beside the ids: `network` and `chainId`; per contract `sourceFile`, `sourceSha256` (the file bytes the owner signed), `gitCommit` and `gitCommitPushed`, `registeredSchemaHash` (never changed by an update), `documentsHash` (sha256 of the documentSchemas and schemaDefs with sorted keys, comparable with a fetched contract), `transitionSha256` (the signed transition's bytes; an update records its own), `roomBytes` and `provedAt` (the block metadata of the first proof after confirmation, an upper bound on the registration block: evo-sdk's wait result carries no height); `v2.contractGroup.admins` (must be empty: clients refuse a group with admins, rule 1) and `description`; `v2.deployer` (`identityId`, `assetLockTxid`, `createdAtHeight` from `--deployer-created-height`; a run with another deployer moves the old block to `v2.deployerSuperseded`); and `v2.nonceLedger`, every transition the deployer signed, in order (a create by identity nonce, an update by identity-contract nonce), written before its broadcast and flipped to `registered` / `updated`. A settled entry is never rewritten. A reservation that never landed and whose nonce went elsewhere is `abandoned`. If the chain's identity nonce is past the ledger's last, something else signed with the deployer and the next create stops until `--acknowledge-nonce --note ""` records it as an `external` entry; a nonce that created a contract is refused (it was a create of the deployer's, not an external transition), unless it is the record's own `keyExchange` contract. Update entries are matched by contract as well as nonce (each contract's identity-contract nonce starts at 1). A record is one deployer's: another identity is refused unless it registers a new set (`--force-new` without `--only`), which supersedes every recorded contract and archives the ledger in `v2.nonceLedgerSuperseded` (with `deployer`), as a chain change does. @@ -862,6 +871,8 @@ An update may add only optional properties, `enum` values appended at the end, a **UPDATE-2** (the passkey vault) is one more `DataContractUpdate`, of forge-meta alone: `vaultEntry` (§2, forge-meta), a new type with its own unique index and a `refersTo` to the owner's own authentication key, nothing on an existing type. It is the flag `passkey_vault` (`UPDATE2_FLAGS`, off in the registered v1 set; `stale_registered` turns it off with UPDATE-1's). On a network that is not registered yet (mainnet) it is part of the registration set and changes forge-meta's sha256, which the owner signs again. Testnet (`6arQ…`) and devnet sakura (`4CyD…`) registered forge-meta without it (source `04627b52…`), so there it ships as `deploy-v2.mjs --update meta` (applied on testnet on 2026-10-26, forge-meta version 2; sakura is retired and was not updated) and `contract-validate --expect-update` accepts the new forge-meta as an update of the registered one (`ALLOWED (DataContractUpdate v1 -> v2)`; run by hand against `git show ec3c86f12:forge-contracts/contracts/mainnet/forge-meta.json`, the file sakura registered, since no `registered/devnet-sakura/` copy is frozen for CI). Its vectors (`vaultEntry` cases of the `U2` item: shapes, bounds, the immutable `credentialId` and `recipientKey`, the re-seal, the index) are generated for the four-contract set (`vectors.py --mainnet`), and the committed three-contract vectors only assert that the type is absent there. +**UPDATE-3** (boards, [docs/design/boards.md](../design/boards.md) §3) is the next `DataContractUpdate` of forge-meta alone: `board` and `card` (§2, forge-meta), new types with their own indexes, the member gate `label` has, and `card.item`'s reference to forge-collab's issues and PRs; nothing on an existing type. It is the flag `boards` (`UPDATE3_FLAGS`, off in the registered v1 set with UPDATE-1's and UPDATE-2's), and testnet's `NETWORK_REGISTRATIONS` entry lists it under `since` beside `passkey_vault`, so `registered/testnet/` still matches what testnet registered. On mainnet it is part of the registration set. On testnet it ships as `deploy-v2.mjs --update meta` (forge-meta version 3; the update substitutes every recorded id, forge-collab's included). `contract-validate --expect-update` accepts the new forge-meta as an update of `registered/testnet/forge-meta.v1.json` (CI, `validate-registered.sh`) and of testnet's version 2 (`git show 84d6e2d4:forge-contracts/contracts/mainnet/forge-meta.json`, by hand: `ALLOWED`). The update transition is about 10.9 KB (the contract, 10,842 B, plus the update's framing, which was 71 B for version 2). Its vectors (the `U3` item: shapes and bounds, `noPlain`, `hasName`, `dependentRequired`, the roles, the immutable keys, a move, an archive, a remove, the indexes; the `rClaim` update guards in `--guards`) are generated for the four-contract set, and the committed three-contract vectors assert the types are absent. The member gate, its re-check on a replace and `card.item` are references, judged by the offline chain only (`offline-chain.test.mjs`) until the live suite gains board and card cases, which should run on a scratch set before the testnet update. + **The mixed-visibility items (mainnet only).** dash-forge-qa `design/mixed-visibility/DESIGN.md` rev 4.1 §8.3 adds the layout and eleven items to `MAINNET_FLAGS`, in its order. Each is off in every devnet build and on with `build.py --mainnet`; `build.NEEDS` refuses a combination that cannot register (a `where` naming a property another item adds, or B1 without the room forge-meta leaves). Row numbers are DESIGN §8.2's. A refusal is 10422 (the first broken rule in name order), 40127 (a `where` mismatch) or 40120 (no document found), as M-C checks live. | # | Flag | Item | Contract | What consensus enforces | Until mainnet | diff --git a/docs/deploying-to-a-network.md b/docs/deploying-to-a-network.md index 962a199a6..061b027cc 100644 --- a/docs/deploying-to-a-network.md +++ b/docs/deploying-to-a-network.md @@ -26,7 +26,7 @@ Four contracts, in one contract group (`dash-forge`) that has an owner and **no | 1 | `forge-core` | repositories, members (`writer`, `maintainer`, `consent`), packs, refs, releases, config, `pushGrant`. Its create transition also creates the contract group. | | 2 | `forge-collab` | issues, pull requests, reviews, comments, transitions | | 3 | `forge-community` | `authorEvent`, `checkRun`, `event`, `milestone`, `policy`, `runner`, `star`, `watch`, `webhook` | -| 4 | `forge-meta` | `ban`, `follow`, `label`, `packMirror`, `profile`, `repoKey`, `topic`, `vaultEntry` ([forge-v2.md §2](contracts/forge-v2.md#forge-meta-mainnet-set-only)) | +| 4 | `forge-meta` | `ban`, `board`, `card`, `follow`, `label`, `packMirror`, `profile`, `repoKey`, `topic`, `vaultEntry` ([forge-v2.md §2](contracts/forge-v2.md#forge-meta-mainnet-set-only)) | The order is fixed. Each contract takes the deployer's next identity nonce, the contract and group ids derive from those nonces, and each later contract's schema names the ids of the ones registered before it. [forge-v2.md §8](contracts/forge-v2.md#8-deploying) has the details. diff --git a/docs/limits.md b/docs/limits.md index b55ecffe7..1c3570834 100644 --- a/docs/limits.md +++ b/docs/limits.md @@ -18,6 +18,8 @@ What Forge cannot hold or do, in numbers, with where each number comes from. Som | A pack | **1 TiB**: the cap on the size a manifest records (**frozen**). Forge's tools add no smaller cap; on Platform a pack is split over as many chunks as it needs, each costing about 0.005 DASH | [forge-v2.md §9](contracts/forge-v2.md#9-frozen-at-mainnet); [Costs](guides/costs.md) | | A contract (registration) | 20,480 bytes, and at least 2,000 bytes of headroom under that for the create transition | `deploy-v2.mjs` | | A passkey vault entry (`vaultEntry`) | credential id 16 to 255 bytes, recipient key 32, encapsulated key 32, sealed bundle 32 to 256 (Forge writes 256). An update can loosen the sealed bundle's bounds but never make it fixed-length, and cannot take the credential id past 255 bytes or `version` past 255 (**frozen**). One entry per identity and credential. Fees measured on testnet: about 43 to 52 million credits (about 0.0005 DASH) for an identity's first entry, 33 million for a later one, 3 million to re-seal; a delete refunds about 27 to 37 million, and a sign-in reads only | [forge-v2.md §2](contracts/forge-v2.md#forge-meta-mainnet-set-only) | +| A board (`board`, forge-meta) | name 1 to 63 characters (252 bytes), definition 4,096 bytes of JSON, sealed 5,120 bytes; one definition per member and board. The board key stays a u32 and only maintainers and writers define boards (**frozen**); the size bounds can be loosened by an update | [forge-v2.md §2](contracts/forge-v2.md#forge-meta-mainnet-set-only); [Boards](design/boards.md#8-limits) | +| A card (`card`, forge-meta) | column 0 to 255, rank 1 to 63 base-62 digits, field values 2,048 bytes of JSON, sealed 2,560 bytes; one card per member, item and board. A card always names an issue or a PR, and only the board's home repository's members write one (**frozen**) | same | | Keys in a passkey vault entry | at most **6**: the main key (a group-bound limited key with a budget and an expiry), up to 4 per-contract wallet grants (each also with a budget and an expiry: an unlimited one stays on its device) and one encryption key (only if asked). At most **10 passkeys** per identity | [Passkey vault](security/passkey-vault.md#what-an-entry-holds) | | Pack download time | each copy gets `max(120 s, size ÷ 1 MiB/s)`; a manifest with no size allows 256 MiB | [Bring your own storage](guides/bring-your-own-storage.md) | | Read-back check after an upload | a full download and SHA-256 up to 16 MiB; larger packs get a size check and byte-exact head and tail ranges | same | diff --git a/docs/security/private-repos.md b/docs/security/private-repos.md index 559dc6b73..b51c54cdf 100644 --- a/docs/security/private-repos.md +++ b/docs/security/private-repos.md @@ -249,7 +249,7 @@ The plaintext is a sequence of records `tag(u8) ‖ len(u16) ‖ value`. No JSON AD = "dash-forge/v2/doc" ‖ 0x00 ‖ enc[0] ‖ repoId(32) ‖ $ownerId(32) ‖ u32(epoch) ‖ docType(ASCII) ‖ 0x00 ‖ bind ``` -`enc[0]` is the version byte (`0x01` to `0x04`), so a ciphertext cannot be re-framed under another version. A specific-people letter (v0x04) has no epoch keys: its AD is built from `repoId` alone with the literal `epoch = 0`, and is then extended to `AD'` by `SHA-256(H)` (§4.1); a config, whose bind is `COMMIT_e`, has no such AD. `docType` is the contract's type name (`issue`, `patch`, `comment`, `review`, `event`, `authorEvent`, `refUpdate`, `protectedRefUpdate`, `config`, `release`). An `authorEvent` (an issue's or PR's author's own event) is sealed only where the contract declares `authorEvent.enc` (mainnet M3): its value (a retarget's new base) is TLV 15 as an event's, never a head (`private_collab_seal__author_event_retarget`). `bind` is the type's immutable plaintext identity: +`enc[0]` is the version byte (`0x01` to `0x04`), so a ciphertext cannot be re-framed under another version. A specific-people letter (v0x04) has no epoch keys: its AD is built from `repoId` alone with the literal `epoch = 0`, and is then extended to `AD'` by `SHA-256(H)` (§4.1); a config, whose bind is `COMMIT_e`, has no such AD. `docType` is the contract's type name (`issue`, `patch`, `comment`, `review`, `event`, `authorEvent`, `refUpdate`, `protectedRefUpdate`, `config`, `release`, and forge-meta's `board` and `card`, UPDATE-3). An `authorEvent` (an issue's or PR's author's own event) is sealed only where the contract declares `authorEvent.enc` (mainnet M3): its value (a retarget's new base) is TLV 15 as an event's, never a head (`private_collab_seal__author_event_retarget`). `bind` is the type's immutable plaintext identity: | type | bind | |---|---| @@ -259,8 +259,10 @@ AD = "dash-forge/v2/doc" ‖ 0x00 ‖ enc[0] ‖ repoId(32) ‖ $ownerId(32) ‖ | refUpdate, protectedRefUpdate | `refNameHash` (32) ‖ `oidf(newOid)` ‖ `oidf(prevOid or empty)` ‖ `force` (0x00/0x01) | | config | `COMMIT_e` (32) | | release | the document's `tagName` string, as its 43 ASCII bytes (§16.2) | +| board | `u32(key)` (the board's `name` and `spec` sealed together; [boards.md](../design/boards.md) §3.3) | +| card | `u32(board)` ‖ `item` (32) (the card's `col`, `rank` and `f` sealed; its `state` stays plaintext) | -`oidf(x) = u8(len(x)) ‖ x`. Binding `repoId`, `$ownerId`, `epoch` and the type means a ciphertext lifted from one document cannot be replayed as another: not by an outsider into a new comment in the same repo (different `$ownerId`), not into another repo, not under another type or epoch. `$ownerId` is safe to bind because these nine types are not transferable; making one transferable would be a breaking change to this design. The ref-update binding ties the hidden name to the visible tip, so a stored `enc` cannot be re-used to name a different ref for the same OID. The document's `$id`, `$createdAt` and `$createdAtBlockHeight` are not bound (unknown at encryption time). +`oidf(x) = u8(len(x)) ‖ x`. Binding `repoId`, `$ownerId`, `epoch` and the type means a ciphertext lifted from one document cannot be replayed as another: not by an outsider into a new comment in the same repo (different `$ownerId`), not into another repo, not under another type or epoch. `$ownerId` is safe to bind because none of these types is transferable; making one transferable would be a breaking change to this design. The ref-update binding ties the hidden name to the visible tip, so a stored `enc` cannot be re-used to name a different ref for the same OID. A board's or a card's binding is its immutable keys, so a sealed payload cannot be moved to another board or item; both are mutable, and a member's edit re-seals the whole payload under the repository's current epoch (a card is one document per member, item and board, so a replace is its only way to change). The document's `$id`, `$createdAt` and `$createdAtBlockHeight` are not bound (unknown at encryption time). ### 4.5 Ref-name hashing, and the hash check on read diff --git a/forge-contracts/contracts/mainnet/forge-meta.json b/forge-contracts/contracts/mainnet/forge-meta.json index e5bb9c179..9cf56ef0c 100644 --- a/forge-contracts/contracts/mainnet/forge-meta.json +++ b/forge-contracts/contracts/mainnet/forge-meta.json @@ -748,6 +748,355 @@ "sealed" ], "additionalProperties": false + }, + "board": { + "type": "object", + "documentsMutable": true, + "canBeDeleted": false, + "ownerRefersTo": { + "anyOf": [ + { + "type": "deletableDocument", + "contractId": "FORGE_CORE_CONTRACT_ID", + "documentType": "maintainer", + "findBy": { + "repoId": "repoId", + "memberId": "." + } + }, + { + "type": "deletableDocument", + "contractId": "FORGE_CORE_CONTRACT_ID", + "documentType": "writer", + "findBy": { + "repoId": "repoId", + "memberId": "." + }, + "where": { + "role": "r" + } + } + ] + }, + "properties": { + "repoId": { + "$ref": "#/$defs/id", + "position": 0 + }, + "key": { + "type": "integer", + "minimum": 1, + "maximum": 4294967295, + "position": 1 + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 63, + "maxBytes": 252, + "pattern": "^[^\\x00-\\x1f\\x7f]*[^\\s\\x00-\\x1f\\x7f][^\\x00-\\x1f\\x7f]*$", + "position": 2 + }, + "spec": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "maxBytes": 4096, + "position": 3 + }, + "state": { + "type": "integer", + "minimum": 0, + "maximum": 2, + "position": 4 + }, + "enc": { + "type": "array", + "byteArray": true, + "minItems": 29, + "maxItems": 5120, + "position": 5 + }, + "epoch": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295, + "position": 6 + }, + "r": { + "type": "integer", + "minimum": 1, + "maximum": 1, + "position": 7 + } + }, + "immutable": [ + "repoId", + "key" + ], + "indices": [ + { + "name": "byKey", + "properties": [ + { + "repoId": "asc" + }, + { + "key": "asc" + }, + { + "$ownerId": "asc" + } + ], + "unique": true + } + ], + "required": [ + "$createdAt", + "$updatedAt", + "repoId", + "key", + "state", + "r" + ], + "additionalProperties": false, + "dependentRequired": { + "enc": [ + "epoch" + ] + }, + "propertyConstraints": { + "noPlain": { + "anyOf": [ + { + "absent": "enc" + }, + { + "allOf": [ + { + "absent": "name" + }, + { + "absent": "spec" + } + ] + } + ] + }, + "hasName": { + "anyOf": [ + { + "present": "enc" + }, + { + "allOf": [ + { + "present": "name" + }, + { + "present": "spec" + } + ] + } + ] + }, + "rClaim": { + "equal": [ + "r", + 1 + ] + } + } + }, + "card": { + "type": "object", + "documentsMutable": true, + "canBeDeleted": false, + "ownerRefersTo": { + "anyOf": [ + { + "type": "deletableDocument", + "contractId": "FORGE_CORE_CONTRACT_ID", + "documentType": "maintainer", + "findBy": { + "repoId": "repoId", + "memberId": "." + } + }, + { + "type": "deletableDocument", + "contractId": "FORGE_CORE_CONTRACT_ID", + "documentType": "writer", + "findBy": { + "repoId": "repoId", + "memberId": "." + }, + "where": { + "role": "r" + } + } + ] + }, + "properties": { + "repoId": { + "$ref": "#/$defs/id", + "position": 0 + }, + "board": { + "type": "integer", + "minimum": 1, + "maximum": 4294967295, + "position": 1 + }, + "item": { + "type": "identifier", + "refersTo": { + "anyOf": [ + { + "type": "permanentDocument", + "contractId": "FORGE_COLLAB_CONTRACT_ID", + "documentType": "issue" + }, + { + "type": "permanentDocument", + "contractId": "FORGE_COLLAB_CONTRACT_ID", + "documentType": "patch" + } + ] + }, + "position": 2 + }, + "col": { + "type": "integer", + "minimum": 0, + "maximum": 255, + "position": 3 + }, + "rank": { + "type": "string", + "minLength": 1, + "maxLength": 63, + "pattern": "^[0-9A-Za-z]*[1-9A-Za-z]$", + "position": 4 + }, + "f": { + "type": "string", + "minLength": 1, + "maxLength": 2048, + "maxBytes": 2048, + "position": 5 + }, + "state": { + "type": "integer", + "minimum": 0, + "maximum": 2, + "position": 6 + }, + "enc": { + "type": "array", + "byteArray": true, + "minItems": 29, + "maxItems": 2560, + "position": 7 + }, + "epoch": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295, + "position": 8 + }, + "r": { + "type": "integer", + "minimum": 1, + "maximum": 2, + "position": 9 + } + }, + "immutable": [ + "repoId", + "board", + "item" + ], + "indices": [ + { + "name": "onItem", + "properties": [ + { + "item": "asc" + }, + { + "repoId": "asc" + }, + { + "board": "asc" + }, + { + "$ownerId": "asc" + } + ], + "unique": true + }, + { + "name": "recent", + "properties": [ + { + "repoId": "asc" + }, + { + "board": "asc" + }, + { + "$updatedAt": "asc" + } + ] + } + ], + "required": [ + "$createdAt", + "$updatedAt", + "repoId", + "board", + "item", + "state", + "r" + ], + "additionalProperties": false, + "dependentRequired": { + "enc": [ + "epoch" + ] + }, + "propertyConstraints": { + "noPlain": { + "anyOf": [ + { + "absent": "enc" + }, + { + "allOf": [ + { + "absent": "col" + }, + { + "absent": "rank" + }, + { + "absent": "f" + } + ] + } + ] + }, + "rClaim": { + "in": [ + "r", + [ + 1, + 2 + ] + ] + } + } } }, "config": { diff --git a/forge-contracts/schema/build.py b/forge-contracts/schema/build.py index a7fc4abb7..9a9c73503 100644 --- a/forge-contracts/schema/build.py +++ b/forge-contracts/schema/build.py @@ -155,12 +155,18 @@ # (META_TYPES): on a registered network it ships as `deploy-v2.mjs --update meta`, on one not yet # registered it is part of the registration set. passkey_vault=True, # vaultEntry: a passkey-sealed key bundle per (owner, credential id) + # ---- UPDATE-3 (boards, docs/design/boards.md §3): two new document types only, as UPDATE-2. Four-contract + # set only (`layout_meta`), moved to forge-meta by META_TYPES; `deploy-v2.mjs --update meta` on a + # registered network (forge-meta v3 on testnet), part of the registration set elsewhere. + boards=True, # board (a board's definition) and card (a member's placement of one item) ) # The UPDATE-1 items: every one off is the registered v1 set (registered/*.v1.json). UPDATE1_FLAGS = ('release_target_oid', 'config_moved_to', 'pack_mirror', 'transition_closed_by_pr', 'profile_key_proofs', 'profile_bot', 'author_retarget', 'policy_code_owners', 'repo_ban') # The UPDATE-2 items: added after UPDATE-1, so the registered v1 set has them off too (stale_registered). UPDATE2_FLAGS = ('passkey_vault',) +# The UPDATE-3 items: added after UPDATE-2, off in the registered v1 set too (stale_registered). +UPDATE3_FLAGS = ('boards',) # Each production network's registration (CONT-03): the committed set it registered, and the flags added after # it. `contracts/registered//.v1.json` is a byte copy of what that network registered # (`freeze-registered.mjs` writes it at the registration commit, P4) and the build with the `since` flags off @@ -171,7 +177,7 @@ # registration; a flag that was on and is later turned off cannot be expressed (--check fails loudly). NETWORK_REGISTRATIONS = { # testnet (dash-testnet-51), Platform 5.0.0-rc.8, 2026-10-26: forge-core D2ZLdgghZTKGpES35a3KVDp5necSfZqqRHLSknjRPAV9 - 'testnet': {'set': 'mainnet', 'since': ('passkey_vault',)}, + 'testnet': {'set': 'mainnet', 'since': ('passkey_vault', 'boards')}, } # ---- Mainnet-only (a fresh registration may add them; an update never can: rules, references and # required fields on existing types are frozen, forge-v2.md §9). Off in every devnet build; the mainnet @@ -308,7 +314,7 @@ GRANT_TTL_MS = 90 * 24 * 3600 * 1000 # D44: the types forge-meta takes, from the contract that holds them in the three-contract set META_TYPES = {'forge-collab': ('repoKey', 'ban'), 'forge-core': ('label', 'topic', 'packMirror'), - 'forge-community': ('profile', 'follow', 'vaultEntry')} + 'forge-community': ('profile', 'follow', 'vaultEntry', 'board', 'card')} # The riders: independent of the RC2 items (other types and properties), so variants.py turns # each off only with every RC2 item on, the largest build. RIDER_FLAGS = ('close_reason', 'review_hunk') @@ -1016,6 +1022,87 @@ def writer_leaf(t): "required": ["$createdAt", "$updatedAt", "credentialId", "recipientKey", "version", "authKeyId", "enc", "sealed"], "additionalProperties": False} + # ======================= UPDATE-3 (boards, docs/design/boards.md §3) ======================= + # Two new document types with their own indexes, so protocol 14 lets an update add them, as UPDATE-2. + # Built with the four-contract layout only and moved to forge-meta (META_TYPES): their references name + # forge-core (the member gate) and forge-collab (the item) by id, which only a later contract may. + # Both are mutable and never deleted, one document per (member, board[, item]): a member's later write + # replaces their own (a replace costs a fraction of a create) and readers take the newest across + # members. A delete would silently bring back an older member's document, which no poll of + # `$updatedAt` sees, and a removed member could still delete theirs, so `state` 2 is the delete. Every + # index key and both timestamps are required: an unrequired `$updatedAt` is never recorded, and a unique + # index holds no document missing a key part. The gate is label's: a maintainer of the home repo, or a + # writer whose role is the claimed `r`; a `deletableDocument` found by `findBy` is asked again on every + # replace (book contract-keywords/owner-refers-to.md "On replace"), so a removed member cannot touch + # their old documents and a role change holds from the next write. No `ownerRefersTo` operand can be + # added by a later update (§9): only the home repo's members write, and a card always names an issue or + # a PR. `enc` is inlined in both: forge-meta's `$defs.enc` (label's, 1,536 B) is too small for a board. + if up['boards'] and f['layout_meta']: + if not f['member_roles']: # (not in NEEDS: the three-contract builds have `boards` on and no forge-meta) + sys.exit('boards needs member_roles: the writer leaf proves `r` against writer.role') + u32 = {"type": "integer", "minimum": 0, "maximum": 4294967295} + key = {"type": "integer", "minimum": 1, "maximum": 4294967295} + gate = {"anyOf": [find_leaf("maintainer", CORE), dict(find_leaf("writer", CORE), where={"role": "r"})]} + # A board's definition, one per (home repo, key, member): `name` and `spec` (§2, JSON, `v: 1`) in a + # public repo, sealed together in `enc` in a private one (bound to `u32(key)`, private-repos.md §4.4). + # `state` 0 open, 1 closed, 2 deleted. Maintainers and role-1 writers define boards (r = 1). + md['board'] = { + "type": "object", "documentsMutable": True, "canBeDeleted": False, + "ownerRefersTo": copy.deepcopy(gate), + "properties": { + "repoId": {"$ref": "#/$defs/id", "position": 0}, + "key": dict(key, position=1), + "name": {"type": "string", "minLength": 1, "maxLength": 63, "maxBytes": 252, "pattern": TITLE, "position": 2}, + "spec": {"type": "string", "minLength": 1, "maxLength": 4096, "maxBytes": 4096, "position": 3}, + "state": {"type": "integer", "minimum": 0, "maximum": 2, "position": 4}, + "enc": {"type": "array", "byteArray": True, "minItems": 29, "maxItems": 5120, "position": 5}, + "epoch": dict(u32, position=6), + "r": {"type": "integer", "minimum": 1, "maximum": 1, "position": 7}}, + "immutable": ["repoId", "key"], + "indices": [ + # One definition per (repo, board, member); the repoId prefix lists a repo's boards + {"name": "byKey", "properties": [{"repoId": "asc"}, {"key": "asc"}, {"$ownerId": "asc"}], "unique": True}], + "required": ["$createdAt", "$updatedAt", "repoId", "key", "state", "r"], + "additionalProperties": False, + "dependentRequired": {"enc": ["epoch"]}, + "propertyConstraints": { + "noPlain": {"anyOf": [{"absent": "enc"}, {"allOf": [{"absent": "name"}, {"absent": "spec"}]}]}, + "hasName": {"anyOf": [{"present": "enc"}, {"allOf": [{"present": "name"}, {"present": "spec"}]}]}}} + # A member's placement and field values for one item on one board: `col` (0 = none), `rank` (§2.6, + # base-62, never ending in `0`) and `f` (JSON field values) in a public repo, sealed in `enc` in a + # private one (bound to `u32(board) ‖ item`). `item` is any repository's issue or PR (no `where`). + # `state` 0 active, 1 archived, 2 removed, plaintext everywhere. Maintainers, writers and triage + # place cards (r 1-2). + md['card'] = { + "type": "object", "documentsMutable": True, "canBeDeleted": False, + "ownerRefersTo": copy.deepcopy(gate), + "properties": { + "repoId": {"$ref": "#/$defs/id", "position": 0}, + "board": dict(key, position=1), + "item": ident(refersTo={"anyOf": [ + {"type": "permanentDocument", "contractId": COLLAB, "documentType": "issue"}, + {"type": "permanentDocument", "contractId": COLLAB, "documentType": "patch"}]}, position=2), + "col": {"type": "integer", "minimum": 0, "maximum": 255, "position": 3}, + "rank": {"type": "string", "minLength": 1, "maxLength": 63, "pattern": "^[0-9A-Za-z]*[1-9A-Za-z]$", + "position": 4}, + "f": {"type": "string", "minLength": 1, "maxLength": 2048, "maxBytes": 2048, "position": 5}, + "state": {"type": "integer", "minimum": 0, "maximum": 2, "position": 6}, + "enc": {"type": "array", "byteArray": True, "minItems": 29, "maxItems": 2560, "position": 7}, + "epoch": dict(u32, position=8), + "r": {"type": "integer", "minimum": 1, "maximum": 2, "position": 9}}, + "immutable": ["repoId", "board", "item"], + "indices": [ + # One card per (item, board, member); the item prefix answers "which boards is this on" + {"name": "onItem", "properties": [{"item": "asc"}, {"repoId": "asc"}, {"board": "asc"}, {"$ownerId": "asc"}], + "unique": True}, + # Load a board, and poll it for what changed since a time + {"name": "recent", "properties": [{"repoId": "asc"}, {"board": "asc"}, {"$updatedAt": "asc"}]}], + "required": ["$createdAt", "$updatedAt", "repoId", "board", "item", "state", "r"], + "additionalProperties": False, + "dependentRequired": {"enc": ["epoch"]}, + "propertyConstraints": { + "noPlain": {"anyOf": [{"absent": "enc"}, {"allOf": [{"absent": "col"}, {"absent": "rank"}, {"absent": "f"}]}]}}} + # ======================= mixed visibility (DESIGN rev 4.1 §8.3) ======================= # A fresh registration only: each adds a rule, a reference or a required field to a type that # exists, which no update can (§9). Row numbers are DESIGN §8.2's; forge-v2.md §9.1 has each. @@ -1342,6 +1429,9 @@ def public_const(t, stamp_rule=None): for t in (ev_home['event'], ev_home['milestone'], cd['label']): t.setdefault('propertyConstraints', {})['rClaim'] = {"in": ["r", [1, 2]]} md['checkRun']['propertyConstraints']['rClaim'] = {"equal": ["r", 1]} + if 'board' in md: # UPDATE-3: role-1 writers define boards, triage places cards too + md['board']['propertyConstraints']['rClaim'] = {"equal": ["r", 1]} + md['card']['propertyConstraints']['rClaim'] = {"in": ["r", [1, 2]]} rk_home['repoKey'].setdefault('propertyConstraints', {})['mrClaim'] = {"in": ["mr", [1, 2, 3]]} # The push class is bounded by B1's own rules (botGrant, botPack, botChunk); a build without B1 # bounds each claim by its schema range instead @@ -1585,11 +1675,11 @@ def stale_registered(registered_root, registrations): or an entry with no directory, is stale: what a network registered is frozen in the same commit that names it.""" stale = [] - v1 = build(flags_from(','.join(UPDATE1_FLAGS + UPDATE2_FLAGS))) + v1 = build(flags_from(','.join(UPDATE1_FLAGS + UPDATE2_FLAGS + UPDATE3_FLAGS))) for n in NAMES: p = os.path.join(registered_root, f'{n}.v1.json') if not os.path.exists(p) or open(p).read() != dumps(v1[n]): - stale.append((p, 'is not the build with every UPDATE-1 and UPDATE-2 flag off')) + stale.append((p, 'is not the build with every UPDATE-1, UPDATE-2 and UPDATE-3 flag off')) dirs = sorted(d for d in os.listdir(registered_root) if os.path.isdir(os.path.join(registered_root, d))) \ if os.path.isdir(registered_root) else [] for d in dirs: diff --git a/forge-contracts/schema/vectors.py b/forge-contracts/schema/vectors.py index 0237f0cd8..48a63255a 100644 --- a/forge-contracts/schema/vectors.py +++ b/forge-contracts/schema/vectors.py @@ -931,6 +931,101 @@ def sealed_release(name): else: index('U2', 'no vaultEntry type', 'vaultEntry', None, False) +# ---------------- UPDATE-3: boards (docs/design/boards.md §3) ---------------- +# The shapes, the plaintext/sealed rules and the frozen keys. The member gate (a maintainer, or a writer of +# the claimed role), its re-check on a replace and `card.item` naming an issue or a PR are references, judged +# by the offline chain (scripts/lib/offline-chain.test.mjs); no live suite case covers them yet. +CONTRACT_OF.update(board='forge-community', card='forge-community') +if F['boards'] and F['layout_meta']: # (build.py builds them with the four-contract layout only) + BASE['board'] = {"repoId": i(1), "key": 1, "name": "Roadmap", "spec": '{"v":1,"cols":[{"id":1,"name":"Todo"}]}', + "state": 0, "r": 1} + BASE['card'] = {"repoId": i(1), "board": 1, "item": i(2), "col": 1, "rank": "V", "f": '{"1":3}', "state": 0, "r": 1} + for _t in ('board', 'card'): + ok('base', f'{_t} ok', _t) + # board + ok('U3', 'a sealed board', 'board', name=DROP, spec=DROP, **SEALED) + ok('U3', 'a closed board', 'board', state=1) + ok('U3', 'a deleted board', 'board', state=2) + no('U3', 'a board in state 3', 'board', 'maximum', state=3) + ok('U3', 'board key 4294967295', 'board', key=4294967295) + no('U3', 'board key 0', 'board', 'minimum', key=0) + no('U3', 'board key 4294967296', 'board', 'maximum', key=4294967296) + no('U3', 'a board claiming role 2 (triage defines no board)', 'board', 'maximum', r=2) + no('U3', 'a board claiming role 0', 'board', 'minimum', r=0) + no('U3', 'a sealed board with a plaintext name', 'board', 'noPlain', spec=DROP, **SEALED) + no('U3', 'a sealed board with a plaintext definition', 'board', 'noPlain', name=DROP, **SEALED) + no('U3', 'a plaintext board without a name', 'board', 'hasName', name=DROP) + no('U3', 'a plaintext board without a definition', 'board', 'hasName', spec=DROP) + no('U3', 'a sealed board without its epoch', 'board', 'required', name=DROP, spec=DROP, enc=b(5, 61)) + ok('U3', 'a board name of 63 four-byte characters', 'board', name='\U0001F600' * 63) + no('U3', 'a board name of 64 characters', 'board', 'maxLength', name='x' * 64) + no('U3', 'an empty board name', 'board', 'minLength', name='') + no('U3', 'a board name of spaces', 'board', 'pattern', name=' ') + no('U3', 'a board name with a control character', 'board', 'pattern', name='a\nb') + ok('U3', 'a definition of 4096 bytes', 'board', spec='x' * 4096) + no('U3', 'a definition of 4097 characters', 'board', 'maxLength', spec='x' * 4097) + no('U3', 'a definition over 4096 bytes', 'board', 'maxBytes', spec='é' * 2049) + ok('U3', 'a sealed board of 5120 bytes', 'board', name=DROP, spec=DROP, enc=b(5, 5120), epoch=0) + no('U3', 'a board enc of 28 bytes', 'board', 'minItems', name=DROP, spec=DROP, enc=b(5, 28), epoch=0) + no('U3', 'a board enc over the 5120-byte field limit', 'board', '10417', name=DROP, spec=DROP, enc=b(5, 5121), epoch=0) + for _p in ('repoId', 'key', 'state', 'r'): + no('U3', f'a board without {_p}', 'board', 'required', **{_p: DROP}) + no('U3', 'a board with another property', 'board', 'additionalProperties', color='#00ff00') + _STORED = doc('board') + replace('U3', 'a board renamed, redefined and closed', 'board', _STORED, None, name='Plan', spec='{"v":1}', state=1) + replace('U3', 'a board deleted (state 2)', 'board', _STORED, None, state=2) + replace('U3', 'board key changed (immutable)', 'board', _STORED, '40128', key=2) + replace('U3', 'board repoId changed (immutable)', 'board', _STORED, '40128', repoId=i(3)) + index('U3', "one definition per repo, board and member; a repo's boards by its prefix", 'board', 'byKey', True, + properties=['repoId', 'key', '$ownerId'], unique=True) + # card + ok('U3', 'a sealed card', 'card', col=DROP, rank=DROP, f=DROP, **SEALED) + ok('U3', 'a card with no column, rank or fields', 'card', col=DROP, rank=DROP, f=DROP) + ok('U3', 'an archived card', 'card', state=1) + ok('U3', 'a removed card', 'card', state=2) + no('U3', 'a card in state 3', 'card', 'maximum', state=3) + ok('U3', 'a triage card (role 2)', 'card', r=2) + no('U3', 'a card claiming role 3 (a reader places nothing)', 'card', 'maximum', r=3) + no('U3', 'a card claiming role 0', 'card', 'minimum', r=0) + no('U3', 'a sealed card with a plaintext column', 'card', 'noPlain', rank=DROP, f=DROP, **SEALED) + no('U3', 'a sealed card with a plaintext rank', 'card', 'noPlain', col=DROP, f=DROP, **SEALED) + no('U3', 'a sealed card with plaintext field values', 'card', 'noPlain', col=DROP, rank=DROP, **SEALED) + no('U3', 'a sealed card without its epoch', 'card', 'required', col=DROP, rank=DROP, f=DROP, enc=b(5, 61)) + ok('U3', 'column 255', 'card', col=255) + no('U3', 'column 256', 'card', 'maximum', col=256) + no('U3', 'column -1', 'card', 'minimum', col=-1) + no('U3', 'card board key 0', 'card', 'minimum', board=0) + ok('U3', 'a rank of 63 digits', 'card', rank='z' * 63) + ok('U3', 'a rank of one digit 1', 'card', rank='1') + no('U3', 'a rank of 64 digits', 'card', 'maxLength', rank='z' * 64) + no('U3', 'an empty rank', 'card', 'minLength', rank='') + no('U3', 'a rank ending in 0', 'card', 'pattern', rank='V0') + no('U3', 'a rank of 0 alone', 'card', 'pattern', rank='0') + no('U3', 'a rank outside the 62 digits', 'card', 'pattern', rank='a-b') + ok('U3', 'field values of 2048 bytes', 'card', f='x' * 2048) + no('U3', 'field values of 2049 characters', 'card', 'maxLength', f='x' * 2049) + no('U3', 'field values over 2048 bytes', 'card', 'maxBytes', f='é' * 1025) + ok('U3', 'a sealed card of 2560 bytes', 'card', col=DROP, rank=DROP, f=DROP, enc=b(5, 2560), epoch=0) + no('U3', 'a card enc of 28 bytes', 'card', 'minItems', col=DROP, rank=DROP, f=DROP, enc=b(5, 28), epoch=0) + no('U3', 'a card enc of 2561 bytes', 'card', 'maxItems', col=DROP, rank=DROP, f=DROP, enc=b(5, 2561), epoch=0) + for _p in ('repoId', 'board', 'item', 'state', 'r'): + no('U3', f'a card without {_p}', 'card', 'required', **{_p: DROP}) + no('U3', 'a card with another property', 'card', 'additionalProperties', note='hi') + _STORED = doc('card') + replace('U3', 'a card moved and re-ranked', 'card', _STORED, None, col=2, rank='Vk') + replace('U3', 'a card archived', 'card', _STORED, None, state=1) + replace('U3', 'a card removed', 'card', _STORED, None, state=2) + replace('U3', 'card item changed (immutable)', 'card', _STORED, '40128', item=i(3)) + replace('U3', 'card board changed (immutable)', 'card', _STORED, '40128', board=2) + replace('U3', 'card repoId changed (immutable)', 'card', _STORED, '40128', repoId=i(3)) + index('U3', 'one card per item, board and member; the boards an item is on by its prefix', 'card', 'onItem', True, + properties=['item', 'repoId', 'board', '$ownerId'], unique=True) + index('U3', "a board's cards, changed since a time", 'card', 'recent', True, + properties=['repoId', 'board', '$updatedAt'], unique=False) +else: + for _t in ('board', 'card'): + index('U3', f'no {_t} type', _t, None, False) + # ---------------- the other mainnet-only rules (forge-v2.md §9.1) ---------------- if F['mainnet_release_target']: no('MN', 'a public publish without targetOid', 'release', 'targetOnPublish', targetOid=DROP) @@ -1159,7 +1254,9 @@ def sealed_release(name): UPDATE_GUARDS = {('transition', 'k_kinds'), ('checkRun', 'rClaim'), ('event', 'rClaim'), ('milestone', 'rClaim'), ('label', 'rClaim'), ('repoKey', 'mrClaim'), # a build without B1 (variants only): the push class's claims - ('refUpdate', 'rClaim'), ('packManifest', 'rClaim'), ('chunk', 'rClaim')} + ('refUpdate', 'rClaim'), ('packManifest', 'rClaim'), ('chunk', 'rClaim'), + # UPDATE-3: role-1 writers define boards, triage places cards too + ('board', 'rClaim'), ('card', 'rClaim')} def uncovered(): @@ -1184,6 +1281,8 @@ def uncovered(): ('label', 'r', {'maximum': 4}, 3, 'rClaim'), ('checkRun', 'r', {'maximum': 4}, 2, 'rClaim'), ('repoKey', 'mr', {'maximum': 4}, 4, 'mrClaim')] +if 'board' in BASE: + GUARD_LOOSENINGS += [('board', 'r', {'maximum': 4}, 2, 'rClaim'), ('card', 'r', {'maximum': 4}, 3, 'rClaim')] def guard_check(out): diff --git a/forge-contracts/scripts/deploy-v2.mjs b/forge-contracts/scripts/deploy-v2.mjs index e06fcb7f5..bf0a9f011 100644 --- a/forge-contracts/scripts/deploy-v2.mjs +++ b/forge-contracts/scripts/deploy-v2.mjs @@ -100,6 +100,7 @@ // // forge-meta (DESIGN rev 4.1 D44): when holds forge-meta.json it is registered fourth, after // forge-community, like the others: its schema names forge-core's id (FORGE_CORE_CONTRACT_ID), and +// with boards (UPDATE-3) forge-collab's (FORGE_COLLAB_CONTRACT_ID: a card names an issue or a PR), and // its create transition enrols it in the group. `--only meta` registers it alone against the // recorded forge-core and group (an earlier run that registered the three). // @@ -128,6 +129,8 @@ // community do the same for forge-collab and forge-community (the recorded ids replace their // placeholders), and --update all updates the three in registration order (UPDATE-1, roadmap D4; // check each with contract-validate --expect-update registered/.v1.json first). +// --update meta updates forge-meta alone, with every recorded id substituted (UPDATE-2's vaultEntry +// names none; UPDATE-3's board and card name forge-core and forge-collab). // // --force-new without --only does the same for the set: when the recorded forge-core was // registered from a different schema (a change such as a new `required` system field, which the @@ -316,6 +319,11 @@ function selfTest(dir = DEFAULT_CONTRACTS_DIR, log = defaultLog) { if (!schemaText('forge-community', dir).includes(placeholderFor('forge-collab'))) { throw new Error('forge-community names no FORGE_COLLAB_CONTRACT_ID: its events would not refer to this forge-collab'); } + // UPDATE-3: a card names any repository's issue or PR, so a forge-meta with cards names forge-collab + if (dependents.includes(META_CONTRACT) && JSON.parse(schemaText(META_CONTRACT.schemaName, dir)).documentSchemas.card + && !schemaText(META_CONTRACT.schemaName, dir).includes(placeholderFor('forge-collab'))) { + throw new Error('forge-meta names no FORGE_COLLAB_CONTRACT_ID: its cards would not refer to this forge-collab'); + } const ids = { [PLACEHOLDER]: want.contract }; for (const { schemaName } of dependents) { const raw = schemaText(schemaName, dir); @@ -1521,7 +1529,7 @@ async function deploy(argv, injected, locks) { return id; } - // --update : an in-place DataContractUpdate of each recorded contract + // --update : an in-place DataContractUpdate of each recorded contract // to its current schema, as the next version (in registration order: core, collab, community). // Returns the step to report; resumable (see the header). async function updateContract({ key, schemaName, substitutions }) { diff --git a/forge-contracts/scripts/deploy-v2.test.mjs b/forge-contracts/scripts/deploy-v2.test.mjs index 2e32ff40e..2459ecdd8 100644 --- a/forge-contracts/scripts/deploy-v2.test.mjs +++ b/forge-contracts/scripts/deploy-v2.test.mjs @@ -530,6 +530,29 @@ test('--update core on a production record: the contract-nonce ledger entry, reg await assert.rejects(t.run(t.prod('--update', 'core')), /differ from git HEAD/); }); +test('--update meta names the recorded forge-core and forge-collab (UPDATE-3: card.item refers to forge-collab)', async () => { + const t = setup(); + await t.run(t.prod()); + const { forgeCore, forgeCollab, forgeMeta } = t.read().v2; + // pretend the chain holds an older forge-meta than the committed file (testnet's v2, before boards) + const tampered = t.read(); + tampered.v2.forgeMeta.schemaHash = '0'.repeat(64); + writeFileSync(t.testnetFile, JSON.stringify(tampered, null, 2)); + await t.run(t.prod('--update', 'meta')); + const rec = t.read(); + assert.equal(rec.v2.forgeMeta.version, 2); + assert.equal(rec.v2.forgeMeta.schemaHash, forgeMeta.schemaHash); + // only forge-meta was updated + assert.deepEqual(rec.v2.nonceLedger.filter((e) => e.kind === 'dataContractUpdate').map((e) => e.key), ['forgeMeta']); + const sent = t.fake.state.contracts.get(forgeMeta.contractId).json; + assert.equal(sent.version, 2); + assert.ok(!JSON.stringify(sent).includes('_CONTRACT_ID'), 'no placeholder left in the update'); + const { board, card } = sent.documentSchemas; + for (const leaf of [...board.ownerRefersTo.anyOf, ...card.ownerRefersTo.anyOf]) assert.equal(leaf.contractId, forgeCore.contractId, leaf.documentType); + assert.deepEqual(card.properties.item.refersTo.anyOf.map((l) => [l.documentType, l.contractId]), + [['issue', forgeCollab.contractId], ['patch', forgeCollab.contractId]]); +}); + test('--update refuses a record of the other set', async () => { const t = setup(); await t.run(t.prod()); diff --git a/forge-contracts/scripts/lib/offline-chain.test.mjs b/forge-contracts/scripts/lib/offline-chain.test.mjs index da05b20e7..df6aadf7f 100644 --- a/forge-contracts/scripts/lib/offline-chain.test.mjs +++ b/forge-contracts/scripts/lib/offline-chain.test.mjs @@ -6,7 +6,7 @@ import { join } from 'node:path'; import { test } from 'node:test'; import { OfflineChain } from './offline-chain.mjs'; -import { CONTRACTS, CONTRACT_OF, META_TYPES, ROOT, TRANSITION, VIS, b58encode, contractOn, documentReader, documentWriter, idBytes, membership, shapeOfSet, transition } from './seed-io.mjs'; +import { CONTRACTS, CONTRACT_OF, META_ONLY_TYPES, META_TYPES, ROOT, TRANSITION, VIS, b58encode, contractOn, documentReader, documentWriter, idBytes, membership, shapeOfSet, transition } from './seed-io.mjs'; // The default set's shape, as the seeds read it from the loaded contract. const SHAPE = shapeOfSet({ contracts: CONTRACTS, contractOf: CONTRACT_OF }); @@ -188,8 +188,8 @@ test('the deployment record picks the layout: forge-meta holds the moved types o const three = { core: 'C', collab: 'L', community: 'M' }; const four = { ...three, meta: 'X' }; for (const t of META_TYPES) { - // (vaultEntry, UPDATE-2, is a four-contract type: no home in the three-contract set) - if (t !== 'vaultEntry') { + // (vaultEntry, board and card are four-contract types: no home in the three-contract set) + if (!META_ONLY_TYPES.has(t)) { assert.ok(CONTRACT_OF[t], `${t} has a three-contract home`); assert.equal(contractOn(three, t), CONTRACT_OF[t], t); } @@ -274,6 +274,44 @@ test('a four-contract set: identifier lookups, no topic vis, and asMember with t await assert.rejects(write(person('stranger'), 'issue', asMember(person('stranger'))), refusedWith(40120, 'issue.asMember')); }); +// UPDATE-3 (docs/design/boards.md §3): a board or a card is written by the home repo's members only +// (a maintainer, or a writer of the claimed role: triage places cards and defines no board), the gate is +// asked again on every replace, a card names an issue or a PR, and neither is ever deleted. +test('a four-contract set: boards and cards are the home repo members\', and a card names an issue or a PR', async () => { + const chain = new OfflineChain({ contractsDir: join(ROOT, 'contracts', 'mainnet') }); + const evo = chain.evo(); + const sdk = new evo.EvoSDK(); + const write = documentWriter({ sdk }, evo, { ids: chain.ids }, noReconnect, { shape: shapeOfSet(chain.set), retries: 0 }); + const R = idBytes((await write(OWNER, 'repo', { name: 'r', visibility: VIS })).id.toBase58()); + await write(OWNER, 'maintainer', membership(R, OWNER.id, OWNER.id)); + const item = idBytes((await write(OWNER, 'issue', issue(R, 1))).id.toBase58()); + const board = { repoId: R, key: 7, name: 'Roadmap', spec: '{"v":1}', state: 0, r: 1 }; + const card = { repoId: R, board: 7, item, col: 1, rank: 'V', state: 0, r: 1 }; + const stranger = person('stranger'); + await assert.rejects(write(stranger, 'board', board), refusedWith(40120, 'board.ownerRefersTo')); + await assert.rejects(write(stranger, 'card', card), refusedWith(40120, 'card.ownerRefersTo')); + const defined = await write(OWNER, 'board', board); + await write(OWNER, 'card', card); + // a card names an issue or a PR: the repo's own id is neither + await assert.rejects(write(OWNER, 'card', { ...card, item: R }), refusedWith(40120, 'card.item')); + // triage (role 2) places a card and defines no board + await write(OTHER, 'consent', { repoId: R }); + const row = await write(OWNER, 'writer', { ...membership(R, OWNER.id, OTHER.id), role: 2 }); + await assert.rejects(write(OTHER, 'board', board), refusedWith(40127, 'board.ownerRefersTo')); + const placed = await write(OTHER, 'card', { ...card, r: 2 }); + // a move is a replace of the member's own card, and the gate is asked again on it + const move = (doc, type, owner, data) => { + const d = evo.Document.fromObject({ __meta: { type, contractId: chain.ids.meta, owner: owner.id, id: doc.id.toBase58() }, ...data }); + return sdk.documents.replace({ document: d }); + }; + await move(placed, 'card', OTHER, { ...card, r: 2, col: 2, rank: 'W' }); + await sdk.documents.delete({ document: row }); + await assert.rejects(move(placed, 'card', OTHER, { ...card, r: 2, col: 3 }), refusedWith(40120, 'card.ownerRefersTo')); + // never deleted: `state` 2 is the delete + await assert.rejects(sdk.documents.delete({ document: defined }), refusedWith(10404)); + await move(defined, 'board', OWNER, { ...board, state: 2 }); +}); + // A lagging node just after an enrolment answers the role read without the writer row: `mRole` is // left out, the member gate refuses (40120), and the write reads the role afresh and rebuilds once. test('a stale role read is re-read once when the member gate refuses', async () => { diff --git a/forge-contracts/scripts/lib/seed-io.mjs b/forge-contracts/scripts/lib/seed-io.mjs index 4cf3e79ec..21e0bb21e 100644 --- a/forge-contracts/scripts/lib/seed-io.mjs +++ b/forge-contracts/scripts/lib/seed-io.mjs @@ -45,10 +45,16 @@ export const CONTRACT_OF = DEFAULT_SET.contractOf; /** * The types forge-meta holds on a four-contract set (DESIGN rev 4.1 D44); a three-contract set - * keeps them in their `CONTRACT_OF` homes, except `vaultEntry` (UPDATE-2, the passkey vault), which - * only the four-contract set has. Parity: forge-core `layout::META_TYPES`, forge-web `lib/layout.ts`. + * keeps them in their `CONTRACT_OF` homes, except `META_ONLY_TYPES`, which only the four-contract + * set has. Parity: forge-core `layout::META_TYPES`, forge-web `lib/layout.ts`. */ -export const META_TYPES = new Set(['repoKey', 'ban', 'label', 'topic', 'packMirror', 'profile', 'follow', 'vaultEntry']); +export const META_TYPES = new Set(['repoKey', 'ban', 'label', 'topic', 'packMirror', 'profile', 'follow', 'vaultEntry', 'board', 'card']); + +/** + * The `META_TYPES` with no three-contract home: `vaultEntry` (UPDATE-2, the passkey vault), `board` + * and `card` (UPDATE-3, docs/design/boards.md §3). Parity: forge-core `layout::META_ONLY_TYPES`. + */ +export const META_ONLY_TYPES = new Set(['vaultEntry', 'board', 'card']); /** * The contract (`core`, `collab`, `community`, `meta`) that holds `type` on the network whose ids diff --git a/forge-contracts/scripts/lib/seed-io.test.mjs b/forge-contracts/scripts/lib/seed-io.test.mjs index 2b01df0e9..7cddf877c 100644 --- a/forge-contracts/scripts/lib/seed-io.test.mjs +++ b/forge-contracts/scripts/lib/seed-io.test.mjs @@ -6,7 +6,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, test } from 'node:test'; -import { CONTRACTS, CONTRACT_OF, META_TYPES, ROOT, assertWriteTarget, contractOn, contractsIn, resolveNetwork, shapeData, shapeOfSet } from './seed-io.mjs'; +import { CONTRACTS, CONTRACT_OF, META_ONLY_TYPES, META_TYPES, ROOT, assertWriteTarget, contractOn, contractsIn, resolveNetwork, shapeData, shapeOfSet } from './seed-io.mjs'; const typesOf = (dir, file) => Object.keys(JSON.parse(readFileSync(join(dir, file), 'utf8')).documentSchemas); @@ -35,8 +35,12 @@ test('the committed mainnet set is four contracts, forge-meta last', () => { test('a three-contract record keeps the moved types in their old homes', () => { const ids = { core: 'c', collab: 'l', community: 'm' }; - // (vaultEntry, UPDATE-2, is a four-contract type: the three-contract set has no home for it) - for (const t of META_TYPES) if (t !== 'vaultEntry') assert.equal(contractOn(ids, t), CONTRACT_OF[t], t); + // (vaultEntry, board and card are four-contract types: the three-contract set has no home for them) + for (const t of META_TYPES) { + if (META_ONLY_TYPES.has(t)) assert.equal(contractOn(ids, t), undefined, t); + else assert.equal(contractOn(ids, t), CONTRACT_OF[t], t); + } + for (const t of META_ONLY_TYPES) assert.ok(META_TYPES.has(t), t); }); // ---- the shape of a loaded set decides the fields a write carries (DESIGN MB1) ---- diff --git a/forge-contracts/vectors/rc1/forge-community.indices.json b/forge-contracts/vectors/rc1/forge-community.indices.json index 418464e54..baffa089f 100644 --- a/forge-contracts/vectors/rc1/forge-community.indices.json +++ b/forge-contracts/vectors/rc1/forge-community.indices.json @@ -43,6 +43,18 @@ "type": "vaultEntry", "expect": "absent" }, + { + "item": "U3", + "name": "no board type", + "type": "board", + "expect": "absent" + }, + { + "item": "U3", + "name": "no card type", + "type": "card", + "expect": "absent" + }, { "item": "EVK", "name": "no byKind index", diff --git a/forge-web/lib/layout.test.ts b/forge-web/lib/layout.test.ts index 1047aed50..85ed7bb33 100644 --- a/forge-web/lib/layout.test.ts +++ b/forge-web/lib/layout.test.ts @@ -13,7 +13,7 @@ import { describe, expect, it } from 'vitest' import { checkMembers } from './auth/group-trust' import { forgeContractIds, forgeV2Ids, groupTrust, type DeploymentFile, type ForgeIds } from './deployments' -import { META_TYPES, contractKindOfType, rc1WriteProblem, writeContractKind } from './layout' +import { META_ONLY_TYPES, META_TYPES, contractKindOfType, rc1WriteProblem, writeContractKind } from './layout' import { contractOf } from './repo/source' const THREE: ForgeIds = { core: 'CORE', collab: 'COLLAB', community: 'COMMUNITY', group: 'G' } @@ -28,12 +28,13 @@ const OLD_HOME: Readonly> = { profile: 'COMMUNITY', follow: 'COMMUNITY', } -// UPDATE-2 (the passkey vault): in forge-meta only; the three-contract set has no home for it. -const FOUR_CONTRACT_ONLY: ReadonlySet = new Set(['vaultEntry']) +// UPDATE-2 (the passkey vault) and UPDATE-3 (boards): in forge-meta only; the three-contract set has no home for them. +const FOUR_CONTRACT_ONLY: ReadonlySet = new Set(['vaultEntry', 'board', 'card']) describe('the layout follows the deployment record', () => { - it('forge-meta holds the seven moved types, and vaultEntry, only on a four-contract set', () => { + it('forge-meta holds the seven moved types, and vaultEntry, board and card, only on a four-contract set', () => { expect([...META_TYPES].sort()).toEqual([...Object.keys(OLD_HOME), ...FOUR_CONTRACT_ONLY].sort()) + expect([...META_ONLY_TYPES].sort()).toEqual([...FOUR_CONTRACT_ONLY].sort()) for (const t of META_TYPES) { if (FOUR_CONTRACT_ONLY.has(t)) { expect(() => contractOf(THREE, t), t).toThrow(/no Forge contract holds/) diff --git a/forge-web/lib/layout.ts b/forge-web/lib/layout.ts index 0924ad4a7..dbf691670 100644 --- a/forge-web/lib/layout.ts +++ b/forge-web/lib/layout.ts @@ -9,7 +9,7 @@ * * DESIGN rev 4.1 D44 adds a fourth contract, forge-meta: `repoKey`, `ban`, `label`, `topic`, * `packMirror`, `profile` and `follow` ({@link META_TYPES}) move there, and `vaultEntry` (UPDATE-2, - * the passkey vault) exists there only. The deployment record + * the passkey vault), `board` and `card` (UPDATE-3, boards) exist there only ({@link META_ONLY_TYPES}). The deployment record * says which layout a network has (`v2.forgeMeta`, `ForgeIds.meta`), so one build serves * sakura's three-contract set and four-contract sets: pass the network's ids to * {@link contractKindOfType}; without them it answers the three-contract home. @@ -70,10 +70,10 @@ export const COMMUNITY_TYPES: ReadonlySet = typesOf('community') /** * The types forge-meta holds on a four-contract set (D44). None is read by a rule, total or - * derived index of its old contract, so the move changes no consensus rule. `vaultEntry` is the - * exception: it has no three-contract home (`build.py` builds it with the four-contract layout - * only), so on a network without forge-meta no contract holds it. Parity: forge-core - * `layout::META_TYPES`. + * derived index of its old contract, so the move changes no consensus rule. {@link META_ONLY_TYPES} + * are the exception: they have no three-contract home (`build.py` builds them with the + * four-contract layout only), so on a network without forge-meta no contract holds them. Parity: + * forge-core `layout::META_TYPES`. */ export const META_TYPES: ReadonlySet = new Set([ 'repoKey', @@ -84,8 +84,17 @@ export const META_TYPES: ReadonlySet = new Set([ 'profile', 'follow', 'vaultEntry', + 'board', + 'card', ]) +/** + * The {@link META_TYPES} no three-contract set has: `vaultEntry` (UPDATE-2, the passkey vault), + * `board` and `card` (UPDATE-3, `docs/design/boards.md` §3). On a network without forge-meta + * {@link contractKindOfType} answers null for them. Parity: forge-core `layout::META_ONLY_TYPES`. + */ +export const META_ONLY_TYPES: ReadonlySet = new Set(['vaultEntry', 'board', 'card']) + /** * The contract that holds `type` on the network `forge` describes: forge-meta for * {@link META_TYPES} when it has one, else the three-contract home (also the answer without diff --git a/forge-web/lib/repo/contract.ts b/forge-web/lib/repo/contract.ts index 782374f1a..f04126cb5 100644 --- a/forge-web/lib/repo/contract.ts +++ b/forge-web/lib/repo/contract.ts @@ -53,6 +53,10 @@ export const DOC = { topic: 'topic', /** A passkey-sealed copy of a session's keys (forge-meta only; `lib/auth/passkey-vault`). */ vaultEntry: 'vaultEntry', + /** A board's definition, one per (home repo, key, member) (forge-meta only; `docs/design/boards.md` §3.1). */ + board: 'board', + /** A member's placement and field values for one item on one board (forge-meta only; boards.md §3.2). */ + card: 'card', } as const export { withVis } from '../layout' From 2f6b3f4fb0c1af9224038d7636c85f8da34079e7 Mon Sep 17 00:00:00 2001 From: pasta Date: Tue, 27 Oct 2026 20:06:10 +0000 Subject: [PATCH 02/26] feat(rules): board spec, rank, fold and query rules (web + forge-core) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pure board rules of docs/design/boards.md, in forge-web lib/rules/boards.ts and forge-core rules::boards, held together by 66 shared board_*__*.json vectors (board_spec, board_rank, board_fold, board_query, board_iteration, board_view) that both suites run: - spec: strict parse of the v1 definition with every §8 limit, canonical serialization (round-trips, <= 4096 B), the new-board template, card field values (unknown fields/options and wrong types dropped, <= 2048 B) - rank: rankBetween (strictly between incl. implicit bounds ending in 0 and prefix pairs; re-rank when nothing fits), implicit, top, bottom, rerank; property-tested in both languages with one splitmix64 PRNG - fold: placement per item (Done rule incl. columns after Done, default, removed, auto-archive with explicit now), newest card and newest board revision by ($updatedAt, $id) - query: board qualifiers (status, fields with comparisons and ranges, iterations, dates, repo, is:archived, negation), source queries - iterations, grouping, sorting, column totals, WIP, iteration progress forge-core reads JSON with serde_json float_roundtrip so card numbers read exactly as JSON.parse reads them; the web refuses what serde_json refuses (lone surrogates, 1e400, nesting past 127). The search tokenizer moves to lib/rules/search-terms.ts so the rules stay SDK-free. Design §2.7 records the encoding decisions. Co-Authored-By: Claude Opus 5.5 --- crates/forge-core/Cargo.toml | 4 +- crates/forge-core/src/rules.rs | 5 +- crates/forge-core/src/rules/boards.rs | 2618 +++++++++++++++++ crates/forge-core/src/rules/boards/tests.rs | 420 +++ docs/design/boards.md | 256 ++ .../vectors/board_fold__arch_off.json | 168 ++ .../board_fold__auto_archive_boundary.json | 361 +++ .../board_fold__bad_rank_and_values.json | 268 ++ .../vectors/board_fold__boards_newest.json | 78 + .../board_fold__boards_with_deleted.json | 83 + .../vectors/board_fold__newest_card.json | 248 ++ .../board_fold__no_done_no_default.json | 182 ++ .../vectors/board_fold__placement.json | 484 +++ .../vectors/board_fold__removed.json | 271 ++ .../board_fold__reopened_archived.json | 241 ++ .../vectors/board_fold__same_block.json | 260 ++ .../vectors/board_fold__sources.json | 309 ++ .../vectors/board_iteration__at.json | 134 + .../vectors/board_iteration__range.json | 158 + .../board_iteration__range_leap_year.json | 50 + .../board_query__match_archive_and_state.json | 334 +++ ...d_query__match_before_first_iteration.json | 308 ++ .../vectors/board_query__match_dates.json | 315 ++ .../vectors/board_query__match_fields.json | 345 +++ .../board_query__match_iterations.json | 328 +++ .../vectors/board_query__match_no_viewer.json | 301 ++ .../board_query__match_people_and_repo.json | 344 +++ .../vectors/board_query__match_text.json | 319 ++ .../board_query__parse_board_qualifiers.json | 287 ++ .../board_query__parse_issue_qualifiers.json | 180 ++ .../vectors/board_query__parse_source.json | 152 + .../board_query__parse_unresolved.json | 144 + .../vectors/board_rank__between.json | 167 ++ .../board_rank__between_implicit_bounds.json | 55 + .../vectors/board_rank__between_refused.json | 111 + .../vectors/board_rank__bottom.json | 45 + .../vectors/board_rank__implicit.json | 48 + .../vectors/board_rank__rerank_empty.json | 13 + .../vectors/board_rank__rerank_three.json | 17 + .../vectors/board_rank__rerank_too_many.json | 13 + .../vectors/board_rank__rerank_wide.json | 45 + forge-contracts/vectors/board_rank__top.json | 49 + .../vectors/board_spec__default_template.json | 14 + .../vectors/board_spec__parse_canonical.json | 61 + .../vectors/board_spec__parse_refused.json | 501 ++++ .../board_spec__parse_serde_refusals.json | 85 + .../vectors/board_spec__values_dropped.json | 125 + .../vectors/board_spec__values_escapes.json | 125 + .../board_spec__values_exact_numbers.json | 50 + .../vectors/board_spec__values_kept.json | 130 + .../board_spec__values_lone_surrogate.json | 123 + .../vectors/board_spec__values_not_json.json | 123 + .../board_spec__values_not_object.json | 123 + .../vectors/board_spec__values_null.json | 123 + .../vectors/board_spec__values_numbers.json | 60 + .../vectors/board_spec__values_overflow.json | 62 + .../board_spec__values_serde_refusals.json | 123 + .../vectors/board_view__group_assignee.json | 298 ++ .../vectors/board_view__group_iteration.json | 298 ++ .../vectors/board_view__group_label.json | 298 ++ .../vectors/board_view__group_milestone.json | 297 ++ .../vectors/board_view__group_repo.json | 292 ++ .../vectors/board_view__group_select.json | 306 ++ .../vectors/board_view__group_status.json | 301 ++ .../vectors/board_view__group_unknown.json | 287 ++ .../vectors/board_view__progress.json | 282 ++ .../board_view__progress_no_points.json | 282 ++ forge-contracts/vectors/board_view__sort.json | 394 +++ .../vectors/board_view__totals.json | 304 ++ .../board_view__totals_default_view.json | 304 ++ .../board_view__totals_no_number_field.json | 304 ++ .../lib/rules/boards.conformance.test.ts | 172 ++ forge-web/lib/rules/boards.test.ts | 135 + forge-web/lib/rules/boards.ts | 1535 ++++++++++ forge-web/lib/rules/conformance.test.ts | 6 +- forge-web/lib/rules/index.ts | 2 + forge-web/lib/rules/search-terms.ts | 42 + forge-web/lib/view/issue-query.ts | 42 +- 78 files changed, 18487 insertions(+), 40 deletions(-) create mode 100644 crates/forge-core/src/rules/boards.rs create mode 100644 crates/forge-core/src/rules/boards/tests.rs create mode 100644 docs/design/boards.md create mode 100644 forge-contracts/vectors/board_fold__arch_off.json create mode 100644 forge-contracts/vectors/board_fold__auto_archive_boundary.json create mode 100644 forge-contracts/vectors/board_fold__bad_rank_and_values.json create mode 100644 forge-contracts/vectors/board_fold__boards_newest.json create mode 100644 forge-contracts/vectors/board_fold__boards_with_deleted.json create mode 100644 forge-contracts/vectors/board_fold__newest_card.json create mode 100644 forge-contracts/vectors/board_fold__no_done_no_default.json create mode 100644 forge-contracts/vectors/board_fold__placement.json create mode 100644 forge-contracts/vectors/board_fold__removed.json create mode 100644 forge-contracts/vectors/board_fold__reopened_archived.json create mode 100644 forge-contracts/vectors/board_fold__same_block.json create mode 100644 forge-contracts/vectors/board_fold__sources.json create mode 100644 forge-contracts/vectors/board_iteration__at.json create mode 100644 forge-contracts/vectors/board_iteration__range.json create mode 100644 forge-contracts/vectors/board_iteration__range_leap_year.json create mode 100644 forge-contracts/vectors/board_query__match_archive_and_state.json create mode 100644 forge-contracts/vectors/board_query__match_before_first_iteration.json create mode 100644 forge-contracts/vectors/board_query__match_dates.json create mode 100644 forge-contracts/vectors/board_query__match_fields.json create mode 100644 forge-contracts/vectors/board_query__match_iterations.json create mode 100644 forge-contracts/vectors/board_query__match_no_viewer.json create mode 100644 forge-contracts/vectors/board_query__match_people_and_repo.json create mode 100644 forge-contracts/vectors/board_query__match_text.json create mode 100644 forge-contracts/vectors/board_query__parse_board_qualifiers.json create mode 100644 forge-contracts/vectors/board_query__parse_issue_qualifiers.json create mode 100644 forge-contracts/vectors/board_query__parse_source.json create mode 100644 forge-contracts/vectors/board_query__parse_unresolved.json create mode 100644 forge-contracts/vectors/board_rank__between.json create mode 100644 forge-contracts/vectors/board_rank__between_implicit_bounds.json create mode 100644 forge-contracts/vectors/board_rank__between_refused.json create mode 100644 forge-contracts/vectors/board_rank__bottom.json create mode 100644 forge-contracts/vectors/board_rank__implicit.json create mode 100644 forge-contracts/vectors/board_rank__rerank_empty.json create mode 100644 forge-contracts/vectors/board_rank__rerank_three.json create mode 100644 forge-contracts/vectors/board_rank__rerank_too_many.json create mode 100644 forge-contracts/vectors/board_rank__rerank_wide.json create mode 100644 forge-contracts/vectors/board_rank__top.json create mode 100644 forge-contracts/vectors/board_spec__default_template.json create mode 100644 forge-contracts/vectors/board_spec__parse_canonical.json create mode 100644 forge-contracts/vectors/board_spec__parse_refused.json create mode 100644 forge-contracts/vectors/board_spec__parse_serde_refusals.json create mode 100644 forge-contracts/vectors/board_spec__values_dropped.json create mode 100644 forge-contracts/vectors/board_spec__values_escapes.json create mode 100644 forge-contracts/vectors/board_spec__values_exact_numbers.json create mode 100644 forge-contracts/vectors/board_spec__values_kept.json create mode 100644 forge-contracts/vectors/board_spec__values_lone_surrogate.json create mode 100644 forge-contracts/vectors/board_spec__values_not_json.json create mode 100644 forge-contracts/vectors/board_spec__values_not_object.json create mode 100644 forge-contracts/vectors/board_spec__values_null.json create mode 100644 forge-contracts/vectors/board_spec__values_numbers.json create mode 100644 forge-contracts/vectors/board_spec__values_overflow.json create mode 100644 forge-contracts/vectors/board_spec__values_serde_refusals.json create mode 100644 forge-contracts/vectors/board_view__group_assignee.json create mode 100644 forge-contracts/vectors/board_view__group_iteration.json create mode 100644 forge-contracts/vectors/board_view__group_label.json create mode 100644 forge-contracts/vectors/board_view__group_milestone.json create mode 100644 forge-contracts/vectors/board_view__group_repo.json create mode 100644 forge-contracts/vectors/board_view__group_select.json create mode 100644 forge-contracts/vectors/board_view__group_status.json create mode 100644 forge-contracts/vectors/board_view__group_unknown.json create mode 100644 forge-contracts/vectors/board_view__progress.json create mode 100644 forge-contracts/vectors/board_view__progress_no_points.json create mode 100644 forge-contracts/vectors/board_view__sort.json create mode 100644 forge-contracts/vectors/board_view__totals.json create mode 100644 forge-contracts/vectors/board_view__totals_default_view.json create mode 100644 forge-contracts/vectors/board_view__totals_no_number_field.json create mode 100644 forge-web/lib/rules/boards.conformance.test.ts create mode 100644 forge-web/lib/rules/boards.test.ts create mode 100644 forge-web/lib/rules/boards.ts create mode 100644 forge-web/lib/rules/search-terms.ts diff --git a/crates/forge-core/Cargo.toml b/crates/forge-core/Cargo.toml index e81377d7e..74da5ea9f 100644 --- a/crates/forge-core/Cargo.toml +++ b/crates/forge-core/Cargo.toml @@ -11,7 +11,9 @@ description = "Shared library for Dash Forge: platform client, pack pipeline, ba [dependencies] thiserror.workspace = true serde.workspace = true -serde_json.workspace = true +# `float_roundtrip`: read every JSON number exactly, as JavaScript's `JSON.parse` does (the default +# parser is off by one ulp for some; a board card's number field must read alike in both clients). +serde_json = { workspace = true, features = ["float_roundtrip"] } tracing.workspace = true # The CLIs' shared stderr logger (`logging`, feature `cli-logging`), which hides the SDK's # recovered-error noise. diff --git a/crates/forge-core/src/rules.rs b/crates/forge-core/src/rules.rs index baf70f3d6..0c16a7a86 100644 --- a/crates/forge-core/src/rules.rs +++ b/crates/forge-core/src/rules.rs @@ -50,6 +50,7 @@ pub mod agent_request; pub mod asset_name; pub mod aud; pub mod bans; +pub mod boards; pub mod ci_rerun; pub mod codeowners; pub mod embargo; @@ -3871,7 +3872,8 @@ mod tests { let v: Vector = serde_json::from_slice(&bytes) .unwrap_or_else(|e| panic!("parse {}: {e}", path.display())); // the private-repository and mixed-visibility envelope vectors run in - // `private::conformance`, the environment snapshots in `env::conformance` + // `private::conformance`, the environment snapshots in `env::conformance`, the + // boards' (`board_*`) in `boards::tests::board_vectors` if crate::private::conformance::CRYPTO_CASE_PREFIXES .iter() .any(|p| v.case.starts_with(p)) @@ -3880,6 +3882,7 @@ mod tests { || v.case == crate::private::access_notice::VECTOR_CASE || v.case == crate::private::bot_post::VECTOR_CASE || v.case == crate::rules::push_grant::VECTOR_CASE + || v.case.starts_with(crate::rules::boards::VECTOR_CASE_PREFIX) || crate::members_git::conformance::CASES.contains(&v.case.as_str()) || v.case == crate::private::branch_key::conformance::CASE || v.case == crate::private::members_check::CASE diff --git a/crates/forge-core/src/rules/boards.rs b/crates/forge-core/src/rules/boards.rs new file mode 100644 index 000000000..fb7a701e1 --- /dev/null +++ b/crates/forge-core/src/rules/boards.rs @@ -0,0 +1,2618 @@ +//! Boards (`docs/design/boards.md`): the pure rules every client applies to a board's +//! documents, so `dg board` and the web show the same board. A port of forge-web's +//! `lib/rules/boards.ts`; the `board_*__*.json` vectors in `forge-contracts/vectors/` pin the +//! two together ([`tests::board_vectors`] here, `lib/rules/boards.conformance.test.ts` there). +//! +//! * **Spec** (§2.1–§2.3, §4, §8): the board definition a `board` document's `spec` holds, +//! parsed strictly ([`parse_spec`]) and written canonically ([`serialize_spec`]); a card's +//! field values ([`parse_field_values`], [`serialize_field_values`]). +//! * **Rank** (§2.6): base-62 fractional ranks ([`rank_between`], [`implicit_rank`], +//! [`top_rank`], [`bottom_rank`], [`rerank`]). +//! * **Fold** (§2.4): where every item shows ([`fold_board`]), and the newest board revision +//! per key ([`newest_boards`]). +//! * **Query** (§4.4): [`parse_board_query`], [`matches_board_query`]. +//! * **Iterations** (§2.2): [`iteration_at`], [`iteration_range`]. +//! * **Views** (§4.1–§4.5): [`group_rows`], [`sort_rows`], [`column_totals`], +//! [`iteration_progress`]. +//! +//! Everything is pure: no SDK, no clock (`now` is an input), no I/O. Strings compare by code +//! point (Rust's `str` order, the web's `compareStrings`). + +use std::cmp::Ordering; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt::Write as _; + +use serde::{Deserialize, Serialize, Serializer}; +use serde_json::{Map, Value}; + +use super::search::{search_terms, tokens}; + +/// The vector case prefix: `board_rank`, `board_spec`, `board_fold`, `board_query`, +/// `board_iteration`, `board_view`. +pub const VECTOR_CASE_PREFIX: &str = "board_"; + +/// A `board.spec` holds at most this many UTF-8 bytes (the contract's `maxBytes`). +pub const SPEC_MAX_BYTES: usize = 4096; +/// A `card.f` holds at most this many UTF-8 bytes. +pub const FIELD_VALUES_MAX_BYTES: usize = 2048; +/// At most 20 status columns. +pub const MAX_COLUMNS: usize = 20; +/// At most 12 custom fields. +pub const MAX_FIELDS: usize = 12; +/// At most 30 options per single-select field. +pub const MAX_OPTIONS: usize = 30; +/// At most 5 sources. +pub const MAX_SOURCES: usize = 5; +/// At most 8 saved views. +pub const MAX_VIEWS: usize = 8; +/// A view lists at most this many table columns. +pub const MAX_VIEW_COLS: usize = 24; +/// Column, field, option and view names: 1–63 characters. +pub const NAME_MAX: usize = 63; +/// A board's description: at most this many characters. +pub const DESC_MAX: usize = 1024; +/// A source's or view's query: at most this many characters (the issue list's `Q_MAX`). +pub const QUERY_MAX: usize = 512; +/// A text field's value: 1–200 characters. +pub const TEXT_VALUE_MAX: usize = 200; +/// A column's WIP limit: 1–9999. +pub const WIP_MAX: i64 = 9999; +/// An iteration field's length: 1–90 days. +pub const ITER_DAYS_MAX: i64 = 90; +/// The highest iteration index a card may name. +pub const ITER_INDEX_MAX: i64 = 65535; +/// Auto-archive after at most this many days (0 = off). +pub const ARCH_MAX: i64 = 3650; +/// A number field's value: finite, |x| ≤ 1e15, and 0 or |x| ≥ 1e-6 (both clients print it alike). +pub const NUM_ABS_MAX: f64 = 1e15; +/// See [`NUM_ABS_MAX`]. +pub const NUM_ABS_MIN: f64 = 1e-6; +/// An explicit rank is at most 63 characters (the `card.rank` schema). +pub const RANK_MAX: usize = 63; +/// Ranks are re-spread for at most this many items at once. +pub const RERANK_MAX: u64 = 1_000_000; + +const DAY_MS: i64 = 86_400_000; + +// --------------------------------------------------------------------------------------------- +// Shared value shapes +// --------------------------------------------------------------------------------------------- + +/// A number or a string: a field value (an option id, a number, `YYYY-MM-DD`, an iteration +/// index, text), a query operand, a group key. A whole number serializes as a JSON integer, as +/// the web's `JSON.stringify` writes it. +#[derive(Debug, Clone, PartialEq)] +pub enum Scalar { + /// A number. + Num(f64), + /// A string. + Text(String), +} + +impl Scalar { + fn num(&self) -> Option { + match self { + Self::Num(x) => Some(*x), + Self::Text(_) => None, + } + } + + fn text(&self) -> Option<&str> { + match self { + Self::Num(_) => None, + Self::Text(t) => Some(t), + } + } + + /// As `String(v)` writes it. + fn display(&self) -> String { + match self { + Self::Num(x) => js_number(*x), + Self::Text(t) => t.clone(), + } + } +} + +impl From for Scalar { + #[allow(clippy::cast_precision_loss)] // ids, indices and counts: far below 2^53 + fn from(n: i64) -> Self { + Self::Num(n as f64) + } +} + +impl Serialize for Scalar { + #[allow(clippy::cast_possible_truncation, clippy::float_cmp)] // a whole number below 2^53 + fn serialize(&self, s: S) -> Result { + match self { + Self::Text(t) => s.serialize_str(t), + Self::Num(x) if x.fract() == 0.0 && x.abs() < 9_007_199_254_740_992.0 => { + s.serialize_i64(*x as i64) + } + Self::Num(x) => s.serialize_f64(*x), + } + } +} + +/// A finite number as JavaScript's `String(x)` writes it, for |x| in [1e-6, 1e21) or 0 (the +/// numbers a board stores and sums): ryu's shortest round-trip digits (JavaScript's, ties to +/// even; Rust's own `{}` rounds an exact tie up), written without an exponent; `-0` as `0`. +#[allow(clippy::float_cmp, clippy::cast_possible_truncation)] // -0 == 0; a whole number below 2^53 +fn js_number(x: f64) -> String { + if x == 0.0 { + return "0".into(); + } + if x.fract() == 0.0 && x.abs() < 9_007_199_254_740_992.0 { + return format!("{}", x as i64); + } + // serde_json writes f64 with ryu: `71292843364840.12`, `1.5e-6`, `1.152921504606847e+18` + let ryu = serde_json::to_string(&x).unwrap_or_default(); + let (sign, body) = ryu + .strip_prefix('-') + .map_or(("", ryu.as_str()), |b| ("-", b)); + let (mantissa, exp) = body + .split_once('e') + .map_or((body, 0), |(m, e)| (m, e.parse::().unwrap_or(0))); + let (int, frac) = mantissa.split_once('.').unwrap_or((mantissa, "")); + let all = format!("{int}{frac}"); + let digits = all.trim_start_matches('0'); + // the decimal point sits `point` digits into `digits` + let point = i64::try_from(int.len()).unwrap_or(0) + exp + - i64::try_from(all.len() - digits.len()).unwrap_or(0); + let digits = digits.trim_end_matches('0'); + let len = i64::try_from(digits.len()).unwrap_or(0); + let zeros = |n: i64| "0".repeat(usize::try_from(n).unwrap_or(0)); + if point <= 0 { + format!("{sign}0.{}{digits}", zeros(-point)) + } else if point >= len { + format!("{sign}{digits}{}", zeros(point - len)) + } else { + let at = usize::try_from(point).unwrap_or(0); + format!("{sign}{}.{}", &digits[..at], &digits[at..]) + } +} + +/// `s`'s length in characters (code points: the contract's `maxLength`). +fn char_len(s: &str) -> usize { + s.chars().count() +} + +/// The white space a name may not start or end with: JavaScript's `trim` set less the +/// controls (refused anyway). +fn is_space(c: char) -> bool { + matches!( + c as u32, + 0x20 | 0xa0 | 0x1680 | 0x2000 + ..=0x200a | 0x2028 | 0x2029 | 0x202f | 0x205f | 0x3000 | 0xfeff + ) +} + +/// C0, DEL and C1 control characters. +fn is_control(c: char) -> bool { + let x = c as u32; + x < 0x20 || (0x7f..=0x9f).contains(&x) +} + +/// A column, field, option or view name: 1–63 characters, no control character or `"` (a +/// query quotes names with `"`), not starting or ending with white space. +fn name_ok(s: &str) -> bool { + (1..=NAME_MAX).contains(&char_len(s)) + && !s.chars().any(|c| is_control(c) || c == '"') + && !s.chars().next().is_some_and(is_space) + && !s.chars().last().is_some_and(is_space) +} + +/// A JSON number that is a whole number in `min..=max` (the web's `Number.isInteger` check). +#[allow( + clippy::cast_possible_truncation, + clippy::cast_precision_loss, + clippy::float_cmp +)] +fn int_in(v: Option<&Value>, min: i64, max: i64) -> Option { + let x = v?.as_f64()?; + (x.fract() == 0.0 && x >= min as f64 && x <= max as f64).then_some(x as i64) +} + +/// A JSON string of at most `max` characters. +fn text_in(v: &Value, max: usize) -> Option { + v.as_str() + .filter(|s| char_len(s) <= max) + .map(str::to_string) +} + +fn is_color(s: &str) -> bool { + s.len() == 7 && s.starts_with('#') && s.bytes().skip(1).all(|b| b.is_ascii_hexdigit()) +} + +/// An identity or document id: 42–44 base58 characters (the web's `isIdentityId`). +fn is_identifier(s: &str) -> bool { + (42..=44).contains(&s.len()) + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() && !matches!(b, b'0' | b'O' | b'I' | b'l')) +} + +/// Days since 1970-01-01 of a proleptic Gregorian date (Hinnant's `days_from_civil`). +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let yy = if m <= 2 { y - 1 } else { y }; + let era = yy.div_euclid(400); + let yoe = yy - era * 400; + let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +/// The date `days` after 1970-01-01, as `YYYY-MM-DD` (Hinnant's `civil_from_days`). +fn civil_from_days(days: i64) -> String { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!("{y:04}-{m:02}-{d:02}") +} + +/// A `YYYY-MM-DD` calendar date's day number (days since 1970-01-01), or `None`. +#[must_use] +pub fn date_days(s: &str) -> Option { + let bytes = s.as_bytes(); + if bytes.len() != 10 + || bytes[4] != b'-' + || bytes[7] != b'-' + || ![0, 1, 2, 3, 5, 6, 8, 9] + .iter() + .all(|&i| bytes[i].is_ascii_digit()) + { + return None; + } + let (y, m, d) = ( + s[0..4].parse::().ok()?, + s[5..7].parse::().ok()?, + s[8..10].parse::().ok()?, + ); + if y < 1 || !(1..=12).contains(&m) || d < 1 { + return None; + } + let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; + let len = [ + 31, + if leap { 29 } else { 28 }, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31, + ]; + (d <= len[usize::try_from(m - 1).ok()?]).then(|| days_from_civil(y, m, d)) +} + +/// The UTC date of a millisecond time, as `YYYY-MM-DD`. +#[must_use] +pub fn date_of(ms: i64) -> String { + civil_from_days(ms.div_euclid(DAY_MS)) +} + +fn is_zero(x: &T) -> bool { + *x == T::default() +} + +// --------------------------------------------------------------------------------------------- +// Spec (§2.1–§2.3, §4) +// --------------------------------------------------------------------------------------------- + +/// A status column (§2.1): `id` 1–255 stable across renames; order is the array order. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct BoardColumn { + /// 1–255. + pub id: u8, + /// The column's name. + pub name: String, + /// `#rrggbb`. + #[serde(skip_serializing_if = "Option::is_none")] + pub color: Option, + /// WIP limit (§4.5): shown and warned on, never blocking. + #[serde(skip_serializing_if = "Option::is_none")] + pub wip: Option, +} + +/// The custom field types (§2.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum FieldType { + /// Single select: an option id. + Sel, + /// A finite number. + Num, + /// `YYYY-MM-DD`. + Date, + /// An iteration index. + Iter, + /// Text, 1–200 characters. + Text, +} + +/// A single-select option. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct FieldOption { + /// 1–255. + pub id: u8, + /// The option's name. + pub name: String, + /// `#rrggbb`. + #[serde(skip_serializing_if = "Option::is_none")] + pub color: Option, +} + +/// A custom field (§2.2). `options` is present exactly for `sel`; `start` (`YYYY-MM-DD`) and +/// `days` (1–90) exactly for `iter`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct BoardField { + /// 1–255. + pub id: u8, + /// The field's name. + pub name: String, + /// The type. + #[serde(rename = "type")] + pub kind: FieldType, + /// A `sel` field's options. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option>, + /// An `iter` field's first day. + #[serde(skip_serializing_if = "Option::is_none")] + pub start: Option, + /// An `iter` field's length in days. + #[serde(skip_serializing_if = "Option::is_none")] + pub days: Option, +} + +/// A source's kind: issues, pull requests, or both. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum SourceKind { + /// Issues. + #[serde(rename = "i")] + Issues, + /// Pull requests. + #[serde(rename = "p")] + Pulls, + /// Both. + #[serde(rename = "a")] + All, +} + +/// An auto-include rule (§2.3): every item of repository `r` (absent: the home repository) of +/// kind `k` that query `q` matches is on the board ([`parse_source_query`]). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct BoardSource { + /// The repository id. + #[serde(skip_serializing_if = "Option::is_none")] + pub r: Option, + /// The kind. + pub k: SourceKind, + /// The filter, empty for all. + #[serde(skip_serializing_if = "String::is_empty")] + pub q: String, +} + +/// A view's layout (§4.1–§4.3). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum ViewLayout { + /// Columns of cards. + Board, + /// Rows. + Table, + /// A timeline. + Roadmap, +} + +/// A saved view (§4); its keys as the web's `BoardView` documents them (`status`, `assignee`, +/// `label`, `milestone`, `repo`, `f`, …). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct BoardView { + /// 1–255. + pub id: u8, + /// The view's name. + pub name: String, + /// The layout. + pub layout: ViewLayout, + /// The filter. + #[serde(skip_serializing_if = "String::is_empty")] + pub q: String, + /// The grouping (board columns, table sections); absent is `status`. + #[serde(skip_serializing_if = "Option::is_none")] + pub group: Option, + /// Swimlanes. + #[serde(skip_serializing_if = "Option::is_none")] + pub lane: Option, + /// The sort, `-` first for descending; absent is `rank`. + #[serde(skip_serializing_if = "Option::is_none")] + pub sort: Option, + /// The fields shown. + #[serde(skip_serializing_if = "Option::is_none")] + pub cols: Option>, + /// The roadmap's dates: one `iter` field, or a start and an end `date` field. + #[serde(skip_serializing_if = "Option::is_none")] + pub date: Option>, +} + +/// A board definition, `v: 1` (§2). `def` / `done` are column ids, 0 for none; `arch` is +/// days, 0 = off. Serializes canonically: the declared key order, defaults omitted. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct BoardSpec { + /// Always 1. + pub v: u8, + /// The description. + #[serde(skip_serializing_if = "Option::is_none")] + pub desc: Option, + /// 1–20 columns. + pub columns: Vec, + /// The default column. + #[serde(skip_serializing_if = "is_zero")] + pub def: u8, + /// The Done column. + #[serde(skip_serializing_if = "is_zero")] + pub done: u8, + /// Auto-include rules. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub sources: Vec, + /// Custom fields. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub fields: Vec, + /// Saved views. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub views: Vec, + /// Auto-archive after this many days. + #[serde(skip_serializing_if = "is_zero")] + pub arch: u16, +} + +impl BoardSpec { + /// A field by id. + #[must_use] + pub fn field(&self, id: u8) -> Option<&BoardField> { + self.fields.iter().find(|f| f.id == id) + } + + fn column_index(&self, id: u8) -> Option { + self.columns.iter().position(|c| c.id == id) + } +} + +/// Why a spec was refused (the web's `SpecError`): not JSON or not an object, not `v: 1`, +/// over 4096 bytes, or the part that is malformed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SpecError { + /// Not JSON, or not an object. + Json, + /// Not `v: 1`. + Version, + /// Over 4096 bytes. + Size, + /// The description. + Desc, + /// The column list. + Columns, + /// A column (malformed or repeated). + Column, + /// `def`. + Def, + /// `done`. + Done, + /// The source list. + Sources, + /// A source. + Source, + /// The field list. + Fields, + /// A field (malformed, repeated or reserved). + Field, + /// A field's options. + Options, + /// The view list. + Views, + /// A view. + View, + /// `arch`. + Arch, +} + +impl SpecError { + /// The code both clients name it by. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Json => "json", + Self::Version => "version", + Self::Size => "size", + Self::Desc => "desc", + Self::Columns => "columns", + Self::Column => "column", + Self::Def => "def", + Self::Done => "done", + Self::Sources => "sources", + Self::Source => "source", + Self::Fields => "fields", + Self::Field => "field", + Self::Options => "options", + Self::Views => "views", + Self::View => "view", + Self::Arch => "arch", + } + } +} + +impl std::fmt::Display for SpecError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +impl std::error::Error for SpecError {} + +/// Names a field may not have, in any letter case: the query's own keys and the built-in +/// fields (§2.2, §4.4). +const RESERVED_FIELD_NAMES: &[&str] = &[ + "is", + "state", + "label", + "labels", + "assignee", + "assignees", + "author", + "milestone", + "no", + "status", + "repo", + "repository", + "title", + "number", + "created", +]; +const GROUP_BUILTINS: &[&str] = &["status", "assignee", "label", "milestone", "repo"]; +const SORT_BUILTINS: &[&str] = &[ + "rank", + "title", + "number", + "created", + "status", + "repo", + "author", + "milestone", +]; +const COL_BUILTINS: &[&str] = &[ + "title", + "number", + "repo", + "state", + "author", + "assignees", + "labels", + "milestone", + "created", + "status", +]; + +/// The field id a `f` key names (1–255, no leading zero). +#[must_use] +pub fn field_key_id(key: &str) -> Option { + let digits = key.strip_prefix('f')?; + if digits.is_empty() + || digits.len() > 3 + || digits.starts_with('0') + || !digits.bytes().all(|b| b.is_ascii_digit()) + { + return None; + } + digits.parse::().ok() +} + +fn field_of_key<'a>(fields: &'a [BoardField], key: &str) -> Option<&'a BoardField> { + let id = field_key_id(key)?; + fields.iter().find(|f| f.id == id) +} + +fn group_key_ok(fields: &[BoardField], key: &str, board_layout: bool) -> bool { + if key == "status" { + return true; + } + if GROUP_BUILTINS.contains(&key) { + return !board_layout; + } + field_of_key(fields, key).is_some_and(|f| matches!(f.kind, FieldType::Sel | FieldType::Iter)) +} + +fn sort_key_ok(fields: &[BoardField], key: &str) -> bool { + let k = key.strip_prefix('-').unwrap_or(key); + SORT_BUILTINS.contains(&k) || field_of_key(fields, k).is_some() +} + +fn col_key_ok(fields: &[BoardField], key: &str) -> bool { + COL_BUILTINS.contains(&key) || field_of_key(fields, key).is_some() +} + +/// Whether ids or names (in lower case) repeat. +fn repeats<'a>(entries: impl Iterator + Clone) -> bool { + let n = entries.clone().count(); + let ids: HashSet = entries.clone().map(|(id, _)| id).collect(); + let names: HashSet = entries.map(|(_, name)| name.to_lowercase()).collect(); + ids.len() != n || names.len() != n +} + +fn color_of(v: Option<&Value>, err: SpecError) -> Result, SpecError> { + match v { + None => Ok(None), + Some(v) => v + .as_str() + .filter(|s| is_color(s)) + .map(|s| Some(s.to_string())) + .ok_or(err), + } +} + +/// An entry's `id` (1–255) and `name`. +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // 1..=255 +fn id_name(o: &Map, name_ok: impl Fn(&str) -> bool) -> Option<(u8, String)> { + let id = int_in(o.get("id"), 1, 255)? as u8; + let name = o.get("name")?.as_str().filter(|n| name_ok(n))?; + Some((id, name.to_string())) +} + +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // 1..=9999 +fn parse_columns(v: Option<&Value>) -> Result, SpecError> { + let list = v + .and_then(Value::as_array) + .filter(|l| (1..=MAX_COLUMNS).contains(&l.len())) + .ok_or(SpecError::Columns)?; + let mut out = Vec::new(); + for c in list { + let o = c.as_object().ok_or(SpecError::Column)?; + let (id, name) = id_name(o, name_ok).ok_or(SpecError::Column)?; + let color = color_of(o.get("color"), SpecError::Column)?; + let wip = match o.get("wip") { + None => None, + Some(w) => Some(int_in(Some(w), 1, WIP_MAX).ok_or(SpecError::Column)? as u16), + }; + out.push(BoardColumn { + id, + name, + color, + wip, + }); + } + if repeats(out.iter().map(|c| (c.id, c.name.as_str()))) { + return Err(SpecError::Column); + } + Ok(out) +} + +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // 0..=255 +fn parse_column_ref( + v: Option<&Value>, + columns: &[BoardColumn], + err: SpecError, +) -> Result { + let Some(v) = v else { return Ok(0) }; + let id = int_in(Some(v), 0, 255).ok_or(err)? as u8; + if id != 0 && !columns.iter().any(|c| c.id == id) { + return Err(err); + } + Ok(id) +} + +fn parse_sources(value: Option<&Value>) -> Result, SpecError> { + let Some(value) = value else { + return Ok(Vec::new()); + }; + let list = value + .as_array() + .filter(|l| l.len() <= MAX_SOURCES) + .ok_or(SpecError::Sources)?; + list.iter() + .map(|entry| { + let obj = entry.as_object().ok_or(SpecError::Source)?; + let r = match obj.get("r") { + None => None, + Some(repo) => Some( + repo.as_str() + .filter(|id| is_identifier(id)) + .ok_or(SpecError::Source)? + .to_string(), + ), + }; + let k = match obj.get("k").and_then(Value::as_str) { + Some("i") => SourceKind::Issues, + Some("p") => SourceKind::Pulls, + Some("a") => SourceKind::All, + _ => return Err(SpecError::Source), + }; + let q = match obj.get("q") { + None => String::new(), + Some(text) => text_in(text, QUERY_MAX).ok_or(SpecError::Source)?, + }; + Ok(BoardSource { r, k, q }) + }) + .collect() +} + +fn parse_options(v: Option<&Value>) -> Result, SpecError> { + let list = v + .and_then(Value::as_array) + .filter(|l| l.len() <= MAX_OPTIONS) + .ok_or(SpecError::Options)?; + let mut out = Vec::new(); + for o in list { + let o = o.as_object().ok_or(SpecError::Options)?; + let (id, name) = id_name(o, name_ok).ok_or(SpecError::Options)?; + let color = color_of(o.get("color"), SpecError::Options)?; + out.push(FieldOption { id, name, color }); + } + if repeats(out.iter().map(|o| (o.id, o.name.as_str()))) { + return Err(SpecError::Options); + } + Ok(out) +} + +fn field_name_ok(name: &str) -> bool { + name_ok(name) + && !name.contains(':') + && !name.starts_with('-') + && !RESERVED_FIELD_NAMES.contains(&name.to_lowercase().as_str()) +} + +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // 1..=90 +fn parse_fields(v: Option<&Value>) -> Result, SpecError> { + let Some(v) = v else { return Ok(Vec::new()) }; + let list = v + .as_array() + .filter(|l| l.len() <= MAX_FIELDS) + .ok_or(SpecError::Fields)?; + let mut out = Vec::new(); + for f in list { + let o = f.as_object().ok_or(SpecError::Field)?; + let (id, name) = id_name(o, field_name_ok).ok_or(SpecError::Field)?; + let kind = match o.get("type").and_then(Value::as_str) { + Some("sel") => FieldType::Sel, + Some("num") => FieldType::Num, + Some("date") => FieldType::Date, + Some("iter") => FieldType::Iter, + Some("text") => FieldType::Text, + _ => return Err(SpecError::Field), + }; + if o.contains_key("options") != (kind == FieldType::Sel) { + return Err(SpecError::Field); + } + if (o.contains_key("start") || o.contains_key("days")) && kind != FieldType::Iter { + return Err(SpecError::Field); + } + let mut field = BoardField { + id, + name, + kind, + options: None, + start: None, + days: None, + }; + match kind { + FieldType::Sel => field.options = Some(parse_options(o.get("options"))?), + FieldType::Iter => { + let start = o + .get("start") + .and_then(Value::as_str) + .filter(|s| date_days(s).is_some()) + .ok_or(SpecError::Field)?; + let days = int_in(o.get("days"), 1, ITER_DAYS_MAX).ok_or(SpecError::Field)?; + field.start = Some(start.to_string()); + field.days = Some(days as u8); + } + _ => {} + } + out.push(field); + } + if repeats(out.iter().map(|f| (f.id, f.name.as_str()))) { + return Err(SpecError::Field); + } + Ok(out) +} + +/// An optional string member: `Ok(None)` absent, `Err` present but not a string. +fn opt_str(o: &Map, key: &str) -> Result, ()> { + match o.get(key) { + None => Ok(None), + Some(Value::String(s)) => Ok(Some(s.clone())), + Some(_) => Err(()), + } +} + +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // 1..=255 +fn parse_view(w: &Value, fields: &[BoardField]) -> Option { + let o = w.as_object()?; + let (id, name) = id_name(o, name_ok)?; + let layout = match o.get("layout").and_then(Value::as_str)? { + "board" => ViewLayout::Board, + "table" => ViewLayout::Table, + "roadmap" => ViewLayout::Roadmap, + _ => return None, + }; + let q = match o.get("q") { + None => String::new(), + Some(q) => text_in(q, QUERY_MAX)?, + }; + let (group, lane, sort) = ( + opt_str(o, "group").ok()?, + opt_str(o, "lane").ok()?, + opt_str(o, "sort").ok()?, + ); + if group + .as_deref() + .is_some_and(|g| !group_key_ok(fields, g, layout == ViewLayout::Board)) + { + return None; + } + if let Some(l) = lane.as_deref() { + if l == "status" + || l == group.as_deref().unwrap_or("status") + || !group_key_ok(fields, l, false) + { + return None; + } + } + if sort.as_deref().is_some_and(|s| !sort_key_ok(fields, s)) { + return None; + } + let cols = match o.get("cols") { + None => None, + Some(c) => { + let list = c.as_array().filter(|l| l.len() <= MAX_VIEW_COLS)?; + let keys: Vec = list + .iter() + .map(|k| { + k.as_str() + .filter(|k| col_key_ok(fields, k)) + .map(str::to_string) + }) + .collect::>()?; + if keys.iter().collect::>().len() != keys.len() { + return None; + } + Some(keys) + } + }; + let date = match o.get("date") { + None => None, + Some(d) => { + let ids: Vec = d + .as_array()? + .iter() + .map(|x| int_in(Some(x), 1, 255).map(|x| x as u8)) + .collect::>()?; + let types: Vec> = ids + .iter() + .map(|id| fields.iter().find(|f| f.id == *id).map(|f| f.kind)) + .collect(); + let iter = types == [Some(FieldType::Iter)]; + let range = types == [Some(FieldType::Date), Some(FieldType::Date)] && ids[0] != ids[1]; + if !iter && !range { + return None; + } + Some(ids) + } + }; + Some(BoardView { + id, + name, + layout, + q, + group, + lane, + sort, + cols, + date, + }) +} + +fn parse_views(v: Option<&Value>, fields: &[BoardField]) -> Result, SpecError> { + let Some(v) = v else { return Ok(Vec::new()) }; + let list = v + .as_array() + .filter(|l| l.len() <= MAX_VIEWS) + .ok_or(SpecError::Views)?; + let out: Vec = list + .iter() + .map(|w| parse_view(w, fields).ok_or(SpecError::View)) + .collect::>()?; + if repeats(out.iter().map(|w| (w.id, w.name.as_str()))) { + return Err(SpecError::View); + } + Ok(out) +} + +/// Read a board definition (`board.spec`, §2): JSON, `v: 1`, at most 4096 UTF-8 bytes, every +/// limit of §8, ids 1–255 and unique, names unique in any letter case, every reference (`def`, +/// `done`, a view's keys) to something the spec defines. Unknown keys are tolerated and +/// dropped by [`serialize_spec`]; a known key of the wrong type or shape refuses the spec. +/// Checked in the canonical key order, so both clients name the same first problem. +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // arch 0..=3650 +pub fn parse_spec(json: &str) -> Result { + if json.len() > SPEC_MAX_BYTES { + return Err(SpecError::Size); + } + let raw: Value = serde_json::from_str(json).map_err(|_| SpecError::Json)?; + let Value::Object(raw) = raw else { + return Err(SpecError::Json); + }; + if int_in(raw.get("v"), 1, 1).is_none() { + return Err(SpecError::Version); + } + // an empty description is none (written as none) + let desc = match raw.get("desc") { + None => None, + Some(d) => Some(text_in(d, DESC_MAX).ok_or(SpecError::Desc)?).filter(|d| !d.is_empty()), + }; + let columns = parse_columns(raw.get("columns"))?; + let def = parse_column_ref(raw.get("def"), &columns, SpecError::Def)?; + let done = parse_column_ref(raw.get("done"), &columns, SpecError::Done)?; + let sources = parse_sources(raw.get("sources"))?; + let fields = parse_fields(raw.get("fields"))?; + let views = parse_views(raw.get("views"), &fields)?; + let arch = match raw.get("arch") { + None => 0, + Some(a) => int_in(Some(a), 0, ARCH_MAX).ok_or(SpecError::Arch)? as u16, + }; + Ok(BoardSpec { + v: 1, + desc, + columns, + def, + done, + sources, + fields, + views, + arch, + }) +} + +/// Write a definition as canonical compact JSON (the declared key order, defaults omitted), +/// so equal specs are equal bytes in both clients. Refused when it would not read back +/// ([`parse_spec`]'s error) or is over 4096 bytes: what this returns always parses to an +/// equal spec. +pub fn serialize_spec(spec: &BoardSpec) -> Result { + let json = serde_json::to_string(spec).map_err(|_| SpecError::Json)?; + let back = parse_spec(&json)?; + serde_json::to_string(&back).map_err(|_| SpecError::Json) +} + +/// The Monday (UTC) of the week holding `ms`, as `YYYY-MM-DD`. +#[must_use] +pub fn monday_of(ms: i64) -> String { + let days = ms.div_euclid(DAY_MS); + // 1970-01-01 was a Thursday: (days + 3) mod 7 is days since Monday + civil_from_days(days - (days + 3).rem_euclid(7)) +} + +/// The new-board template: Todo / In progress / Done (Done the done column, Todo the +/// default), the home repository's issues and pull requests, Priority (P0–P3), Estimate and a +/// two-week Iteration starting the Monday of the week of `now_ms`, a Board, a Table and a +/// Roadmap view, and auto-archive after 14 days. +#[must_use] +pub fn default_spec(home_repo_id: &str, now_ms: i64) -> BoardSpec { + let column = |id, name: &str| BoardColumn { + id, + name: name.into(), + color: None, + wip: None, + }; + let option = |id, name: &str, color: &str| FieldOption { + id, + name: name.into(), + color: Some(color.into()), + }; + let field = |id, name: &str, kind| BoardField { + id, + name: name.into(), + kind, + options: None, + start: None, + days: None, + }; + let view = |id, name: &str, layout| BoardView { + id, + name: name.into(), + layout, + q: String::new(), + group: None, + lane: None, + sort: None, + cols: None, + date: None, + }; + BoardSpec { + v: 1, + desc: None, + columns: vec![ + column(1, "Todo"), + column(2, "In progress"), + column(3, "Done"), + ], + def: 1, + done: 3, + sources: vec![BoardSource { + r: Some(home_repo_id.to_string()), + k: SourceKind::All, + q: String::new(), + }], + fields: vec![ + BoardField { + options: Some(vec![ + option(1, "P0", "#d1242f"), + option(2, "P1", "#fb8f44"), + option(3, "P2", "#d4a72c"), + option(4, "P3", "#8c959f"), + ]), + ..field(1, "Priority", FieldType::Sel) + }, + field(2, "Estimate", FieldType::Num), + BoardField { + start: Some(monday_of(now_ms)), + days: Some(14), + ..field(3, "Iteration", FieldType::Iter) + }, + ], + views: vec![ + view(1, "Board", ViewLayout::Board), + BoardView { + cols: Some( + ["title", "status", "assignees", "f1", "f2", "f3"] + .map(String::from) + .to_vec(), + ), + ..view(2, "Table", ViewLayout::Table) + }, + BoardView { + date: Some(vec![3]), + ..view(3, "Roadmap", ViewLayout::Roadmap) + }, + ], + arch: 14, + } +} + +// --------------------------------------------------------------------------------------------- +// Card field values (§3.2 `f`) +// --------------------------------------------------------------------------------------------- + +/// A card's field values by field id (ascending, as JSON keys). +pub type FieldValues = BTreeMap; + +/// `v` as a value of `field`, if it is a valid one (`-0` reads as 0). +#[allow(clippy::float_cmp)] // -0 == 0 +fn field_value(field: &BoardField, v: &Value) -> Option { + match field.kind { + FieldType::Sel => { + let id = int_in(Some(v), 1, 255)?; + field + .options + .as_deref() + .unwrap_or_default() + .iter() + .any(|o| i64::from(o.id) == id) + .then(|| Scalar::from(id)) + } + FieldType::Num => { + let x = v.as_f64().filter(|x| x.is_finite())?; + (x.abs() <= NUM_ABS_MAX && (x == 0.0 || x.abs() >= NUM_ABS_MIN)) + .then_some(Scalar::Num(if x == 0.0 { 0.0 } else { x })) + } + FieldType::Date => v + .as_str() + .filter(|s| date_days(s).is_some()) + .map(|s| Scalar::Text(s.to_string())), + FieldType::Iter => int_in(Some(v), 0, ITER_INDEX_MAX).map(Scalar::from), + FieldType::Text => v + .as_str() + .filter(|s| !s.is_empty() && char_len(s) <= TEXT_VALUE_MAX) + .map(|s| Scalar::Text(s.to_string())), + } +} + +fn valid_values<'a>( + entries: impl Iterator, + spec: &BoardSpec, +) -> FieldValues { + let mut out = FieldValues::new(); + for (key, v) in entries { + let canonical = !key.is_empty() + && key.len() <= 3 + && !key.starts_with('0') + && key.bytes().all(|b| b.is_ascii_digit()); + let Some(field) = canonical + .then(|| key.parse::().ok()) + .flatten() + .and_then(|id| spec.field(id)) + else { + continue; + }; + if let Some(value) = field_value(field, v) { + out.insert(field.id, value); + } + } + out +} + +/// A card's field values (`card.f`, `{"": value}`), keeping only those `spec` +/// defines with a value of the field's type (a deleted field, a deleted option, a wrong type +/// are dropped). Not JSON or not an object reads as none. +#[must_use] +pub fn parse_field_values(json: Option<&str>, spec: &BoardSpec) -> FieldValues { + let Some(json) = json.filter(|j| !j.is_empty()) else { + return FieldValues::new(); + }; + match serde_json::from_str::(json) { + Ok(Value::Object(o)) => valid_values(o.iter(), spec), + _ => FieldValues::new(), + } +} + +/// Field values as canonical JSON (ids ascending, invalid entries dropped as +/// [`parse_field_values`] drops them, numbers as JavaScript writes them); `None` over 2048 +/// bytes. +#[must_use] +pub fn serialize_field_values(values: &FieldValues, spec: &BoardSpec) -> Option { + let mut out = String::from("{"); + for (id, v) in values { + let Some(field) = spec.field(*id) else { + continue; + }; + let raw = match v { + Scalar::Num(x) => serde_json::Number::from_f64(*x).map(Value::Number), + Scalar::Text(t) => Some(Value::String(t.clone())), + }; + if raw.and_then(|r| field_value(field, &r)).is_none() { + continue; + } + if out.len() > 1 { + out.push(','); + } + let _ = write!(out, "\"{id}\":"); + match v { + Scalar::Num(x) => out.push_str(&js_number(*x)), + Scalar::Text(t) => out.push_str(&serde_json::to_string(t).unwrap_or_default()), + } + } + out.push('}'); + (out.len() <= FIELD_VALUES_MAX_BYTES).then_some(out) +} + +// --------------------------------------------------------------------------------------------- +// Rank (§2.6) +// --------------------------------------------------------------------------------------------- + +/// The 62 rank digits, in ASCII (byte) order. +pub const RANK_DIGITS: &[u8; 62] = + b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + +/// A rank digit's value 0–61. +fn digit_of(c: u8) -> Option { + match c { + b'0'..=b'9' => Some(u32::from(c - b'0')), + b'A'..=b'Z' => Some(u32::from(c - b'A') + 10), + b'a'..=b'z' => Some(u32::from(c - b'a') + 36), + _ => None, + } +} + +fn digit(x: u32) -> char { + char::from(RANK_DIGITS[x as usize]) +} + +/// Whether `r` is a well-formed explicit rank: 1–63 digits, not ending in `0` (the +/// `card.rank` pattern). +#[must_use] +pub fn is_explicit_rank(r: &str) -> bool { + (1..=RANK_MAX).contains(&r.len()) + && r.bytes().all(|b| digit_of(b).is_some()) + && !r.ends_with('0') +} + +/// Why no rank was made (the web's `RankError`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RankError { + /// A bound is not 0–63 rank digits. + Invalid, + /// The lower bound is above the upper. + Order, + /// No rank of at most 63 digits fits (the bounds are equal, or `b` is `a` + `0…0`, or the + /// gap is used up): re-rank the column (§2.6). + Rerank, +} + +impl RankError { + /// The code both clients name it by. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Invalid => "invalid", + Self::Order => "order", + Self::Rerank => "re-rank", + } + } +} + +impl std::fmt::Display for RankError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Rerank => "Re-rank this column", + other => other.as_str(), + }) + } +} + +impl std::error::Error for RankError {} + +/// A rank strictly between `a` and `b` in byte order (`""` is open: below everything / above +/// everything), ending in a non-zero digit, at most 63 digits: the web's `rankBetween`, whose +/// comment gives the construction and why it is strictly between. +pub fn rank_between(a: &str, b: &str) -> Result { + let ok = |r: &str| r.len() <= RANK_MAX && r.bytes().all(|c| digit_of(c).is_some()); + if !ok(a) || !ok(b) { + return Err(RankError::Invalid); + } + if !b.is_empty() && a >= b { + // two members dropping into one gap at once write one rank: nothing lies between them + return Err(if a == b { + RankError::Rerank + } else { + RankError::Order + }); + } + let (lo, hi) = (a.as_bytes(), b.as_bytes()); + let mut out = String::new(); + let mut lo_tight = true; + let mut hi_tight = !hi.is_empty(); + for i in 0.. { + if i >= RANK_MAX || (hi_tight && i >= hi.len()) { + return Err(RankError::Rerank); + } + let in_lo = lo_tight && i < lo.len(); + let floor = if in_lo { + digit_of(lo[i]).unwrap_or(0) + } else { + 0 + }; + let hd = if hi_tight { + digit_of(hi[i]).unwrap_or(0) + } else { + 62 + }; + let ceil = if hi_tight && i + 1 < hi.len() { + hd + 1 + } else { + hd + }; + if ceil >= floor + 2 { + out.push(digit(floor.midpoint(ceil))); + return Ok(out); + } + lo_tight = in_lo; + hi_tight = hi_tight && floor == hd; + out.push(digit(floor)); + } + unreachable!("the loop returns by RANK_MAX") +} + +/// `n` in `width` base-62 digits (clamped to 0 … 62^width − 1). +fn base62(n: i64, width: u32) -> String { + let max = 62_i64.pow(width) - 1; + let mut v = n.clamp(0, max); + let mut out = vec![b'0'; width as usize]; + for slot in out.iter_mut().rev() { + *slot = RANK_DIGITS[usize::try_from(v % 62).unwrap_or(0)]; + v /= 62; + } + String::from_utf8(out).unwrap_or_default() +} + +/// The rank of an item with no card, or whose newest card has no rank: `V`, its +/// `$createdAt` in 8 base-62 digits, the first 3 bytes of its `$id` (big-endian, mod 62⁴) in 4. +#[must_use] +pub fn implicit_rank(created_at_ms: i64, item_id_bytes: &[u8]) -> String { + let byte = |i: usize| i64::from(item_id_bytes.get(i).copied().unwrap_or(0)); + let head = (byte(0) << 16) | (byte(1) << 8) | byte(2); + format!( + "V{}{}", + base62(created_at_ms, 8), + base62(head % 62_i64.pow(4), 4) + ) +} + +/// The bytes of a base58 id (the web's `base58Decode`); none when it is not base58. +fn base58_bytes(s: &str) -> Vec { + const ALPHABET: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + // little-endian magnitude + let mut le: Vec = Vec::new(); + for c in s.bytes() { + let Some(d) = ALPHABET.iter().position(|&a| a == c) else { + return Vec::new(); + }; + let mut carry = u32::try_from(d).unwrap_or(0); + for b in &mut le { + carry += u32::from(*b) * 58; + *b = (carry & 0xff) as u8; + carry >>= 8; + } + while carry > 0 { + le.push((carry & 0xff) as u8); + carry >>= 8; + } + } + let zeros = s.bytes().take_while(|&c| c == b'1').count(); + let mut out = vec![0; zeros]; + out.extend(le.iter().rev()); + out +} + +/// [`implicit_rank`] of an item by its base58 `$id`. +#[must_use] +pub fn implicit_rank_of(created_at_ms: i64, item_id: &str) -> String { + implicit_rank(created_at_ms, &base58_bytes(item_id)) +} + +/// The rank that puts a card at the top of a column whose first rank is `first` (`None`: +/// empty), above the sourced pool. +pub fn top_rank(first: Option<&str>) -> Result { + rank_between("", first.filter(|f| *f <= "V").unwrap_or("V")) +} + +/// The rank that puts a card at the bottom of a column whose last rank is `last` (`None`: +/// empty), below the sourced pool. +pub fn bottom_rank(last: Option<&str>) -> Result { + rank_between(last.filter(|l| *l >= "W").unwrap_or("W"), "") +} + +/// `n` evenly spaced explicit ranks, ascending, for re-ranking a column (§2.6): rank k is +/// k/(n+1) of the way from `0` to `V`, in the fewest digits that leave 62 free ranks between +/// neighbours, trailing zeros dropped. `Invalid` past 1 000 000. +pub fn rerank(n: u64) -> Result, RankError> { + if n > RERANK_MAX { + return Err(RankError::Invalid); + } + let n = i64::try_from(n).map_err(|_| RankError::Invalid)?; + let mut width = 1; + while 31 * 62_i64.pow(width - 1) < 62 * (n + 1) { + width += 1; + } + let space = 31 * 62_i64.pow(width - 1); + Ok((1..=n) + .map(|k| { + base62(k * space / (n + 1), width) + .trim_end_matches('0') + .to_string() + }) + .collect()) +} + +// --------------------------------------------------------------------------------------------- +// Iterations (§2.2) +// --------------------------------------------------------------------------------------------- + +/// One iteration of an `iter` field: index k, named " k+1", `start` … `end` (the last +/// day, inclusive). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct IterationRange { + /// k. + pub index: i64, + /// " k+1". + pub name: String, + /// The first day. + pub start: String, + /// The last day. + pub end: String, + /// `start`'s midnight UTC. + pub start_ms: i64, + /// The next iteration's (exclusive end). + pub end_ms: i64, +} + +/// An `iter` field's first day number and length. +fn iter_of(field: &BoardField) -> Option<(i64, i64)> { + if field.kind != FieldType::Iter { + return None; + } + let days = i64::from(field.days.filter(|d| *d > 0)?); + Some((date_days(field.start.as_deref()?)?, days)) +} + +/// The index of `field`'s iteration holding `date_ms` (UTC days); `None` before its first or +/// past index 65535, or not an `iter` field. +#[must_use] +pub fn iteration_at(field: &BoardField, date_ms: i64) -> Option { + let (start, days) = iter_of(field)?; + let k = (date_ms.div_euclid(DAY_MS) - start).div_euclid(days); + (0..=ITER_INDEX_MAX).contains(&k).then_some(k) +} + +/// Iteration `k` of `field`; `None` when not an `iter` field or `k` out of range. +#[must_use] +pub fn iteration_range(field: &BoardField, k: i64) -> Option { + let (start, days) = iter_of(field)?; + if !(0..=ITER_INDEX_MAX).contains(&k) { + return None; + } + let first = start + k * days; + let next = first + days; + Some(IterationRange { + index: k, + name: format!("{} {}", field.name, k + 1), + start: civil_from_days(first), + end: civil_from_days(next - 1), + start_ms: first * DAY_MS, + end_ms: next * DAY_MS, + }) +} + +// --------------------------------------------------------------------------------------------- +// Items, cards and placement (§2.4) +// --------------------------------------------------------------------------------------------- + +/// An issue or a pull request. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ItemKind { + /// An issue. + Issue, + /// A pull request. + Pr, +} + +/// An item's state. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ItemState { + /// Open. + Open, + /// Closed (not merged). + Closed, + /// Merged. + Merged, +} + +/// What a board reads of an issue or PR (the web's `BoardItem`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BoardItem { + /// The item's `$id`. + pub id: String, + /// Its number. + pub number: u64, + /// Its repository's id. + pub repo_id: String, + /// `owner/name`, as shown, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub repo: Option, + /// Issue or PR. + pub kind: ItemKind, + /// Open, closed or merged. + pub state: ItemState, + /// Its `$createdAt`. + pub created_at: i64, + /// The `$createdAt` of its latest transition into closed or merged. + pub closed_at: Option, + /// The title. + pub title: String, + /// Label names. + pub labels: Vec, + /// Assignee identity ids. + pub assignees: Vec, + /// The milestone's title. + pub milestone: Option, + /// The author's identity id. + pub author: String, +} + +/// Card `state` (§3.2): active. +pub const CARD_ACTIVE: i64 = 0; +/// Archived. +pub const CARD_ARCHIVED: i64 = 1; +/// Removed. +pub const CARD_REMOVED: i64 = 2; + +/// A `card` document as read (a private repo's opened); `col` / `rank` / `f` `None` when +/// absent or unreadable. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CardDoc { + /// `$id`. + pub id: String, + /// `$ownerId`. + pub owner_id: String, + /// `$updatedAt`. + pub updated_at: i64, + /// The item's `$id`. + pub item: String, + /// The column id. + pub col: Option, + /// The rank. + pub rank: Option, + /// The field values' JSON. + pub f: Option, + /// 0 active, 1 archived, 2 removed. + pub state: i64, +} + +/// Why an item is archived. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum ArchivedBy { + /// Its newest card says so. + Card, + /// Auto-archive (`arch`). + Auto, +} + +/// Where one item shows (§2.4). `col` 0 is "No status". +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Placement { + /// The item's `$id`. + pub id: String, + /// On the board: a source matches it or it has a card, and that card is not removed. + pub on: bool, + /// A source matches it. + pub sourced: bool, + /// Its newest card removed it. + pub removed: bool, + /// The newest card's `$id`. + pub card: Option, + /// The column. + pub col: u8, + /// The effective rank. + pub rank: String, + /// Why it is archived, if it is. + pub archived: Option, + /// Its field values. + pub fields: FieldValues, +} + +/// A column's visible items (on the board, not archived), in rank order. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ColumnItems { + /// The column id (0: "No status"). + pub id: u8, + /// Item ids. + pub items: Vec, +} + +/// A board folded (the web's `BoardFold`). +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BoardFold { + /// One per input item, in input order (repeated ids once). + pub items: Vec, + /// "No status" (0) first while it holds an item, then every column in order. + pub columns: Vec, +} + +/// Whether `(a_at, a_id)` is newer than `(b_at, b_id)`. +fn newer(a_at: i64, a_id: &str, b_at: i64, b_id: &str) -> bool { + (a_at, a_id) > (b_at, b_id) +} + +/// Every item's newest card over every member's, by (`$updatedAt`, `$id`) (§2.4). +#[must_use] +pub fn newest_cards(cards: &[CardDoc]) -> HashMap<&str, &CardDoc> { + let mut out: HashMap<&str, &CardDoc> = HashMap::new(); + for c in cards { + match out.get(c.item.as_str()) { + Some(prev) if !newer(c.updated_at, &c.id, prev.updated_at, &prev.id) => {} + _ => { + out.insert(&c.item, c); + } + } + } + out +} + +/// A `board` document as read; `spec` `None` when absent or unreadable. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BoardDoc { + /// `$id`. + pub id: String, + /// `$ownerId`. + pub owner_id: String, + /// `$updatedAt`. + pub updated_at: i64, + /// The board's key. + pub key: u32, + /// 0 open, 1 closed, 2 deleted. + pub state: i64, + /// The name. + pub name: Option, + /// The definition's JSON. + pub spec: Option, +} + +/// Board `state` (§3.1): deleted. +pub const BOARD_DELETED: i64 = 2; + +/// A repository's boards: per key the newest revision over every member's by +/// (`$updatedAt`, `$id`), ascending by key, less the deleted ones unless `with_deleted`. +#[must_use] +pub fn newest_boards(docs: &[BoardDoc], with_deleted: bool) -> Vec<&BoardDoc> { + let mut by_key: BTreeMap = BTreeMap::new(); + for d in docs { + match by_key.get(&d.key) { + Some(prev) if !newer(d.updated_at, &d.id, prev.updated_at, &prev.id) => {} + _ => { + by_key.insert(d.key, d); + } + } + } + by_key + .into_values() + .filter(|d| with_deleted || d.state != BOARD_DELETED) + .collect() +} + +/// Whether `source` includes `item` (§2.3): its repository (absent: `home`) and kind, and the +/// qualifiers of its query (`query`, [`parse_source_query`] of `source.q`). +#[must_use] +pub fn source_matches( + source: &BoardSource, + query: &BoardQuery, + item: &BoardItem, + home: &str, + spec: &BoardSpec, + now: i64, +) -> bool { + if source.r.as_deref().unwrap_or(home) != item.repo_id { + return false; + } + match source.k { + SourceKind::Issues if item.kind != ItemKind::Issue => return false, + SourceKind::Pulls if item.kind != ItemKind::Pr => return false, + _ => {} + } + query_holds(item, None, spec, query, &QueryContext { me: None, now }) +} + +/// Where every item shows (§2.4): the web's `foldBoard`, whose comment states the rules. +#[must_use] +pub fn fold_board( + spec: &BoardSpec, + home: &str, + items: &[BoardItem], + cards: &[CardDoc], + now: i64, +) -> BoardFold { + let newest = newest_cards(cards); + let source_queries: Vec<(&BoardSource, BoardQuery)> = spec + .sources + .iter() + .map(|s| (s, parse_source_query(&s.q, spec))) + .collect(); + let done_index = (spec.done != 0) + .then(|| spec.column_index(spec.done)) + .flatten(); + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for item in items { + if !seen.insert(item.id.as_str()) { + continue; + } + let card = newest.get(item.id.as_str()).copied(); + let sourced = source_queries + .iter() + .any(|(s, q)| source_matches(s, q, item, home, spec, now)); + let removed = card.is_some_and(|c| c.state == CARD_REMOVED); + let card_col = card + .and_then(|c| c.col) + .and_then(|c| u8::try_from(c).ok()) + .filter(|c| spec.column_index(*c).is_some()); + let finished = item.state != ItemState::Open; + let keeps = |d: usize| { + card_col + .and_then(|c| spec.column_index(c)) + .is_some_and(|i| i >= d) + }; + let col = match done_index { + Some(d) if finished && !keeps(d) => spec.done, + _ => card_col.unwrap_or(spec.def), + }; + let archived = if card.is_some_and(|c| c.state == CARD_ARCHIVED) { + Some(ArchivedBy::Card) + } else { + match item.closed_at { + Some(closed) + if spec.arch > 0 + && finished + && card.is_none_or(|c| c.updated_at < closed) + && now >= closed + i64::from(spec.arch) * DAY_MS => + { + Some(ArchivedBy::Auto) + } + _ => None, + } + }; + out.push(Placement { + id: item.id.clone(), + on: (sourced || card.is_some()) && !removed, + sourced, + removed, + card: card.map(|c| c.id.clone()), + col, + rank: card + .and_then(|c| c.rank.clone()) + .filter(|r| is_explicit_rank(r)) + .unwrap_or_else(|| implicit_rank_of(item.created_at, &item.id)), + archived, + fields: card.map_or_else(FieldValues::new, |c| { + parse_field_values(c.f.as_deref(), spec) + }), + }); + } + let mut visible: Vec<&Placement> = out + .iter() + .filter(|p| p.on && p.archived.is_none()) + .collect(); + visible.sort_by(|a, b| by_rank(&a.rank, &a.id, &b.rank, &b.id)); + let in_col = |id: u8| -> Vec { + visible + .iter() + .filter(|p| p.col == id) + .map(|p| p.id.clone()) + .collect() + }; + let none = in_col(0); + let mut columns = Vec::new(); + if !none.is_empty() { + columns.push(ColumnItems { id: 0, items: none }); + } + columns.extend(spec.columns.iter().map(|c| ColumnItems { + id: c.id, + items: in_col(c.id), + })); + BoardFold { + items: out, + columns, + } +} + +/// Order within a column (§2.6): (rank, item `$id`), both by code point. +#[must_use] +pub fn by_rank(a_rank: &str, a_id: &str, b_rank: &str, b_id: &str) -> Ordering { + (a_rank, a_id).cmp(&(b_rank, b_id)) +} + +// --------------------------------------------------------------------------------------------- +// Query (§4.4) +// --------------------------------------------------------------------------------------------- + +/// One qualifier (the web's `QueryPred`): every one ANDed, `not` for a leading `-`. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct QueryPred { + /// `is`, `label`, `milestone`, `assignee`, `author`, `repo`, `status`, `no` or `field`. + pub k: &'static str, + /// A leading `-`. + pub not: bool, + /// The value. + #[serde(skip_serializing_if = "Option::is_none")] + pub v: Option, + /// A `field` predicate's field id. + #[serde(skip_serializing_if = "Option::is_none")] + pub f: Option, + /// `eq`, `gt`, `ge`, `lt`, `le`, `range` or `has`. + #[serde(skip_serializing_if = "Option::is_none")] + pub op: Option<&'static str>, + /// A range's upper end. + #[serde(skip_serializing_if = "Option::is_none")] + pub v2: Option, +} + +impl QueryPred { + fn of(k: &'static str, not: bool, v: Scalar) -> Self { + Self { + k, + not, + v: Some(v), + f: None, + op: None, + v2: None, + } + } + + fn v_text(&self) -> &str { + self.v.as_ref().and_then(Scalar::text).unwrap_or("") + } +} + +/// A parsed board query. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BoardQuery { + /// The qualifiers. + pub preds: Vec, + /// The free text: matched against titles, `#12` / `12` against numbers. + pub text: String, + /// The qualifier tokens not applied, as typed. + pub unresolved: Vec, +} + +const IS_VALUES: &[&str] = &[ + "open", "closed", "merged", "unmerged", "issue", "pr", "archived", +]; +const STATE_VALUES: &[&str] = &["open", "closed", "merged", "unmerged"]; +const QUERY_KEYS: &[&str] = &[ + "is", + "state", + "label", + "milestone", + "assignee", + "author", + "repo", + "status", + "no", +]; +const LABEL_MAX: usize = 30; +const MILESTONE_MAX: usize = 63; +const ITER_RELATIVE: &[&str] = &["@current", "@next", "@previous"]; + +fn unquote(s: &str) -> String { + s.replace('"', "") +} + +/// A person value: an identity id, or `me` (`@me`, any case). +fn person_of(v: &str) -> Option { + let t = v.strip_prefix('@').unwrap_or(v); + if t.to_lowercase() == "me" { + return Some("me".into()); + } + is_identifier(t).then(|| t.to_string()) +} + +/// A comparison value's op and operand(s), still text. +fn comparison(v: &str) -> (&'static str, &str, Option<&str>) { + if let Some(at) = v.find("..") { + return ("range", &v[..at], Some(&v[at + 2..])); + } + for (prefix, op) in [(">=", "ge"), ("<=", "le"), (">", "gt"), ("<", "lt")] { + if let Some(rest) = v.strip_prefix(prefix) { + return (op, rest, None); + } + } + ("eq", v, None) +} + +/// `-?\d{1,15}(\.\d{1,15})?`. +fn is_query_number(s: &str) -> bool { + let body = s.strip_prefix('-').unwrap_or(s); + let (int, frac) = match body.split_once('.') { + Some((i, f)) => (i, Some(f)), + None => (body, None), + }; + let digits = |d: &str| (1..=15).contains(&d.len()) && d.bytes().all(|b| b.is_ascii_digit()); + digits(int) && frac.is_none_or(digits) +} + +/// A typed comparison operand. +fn operand(field: &BoardField, s: &str) -> Option { + match field.kind { + FieldType::Num => is_query_number(s) + .then(|| s.parse::().ok()) + .flatten() + .map(Scalar::Num), + FieldType::Date => { + if s.to_lowercase() == "@today" { + Some(Scalar::Text("@today".into())) + } else { + date_days(s).map(|_| Scalar::Text(s.to_string())) + } + } + FieldType::Iter => { + let low = s.to_lowercase(); + if ITER_RELATIVE.contains(&low.as_str()) { + return Some(Scalar::Text(low)); + } + // `3` or `"Iteration 3"`: iteration 3, index 2 + let prefix = format!("{} ", field.name.to_lowercase()); + let n = low.strip_prefix(&prefix).unwrap_or(&low); + let ok = (1..=5).contains(&n.len()) + && !n.starts_with('0') + && n.bytes().all(|b| b.is_ascii_digit()); + ok.then(|| n.parse::().ok()) + .flatten() + .filter(|n| n - 1 <= ITER_INDEX_MAX) + .map(|n| Scalar::from(n - 1)) + } + _ => None, + } +} + +/// A custom-field qualifier's predicate. +fn field_pred(field: &BoardField, value: &str, not: bool) -> Option { + if value.is_empty() { + return None; + } + let pred = |op: &'static str, v: Scalar, v2: Option| QueryPred { + k: "field", + not, + v: Some(v), + f: Some(field.id), + op: Some(op), + v2, + }; + match field.kind { + FieldType::Sel => { + let low = value.to_lowercase(); + let opt = field + .options + .as_deref() + .unwrap_or_default() + .iter() + .find(|o| o.name.to_lowercase() == low)?; + Some(pred("eq", Scalar::from(i64::from(opt.id)), None)) + } + FieldType::Text => (char_len(value) <= TEXT_VALUE_MAX) + .then(|| pred("has", Scalar::Text(value.to_lowercase()), None)), + _ => match comparison(value) { + ("range", a, Some(b)) => { + if a == "*" && b == "*" { + return None; + } + let lo = if a == "*" { + None + } else { + Some(operand(field, a)?) + }; + let hi = if b == "*" { + None + } else { + Some(operand(field, b)?) + }; + match (lo, hi) { + (None, Some(hi)) => Some(pred("le", hi, None)), + (Some(lo), None) => Some(pred("ge", lo, None)), + (Some(lo), Some(hi)) => Some(pred("range", lo, Some(hi))), + (None, None) => None, + } + } + (op, a, _) => operand(field, a).map(|v| pred(op, v, None)), + }, + } +} + +/// Read a board query (§4.4): the web's `parseBoardQuery`, whose comment lists the grammar. +#[must_use] +pub fn parse_board_query(text: &str, spec: &BoardSpec) -> BoardQuery { + parse_query(text, spec, false) +} + +/// A source's query (§2.3): [`parse_board_query`] less what depends on the board or the +/// reader rather than the item (`status:`, `no:status`, custom fields, `is:archived`, `@me`), +/// which goes to `unresolved`. +#[must_use] +pub fn parse_source_query(text: &str, spec: &BoardSpec) -> BoardQuery { + parse_query(text, spec, true) +} + +/// Whether a predicate reads the board or the reader, not only the item. +fn board_only(p: &QueryPred) -> bool { + match p.k { + "status" | "field" => true, + "no" => p.v_text() == "status" || field_key_id(p.v_text()).is_some(), + "is" => p.v_text() == "archived", + "assignee" | "author" => p.v_text() == "me", + _ => false, + } +} + +fn parse_query(text: &str, spec: &BoardSpec, for_source: bool) -> BoardQuery { + let mut preds = Vec::new(); + let mut free: Vec = Vec::new(); + let mut unresolved = Vec::new(); + let field_by_name: HashMap = spec + .fields + .iter() + .map(|f| (f.name.to_lowercase(), f)) + .collect(); + for tok in tokens(text) { + let at = tok.find(':').filter(|&at| at > 0); + let raw_key = at.map_or("", |at| &tok[..at]); + let not = raw_key.len() > 1 && raw_key.starts_with('-'); + let key = unquote(if not { &raw_key[1..] } else { raw_key }).to_lowercase(); + let raw_value = at.map_or("", |at| &tok[at + 1..]); + let value = unquote(raw_value); + if key.is_empty() + || (value.is_empty() + && !QUERY_KEYS.contains(&key.as_str()) + && !field_by_name.contains_key(&key)) + || raw_value.starts_with("//") + { + free.push(tok); + continue; + } + match qualifier(&key, &value, not, spec, &field_by_name) { + Some(pred) if !(for_source && board_only(&pred)) => preds.push(pred), + _ => unresolved.push(tok), + } + } + BoardQuery { + preds, + text: free.join(" "), + unresolved, + } +} + +fn qualifier( + key: &str, + value: &str, + not: bool, + spec: &BoardSpec, + field_by_name: &HashMap, +) -> Option { + let low = value.to_lowercase(); + match key { + "is" | "state" => { + let ok = if key == "is" { IS_VALUES } else { STATE_VALUES }; + ok.contains(&low.as_str()) + .then(|| QueryPred::of("is", not, Scalar::Text(low))) + } + "label" => (!value.is_empty() && char_len(value) <= LABEL_MAX) + .then(|| QueryPred::of("label", not, Scalar::Text(value.into()))), + "milestone" => (!value.is_empty() && char_len(value) <= MILESTONE_MAX) + .then(|| QueryPred::of("milestone", not, Scalar::Text(value.into()))), + "assignee" | "author" => { + let k = if key == "author" { + "author" + } else { + "assignee" + }; + person_of(value).map(|who| QueryPred::of(k, not, Scalar::Text(who))) + } + "repo" => { + (!value.is_empty()).then(|| QueryPred::of("repo", not, Scalar::Text(value.into()))) + } + "status" => spec + .columns + .iter() + .find(|c| c.name.to_lowercase() == low) + .map(|c| QueryPred::of("status", not, Scalar::from(i64::from(c.id)))), + "no" => { + if ["label", "assignee", "milestone", "status"].contains(&low.as_str()) { + return Some(QueryPred::of("no", not, Scalar::Text(low))); + } + field_by_name + .get(&low) + .map(|f| QueryPred::of("no", not, Scalar::Text(format!("f{}", f.id)))) + } + _ => field_pred(field_by_name.get(key)?, value, not), + } +} + +/// What a query reads besides the item: the viewer (`@me`) and the time (`@today`, +/// `@current`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QueryContext { + /// The viewer's identity id. + pub me: Option, + /// Now, in ms. + pub now: i64, +} + +/// An operand resolved: `@today` to today's date, the relative iterations to indices. +fn resolve_operand(field: &BoardField, v: &Scalar, ctx: &QueryContext) -> Option { + match v.text() { + Some("@today") => Some(Scalar::Text(date_of(ctx.now))), + Some(rel) if ITER_RELATIVE.contains(&rel) => { + // before the first iteration there is no current one, and the next is the first + let cur = iteration_at(field, ctx.now); + let start = field.start.as_deref().and_then(date_days).unwrap_or(0); + let before = ctx.now < start * DAY_MS; + let k = match rel { + "@current" => cur, + "@next" => cur.map(|c| c + 1).or(before.then_some(0)), + _ => cur.filter(|c| *c > 0).map(|c| c - 1), + }; + k.map(Scalar::from) + } + _ => Some(v.clone()), + } +} + +fn compare(x: &Scalar, y: &Scalar) -> Ordering { + match (x, y) { + (Scalar::Num(a), Scalar::Num(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal), + _ => x.display().cmp(&y.display()), + } +} + +fn field_holds( + p: &QueryPred, + field: &BoardField, + value: Option<&Scalar>, + ctx: &QueryContext, +) -> bool { + let Some(value) = value else { return false }; + let Some(pv) = p.v.as_ref() else { return false }; + if p.op == Some("has") { + return value.display().to_lowercase().contains(&pv.display()); + } + let Some(a) = resolve_operand(field, pv, ctx) else { + return false; + }; + let c = compare(value, &a); + match p.op { + Some("eq") => c == Ordering::Equal, + Some("gt") => c == Ordering::Greater, + Some("ge") => c != Ordering::Less, + Some("lt") => c == Ordering::Less, + Some("le") => c != Ordering::Greater, + Some("range") => { + p.v2.as_ref() + .and_then(|b| resolve_operand(field, b, ctx)) + .is_some_and(|b| c != Ordering::Less && compare(value, &b) != Ordering::Greater) + } + _ => false, + } +} + +/// Whether the item's title and number hold every free-text term (the Issues tab's +/// `matches_text`, without a body). +fn text_matches(text: &str, item: &BoardItem) -> bool { + let title = item.title.to_lowercase(); + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + search_terms(text).iter().all(|t| { + let holds = if let Some(n) = t.text.strip_prefix('#').filter(|n| digits(n)) { + n.parse::().ok() == Some(item.number) + } else { + (digits(&t.text) && t.text.parse::().ok() == Some(item.number)) + || title.contains(&t.text) + }; + holds != t.not + }) +} + +fn pred_holds( + p: &QueryPred, + item: &BoardItem, + placement: Option<&Placement>, + spec: &BoardSpec, + ctx: &QueryContext, +) -> bool { + let eqi = |a: &str, b: &str| a.to_lowercase() == b.to_lowercase(); + let v = p.v_text(); + match p.k { + "is" => match v { + "open" => item.state == ItemState::Open, + "closed" => item.state != ItemState::Open, + "merged" => item.state == ItemState::Merged, + "unmerged" => item.state != ItemState::Merged, + "issue" => item.kind == ItemKind::Issue, + "pr" => item.kind == ItemKind::Pr, + _ => placement.is_some_and(|pl| pl.archived.is_some()), + }, + "label" => item.labels.iter().any(|l| eqi(l, v)), + "milestone" => item.milestone.as_deref().is_some_and(|m| eqi(m, v)), + "assignee" | "author" => { + let who = if v == "me" { + ctx.me.as_deref() + } else { + Some(v) + }; + who.is_some_and(|who| { + if p.k == "author" { + item.author == who + } else { + item.assignees.iter().any(|a| a == who) + } + }) + } + "repo" => item.repo_id == v || item.repo.as_deref().is_some_and(|r| eqi(r, v)), + "status" => placement.is_some_and(|pl| Some(Scalar::from(i64::from(pl.col))) == p.v), + "no" => match v { + "label" => item.labels.is_empty(), + "assignee" => item.assignees.is_empty(), + "milestone" => item.milestone.is_none(), + "status" => placement.is_some_and(|pl| pl.col == 0), + key => placement + .is_some_and(|pl| field_key_id(key).is_none_or(|id| !pl.fields.contains_key(&id))), + }, + "field" => { + let field = p.f.and_then(|id| spec.field(id)); + match (field, placement) { + (Some(field), Some(pl)) => field_holds(p, field, pl.fields.get(&field.id), ctx), + _ => false, + } + } + _ => false, + } +} + +/// Whether an item (with its placement; none for a source) holds every predicate, each +/// negated by `-`, and the free text. +fn query_holds( + item: &BoardItem, + placement: Option<&Placement>, + spec: &BoardSpec, + query: &BoardQuery, + ctx: &QueryContext, +) -> bool { + query + .preds + .iter() + .all(|p| pred_holds(p, item, placement, spec, ctx) != p.not) + && text_matches(&query.text, item) +} + +/// Whether an item on the board passes `query` (§4.4): on the board, archived exactly when +/// the query has `is:archived`, holding every predicate and the free text. A value the item +/// lacks never matches its qualifier (so `-priority:P0` matches an item with no priority). +#[must_use] +pub fn matches_board_query( + item: &BoardItem, + placement: &Placement, + spec: &BoardSpec, + query: &BoardQuery, + ctx: &QueryContext, +) -> bool { + if !placement.on { + return false; + } + let wants_archived = query + .preds + .iter() + .any(|p| p.k == "is" && p.v_text() == "archived"); + if !wants_archived && placement.archived.is_some() { + return false; + } + query_holds(item, Some(placement), spec, query, ctx) +} + +// --------------------------------------------------------------------------------------------- +// Views: grouping, sorting, totals, progress (§4.1–§4.5) +// --------------------------------------------------------------------------------------------- + +/// An item with its placement, as views take them. +#[derive(Debug, Clone, Copy)] +pub struct BoardRow<'a> { + /// The item. + pub item: &'a BoardItem, + /// Where it shows. + pub placement: &'a Placement, +} + +/// A group: its key (a column id for `status`, 0 for "No status"; an option id; an iteration +/// index; an identity id; a label or milestone name; a repo id; `None` for "No ") and +/// its items. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct RowGroup { + /// The key. + pub key: Option, + /// Item ids. + pub items: Vec, +} + +/// A map key for a [`Scalar`]. +fn scalar_key(s: &Scalar) -> String { + match s { + Scalar::Num(x) => format!("n{}", js_number(*x)), + Scalar::Text(t) => format!("s{t}"), + } +} + +/// `rows` grouped by `by` (a view's `group` or `lane` key): the web's `groupRows`, whose +/// comment gives the order. +#[must_use] +pub fn group_rows(rows: &[BoardRow<'_>], by: &str, spec: &BoardSpec, now: i64) -> Vec { + let field = field_of_key(&spec.fields, by); + let keys_of = |r: &BoardRow<'_>| -> Vec> { + let dedup = |v: &[String]| -> Vec> { + let mut seen = HashSet::new(); + v.iter() + .filter(|x| seen.insert(x.as_str())) + .map(|x| Some(Scalar::Text(x.clone()))) + .collect() + }; + match by { + "status" => { + vec![(r.placement.col != 0).then(|| Scalar::from(i64::from(r.placement.col)))] + } + "assignee" if !r.item.assignees.is_empty() => dedup(&r.item.assignees), + "label" if !r.item.labels.is_empty() => dedup(&r.item.labels), + "assignee" | "label" => vec![None], + "milestone" => vec![r.item.milestone.clone().map(Scalar::Text)], + "repo" => vec![Some(Scalar::Text(r.item.repo_id.clone()))], + _ => vec![field.and_then(|f| r.placement.fields.get(&f.id).cloned())], + } + }; + let order: Vec = if by == "status" { + spec.columns + .iter() + .map(|c| Scalar::from(i64::from(c.id))) + .collect() + } else if field.is_some_and(|f| f.kind == FieldType::Sel) { + field + .and_then(|f| f.options.as_deref()) + .unwrap_or_default() + .iter() + .map(|o| Scalar::from(i64::from(o.id))) + .collect() + } else if field.is_some_and(|f| f.kind == FieldType::Iter) + || ["assignee", "label", "milestone", "repo"].contains(&by) + { + let mut present: Vec = Vec::new(); + let mut seen = HashSet::new(); + let mut add = |k: Scalar| { + if seen.insert(scalar_key(&k)) { + present.push(k); + } + }; + for r in rows { + for k in keys_of(r).into_iter().flatten() { + add(k); + } + } + if let Some(f) = field { + if let Some(cur) = iteration_at(f, now) { + add(Scalar::from(cur)); + } + } + present.sort_by(compare); + present + } else { + return vec![RowGroup { + key: None, + items: rows.iter().map(|r| r.item.id.clone()).collect(), + }]; + }; + let index: HashMap = order + .iter() + .enumerate() + .map(|(i, k)| (scalar_key(k), i)) + .collect(); + let mut empty = Vec::new(); + let mut groups: Vec> = vec![Vec::new(); order.len()]; + for r in rows { + for k in keys_of(r) { + match k { + None => empty.push(r.item.id.clone()), + Some(k) => { + if let Some(&i) = index.get(&scalar_key(&k)) { + groups[i].push(r.item.id.clone()); + } + } + } + } + } + let mut out = Vec::new(); + if !empty.is_empty() { + out.push(RowGroup { + key: (by == "status").then(|| Scalar::from(0)), + items: empty, + }); + } + out.extend(order.into_iter().zip(groups).map(|(k, items)| RowGroup { + key: Some(k), + items, + })); + out +} + +/// A row's sort value under `key` (no `-`); `None` when it has none (sorted last). +fn sort_value(r: &BoardRow<'_>, key: &str, spec: &BoardSpec) -> Option { + let index = |i: usize| Scalar::from(i64::try_from(i).unwrap_or(i64::MAX)); + match key { + "title" => Some(Scalar::Text(r.item.title.to_lowercase())), + #[allow(clippy::cast_precision_loss)] // issue numbers: far below 2^53 + "number" => Some(Scalar::Num(r.item.number as f64)), + "created" => Some(Scalar::from(r.item.created_at)), + "status" => spec.column_index(r.placement.col).map(index), + "repo" => Some(Scalar::Text( + r.item + .repo + .as_deref() + .unwrap_or(&r.item.repo_id) + .to_lowercase(), + )), + "author" => Some(Scalar::Text(r.item.author.clone())), + "milestone" => r + .item + .milestone + .as_ref() + .map(|m| Scalar::Text(m.to_lowercase())), + _ => { + let field = field_of_key(&spec.fields, key)?; + let v = r.placement.fields.get(&field.id)?; + Some(match field.kind { + FieldType::Sel => field + .options + .as_deref() + .unwrap_or_default() + .iter() + .position(|o| *v == Scalar::from(i64::from(o.id))) + .map_or(Scalar::from(-1), index), + FieldType::Text => Scalar::Text(v.display().to_lowercase()), + _ => v.clone(), + }) + } + } +} + +/// `rows` in a view's `sort` (`None` or `rank`: the column order, §2.6): by the key, `-` for +/// descending; rows without a value last in both directions; ties by (rank, item id). +#[must_use] +pub fn sort_rows<'a>( + rows: &[BoardRow<'a>], + sort: Option<&str>, + spec: &BoardSpec, +) -> Vec> { + let desc = sort.is_some_and(|s| s.starts_with('-')); + let key = sort.map_or("rank", |s| s.strip_prefix('-').unwrap_or(s)); + let tie = |a: &BoardRow<'_>, b: &BoardRow<'_>| { + by_rank( + &a.placement.rank, + &a.placement.id, + &b.placement.rank, + &b.placement.id, + ) + }; + let mut out = rows.to_vec(); + if key == "rank" { + out.sort_by(|a, b| if desc { tie(b, a) } else { tie(a, b) }); + return out; + } + out.sort_by( + |a, b| match (sort_value(a, key, spec), sort_value(b, key, spec)) { + (None, None) => tie(a, b), + (None, Some(_)) => Ordering::Greater, + (Some(_), None) => Ordering::Less, + (Some(x), Some(y)) => { + let c = compare(&x, &y); + let c = if desc { c.reverse() } else { c }; + c.then_with(|| tie(a, b)) + } + }, + ); + out +} + +/// The number field a view sums (§4.5): the first `num` field of its `cols`, or with no +/// `cols` the spec's first. +#[must_use] +pub fn sum_field_of(spec: &BoardSpec, view: Option<&BoardView>) -> Option { + let keys: Vec = view + .and_then(|v| v.cols.clone()) + .unwrap_or_else(|| spec.fields.iter().map(|f| format!("f{}", f.id)).collect()); + keys.iter() + .filter_map(|k| field_of_key(&spec.fields, k)) + .find(|f| f.kind == FieldType::Num) + .map(|f| f.id) +} + +/// A group's totals: its item count and the sum of a number field (`None` with none). +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Totals { + /// Items. + pub count: usize, + /// The sum. + pub sum: Option, +} + +/// `rows`' count and the sum of number field `sum_field`'s values (in `rows`' order). +#[must_use] +pub fn totals(rows: &[BoardRow<'_>], sum_field: Option) -> Totals { + let sum = sum_field.map(|id| { + let mut sum = 0.0; + for r in rows { + if let Some(Scalar::Num(x)) = r.placement.fields.get(&id) { + sum += x; + } + } + Scalar::Num(sum) + }); + Totals { + count: rows.len(), + sum, + } +} + +/// A status column's totals (§4.5) and its WIP limit; `over` when the count passes it. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ColumnTotals { + /// The column id (0: "No status"). + pub id: u8, + /// Items. + pub count: usize, + /// The sum. + pub sum: Option, + /// The WIP limit. + pub wip: Option, + /// Over the WIP limit. + pub over: bool, +} + +/// Every status column's totals for `rows` (as [`group_rows`] by `status` groups them). +#[must_use] +pub fn column_totals( + rows: &[BoardRow<'_>], + spec: &BoardSpec, + sum_field: Option, +) -> Vec { + let by_id: HashMap<&str, &BoardRow<'_>> = + rows.iter().map(|r| (r.item.id.as_str(), r)).collect(); + group_rows(rows, "status", spec, 0) + .into_iter() + .map(|g| { + let in_group: Vec> = g + .items + .iter() + .filter_map(|id| by_id.get(id.as_str()).map(|r| **r)) + .collect(); + let t = totals(&in_group, sum_field); + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // column ids + let id = g.key.as_ref().and_then(Scalar::num).unwrap_or(0.0) as u8; + let wip = spec.columns.iter().find(|c| c.id == id).and_then(|c| c.wip); + ColumnTotals { + id, + count: t.count, + sum: t.sum, + wip, + over: wip.is_some_and(|w| t.count > usize::from(w)), + } + }) + .collect() +} + +/// An iteration's progress (§4.5): items and points, all and done. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct IterationProgress { + /// Items in the iteration. + pub total: usize, + /// Of them done. + pub done: usize, + /// Their points (`None` without a points field). + pub points: Option, + /// The done ones' points. + pub done_points: Option, +} + +/// Progress of iteration `k` of field `field_id` over `rows`: the rows whose value is `k`; +/// done is in the Done column, or closed or merged. +#[must_use] +pub fn iteration_progress( + rows: &[BoardRow<'_>], + spec: &BoardSpec, + field_id: u8, + k: i64, + points_field: Option, +) -> IterationProgress { + let want = Scalar::from(k); + let in_iter: Vec> = rows + .iter() + .filter(|r| r.placement.fields.get(&field_id) == Some(&want)) + .copied() + .collect(); + let done: Vec> = in_iter + .iter() + .filter(|r| { + (spec.done != 0 && r.placement.col == spec.done) || r.item.state != ItemState::Open + }) + .copied() + .collect(); + let all = totals(&in_iter, points_field); + let fin = totals(&done, points_field); + IterationProgress { + total: all.count, + done: fin.count, + points: all.sum, + done_points: fin.sum, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/forge-core/src/rules/boards/tests.rs b/crates/forge-core/src/rules/boards/tests.rs new file mode 100644 index 000000000..6bfb2b658 --- /dev/null +++ b/crates/forge-core/src/rules/boards/tests.rs @@ -0,0 +1,420 @@ +use serde_json::{json, Value}; + +use super::*; + +/// The vector's spec (a JSON object), read as `board.spec` would be. +fn spec_of(v: &Value) -> BoardSpec { + parse_spec(&serde_json::to_string(v).unwrap()).expect("vector spec parses") +} + +fn de(v: &Value) -> T { + serde_json::from_value(v.clone()).unwrap() +} + +fn rank_json(r: Result) -> Value { + match r { + Ok(rank) => json!({ "rank": rank }), + Err(e) => json!({ "error": e.as_str() }), + } +} + +fn opt_str(v: &Value) -> Option { + v.as_str().map(str::to_string) +} + +/// The fold a vector describes, and its spec and items. +fn fold_of(inp: &Value) -> (BoardSpec, Vec, BoardFold) { + let spec = spec_of(&inp["spec"]); + let items: Vec = de(&inp["items"]); + let cards: Vec = de(&inp["cards"]); + let fold = fold_board( + &spec, + inp["home"].as_str().unwrap(), + &items, + &cards, + inp["now"].as_i64().unwrap(), + ); + (spec, items, fold) +} + +/// The rows a view vector's query (`q`) keeps, in input order. +fn rows_of<'a>( + inp: &Value, + spec: &BoardSpec, + items: &'a [BoardItem], + fold: &'a BoardFold, +) -> Vec> { + let query = parse_board_query(inp["q"].as_str().unwrap_or(""), spec); + let ctx = QueryContext { + me: opt_str(&inp["me"]), + now: inp["now"].as_i64().unwrap(), + }; + items + .iter() + .zip(&fold.items) + .map(|(item, placement)| BoardRow { item, placement }) + .filter(|r| matches_board_query(r.item, r.placement, spec, &query, &ctx)) + .collect() +} + +#[allow(clippy::too_many_lines)] // one arm per case and op +fn run(case: &str, inp: &Value) -> Value { + let op = inp["op"].as_str().unwrap(); + match (case, op) { + ("board_spec", "parse") => inp["cases"] + .as_array() + .unwrap() + .iter() + .map(|c| match parse_spec(c["json"].as_str().unwrap()) { + Ok(spec) => json!({ "name": c["name"], "json": serialize_spec(&spec).unwrap() }), + Err(e) => json!({ "name": c["name"], "error": e.as_str() }), + }) + .collect(), + ("board_spec", "default") => { + let spec = default_spec(inp["home"].as_str().unwrap(), inp["now"].as_i64().unwrap()); + json!({ "json": serialize_spec(&spec).unwrap() }) + } + ("board_spec", "values") => { + let spec = spec_of(&inp["spec"]); + let values = parse_field_values(inp["f"].as_str(), &spec); + match serialize_field_values(&values, &spec) { + Some(j) => json!({ "values": values, "json": j }), + None => json!({ "values": values, "error": "size" }), + } + } + ("board_rank", "between") => inp["pairs"] + .as_array() + .unwrap() + .iter() + .map(|p| rank_between(p[0].as_str().unwrap_or(""), p[1].as_str().unwrap_or(""))) + .map(rank_json) + .collect(), + ("board_rank", "top") => inp["firsts"] + .as_array() + .unwrap() + .iter() + .map(|f| rank_json(top_rank(f.as_str()))) + .collect(), + ("board_rank", "bottom") => inp["lasts"] + .as_array() + .unwrap() + .iter() + .map(|l| rank_json(bottom_rank(l.as_str()))) + .collect(), + ("board_rank", "implicit") => inp["items"] + .as_array() + .unwrap() + .iter() + .map(|i| { + json!(implicit_rank_of( + i["createdAt"].as_i64().unwrap(), + i["id"].as_str().unwrap() + )) + }) + .collect(), + ("board_rank", "rerank") => match rerank(inp["n"].as_u64().unwrap()) { + Ok(ranks) => json!({ "ranks": ranks }), + Err(e) => json!({ "error": e.as_str() }), + }, + ("board_fold", "fold") => serde_json::to_value(fold_of(inp).2).unwrap(), + ("board_fold", "boards") => { + let docs: Vec = de(&inp["docs"]); + newest_boards(&docs, inp["withDeleted"].as_bool().unwrap_or(false)) + .iter() + .map(|d| json!({ "key": d.key, "id": d.id, "state": d.state })) + .collect() + } + ("board_query", "parse") => { + let spec = spec_of(&inp["spec"]); + serde_json::to_value(parse_board_query(inp["text"].as_str().unwrap(), &spec)).unwrap() + } + ("board_query", "source") => { + let spec = spec_of(&inp["spec"]); + serde_json::to_value(parse_source_query(inp["text"].as_str().unwrap(), &spec)).unwrap() + } + ("board_query", "match") => { + let (spec, items, fold) = fold_of(inp); + inp["texts"] + .as_array() + .unwrap() + .iter() + .map(|text| { + let mut q = inp.clone(); + q["q"] = text.clone(); + rows_of(&q, &spec, &items, &fold) + .iter() + .map(|r| json!(r.item.id)) + .collect::() + }) + .collect() + } + ("board_iteration", "at" | "range") => { + let spec = spec_of(&inp["spec"]); + let field = spec + .field(u8::try_from(inp["field"].as_u64().unwrap()).unwrap()) + .unwrap(); + if op == "at" { + inp["dates"] + .as_array() + .unwrap() + .iter() + .map(|d| json!(iteration_at(field, d.as_i64().unwrap()))) + .collect() + } else { + inp["ks"] + .as_array() + .unwrap() + .iter() + .map(|k| { + serde_json::to_value(iteration_range(field, k.as_i64().unwrap())).unwrap() + }) + .collect() + } + } + ("board_view", _) => { + let (spec, items, fold) = fold_of(inp); + let rows = rows_of(inp, &spec, &items, &fold); + let field_id = |k: &str| inp[k].as_u64().map(|x| u8::try_from(x).unwrap()); + match op { + "group" => serde_json::to_value(group_rows( + &rows, + inp["by"].as_str().unwrap(), + &spec, + inp["now"].as_i64().unwrap(), + )) + .unwrap(), + "sort" => inp["sorts"] + .as_array() + .unwrap() + .iter() + .map(|sort| { + sort_rows(&rows, sort.as_str(), &spec) + .iter() + .map(|r| json!(r.item.id)) + .collect::() + }) + .collect(), + "totals" => { + let view = + field_id("view").and_then(|id| spec.views.iter().find(|v| v.id == id)); + serde_json::to_value(column_totals(&rows, &spec, sum_field_of(&spec, view))) + .unwrap() + } + "progress" => serde_json::to_value(iteration_progress( + &rows, + &spec, + field_id("field").unwrap(), + inp["k"].as_i64().unwrap(), + field_id("points"), + )) + .unwrap(), + other => panic!("unknown board_view op `{other}`"), + } + } + _ => panic!("unknown board vector `{case}` op `{op}`"), + } +} + +/// Every `board_*__*.json` vector, the same as forge-web `lib/rules/boards.conformance.test.ts` +/// runs. +#[test] +fn board_vectors() { + let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../forge-contracts/vectors"); + let mut files: Vec<_> = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| { + p.file_name() + .unwrap() + .to_string_lossy() + .starts_with(VECTOR_CASE_PREFIX) + }) + .collect(); + files.sort(); + let mut cases = std::collections::BTreeSet::new(); + for path in &files { + let v: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + let case = v["case"].as_str().unwrap(); + let name = path.file_name().unwrap().to_string_lossy(); + assert!( + name.starts_with(&format!("{case}__")), + "{name}: file is __.json" + ); + cases.insert(case.to_string()); + let got = run(case, &v["input"]); + assert_eq!(got, v["expected"], "vector {name}"); + } + for c in [ + "board_rank", + "board_spec", + "board_fold", + "board_query", + "board_iteration", + "board_view", + ] { + assert!(cases.contains(c), "no {c} vectors"); + } + assert!(files.len() >= 30, "ran {} board vectors", files.len()); + println!("board_vectors: {} green", files.len()); +} + +/// A deterministic PRNG (splitmix64), the same as `boards.test.ts` uses. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> usize { + usize::try_from(self.next() % n).unwrap() + } + + /// 0–`max` rank digits, biased to `0`, `1`, `y`, `z` and short strings (the edges). + fn digits(&mut self, max: u64) -> String { + let len = self.below(max + 1); + (0..len) + .map(|_| match self.below(4) { + 0 => char::from(b"01yz"[self.below(4)]), + _ => char::from(RANK_DIGITS[self.below(62)]), + }) + .collect() + } +} + +/// Whether nothing lies strictly between `a` < `b`: `b` is `a` and only `0`s. +fn nothing_between(a: &str, b: &str) -> bool { + b.len() > a.len() && b.starts_with(a) && b[a.len()..].bytes().all(|c| c == b'0') +} + +fn check_between(a: &str, b: &str) { + match rank_between(a, b) { + Ok(r) => { + assert!(a < r.as_str(), "{a:?} < {r:?}"); + assert!(b.is_empty() || r.as_str() < b, "{r:?} < {b:?}"); + assert!(is_explicit_rank(&r), "{r:?} is an explicit rank"); + assert!(r.len() <= a.len().max(b.len()) + 1, "{r:?} is short"); + } + Err(e) => { + let too_long = a.len().max(b.len()) >= RANK_MAX; + assert!( + e == RankError::Rerank && (nothing_between(a, b) || too_long), + "{a:?} {b:?}: {e:?}" + ); + } + } +} + +#[test] +fn rank_between_is_strictly_between() { + let mut rng = Rng(0x00b0_a2d5); + for _ in 0..20_000 { + let (x, y) = (rng.digits(6), rng.digits(6)); + // half the pairs share a prefix, so prefix relations (`V` / `V1` / `V10`) are common + let (x, y) = if rng.below(2) == 0 { + let p = rng.digits(4); + (format!("{p}{x}"), format!("{p}{y}")) + } else { + (x, y) + }; + match x.cmp(&y) { + Ordering::Less => check_between(&x, &y), + Ordering::Greater => check_between(&y, &x), + Ordering::Equal if x.is_empty() => assert_eq!(rank_between("", "").as_deref(), Ok("V")), + Ordering::Equal => assert_eq!(rank_between(&x, &y), Err(RankError::Rerank)), + } + check_between(&x, ""); + if !x.is_empty() { + check_between("", &x); + } + } + // the pool: implicit ranks may end in `0` + for (a, b) in [ + ("V", "V0"), + ("V1", "V10"), + ("V1", "V100"), + ("V10", "V1000"), + ("", "0"), + ("", "00"), + ] { + assert_eq!(rank_between(a, b), Err(RankError::Rerank), "{a} {b}"); + } + assert_eq!(rank_between("V1", "V101").as_deref(), Ok("V100V")); + assert_eq!(rank_between("V", "V01").as_deref(), Ok("V00V")); +} + +#[test] +fn repeated_drops_into_one_gap_end_in_rerank() { + // always dropping just below the last drop: each halves the gap + let (mut lo, mut hi) = (String::new(), "V".to_string()); + let mut drops = 0; + while let Ok(r) = rank_between(&lo, &hi) { + hi = r; + drops += 1; + assert!(drops < 1000); + } + assert!((300..=400).contains(&drops), "{drops} drops"); + // and just above it + hi = String::new(); + lo = "V".to_string(); + drops = 0; + while let Ok(r) = rank_between(&lo, &hi) { + lo = r; + drops += 1; + assert!(drops < 20_000); + } + assert!(drops > 300, "{drops} drops"); +} + +#[test] +fn rerank_spreads_below_the_pool() { + for n in [0_u64, 1, 2, 3, 30, 31, 100, 1921, 1922, 5000] { + let ranks = rerank(n).unwrap(); + assert_eq!(ranks.len(), usize::try_from(n).unwrap()); + for w in ranks.windows(2) { + assert!(w[0] < w[1]); + assert!(rank_between(&w[0], &w[1]).is_ok()); + } + assert!(ranks + .iter() + .all(|r| is_explicit_rank(r) && r.as_str() < "V")); + } + assert_eq!(rerank(RERANK_MAX + 1), Err(RankError::Invalid)); +} + +#[test] +fn spec_round_trips_and_defaults_fit() { + let spec = default_spec( + "4tJ7mVo5yJm4b6rKZ2SRsG6YqfJHFDLC2kUwD3nAhZ7b", + 1_761_782_400_000, + ); + let json = serialize_spec(&spec).unwrap(); + assert_eq!(parse_spec(&json).unwrap(), spec); + assert_eq!(serialize_spec(&parse_spec(&json).unwrap()).unwrap(), json); + assert!(json.len() <= SPEC_MAX_BYTES); +} + +#[test] +fn dates_and_mondays() { + assert_eq!(date_days("1970-01-01"), Some(0)); + assert_eq!(date_days("2024-02-29"), Some(19_782)); + assert_eq!(date_days("2023-02-29"), None); + assert_eq!(civil_from_days(19_782), "2024-02-29"); + assert_eq!(monday_of(0), "1969-12-29"); + // 2026-10-27 is a Tuesday + assert_eq!( + monday_of(date_days("2026-10-27").unwrap() * DAY_MS + 5), + "2026-10-26" + ); + assert_eq!( + monday_of(date_days("2026-10-26").unwrap() * DAY_MS), + "2026-10-26" + ); + for d in [-719_162_i64, -700_000, -1, 0, 59, 60, 10_000, 2_932_896] { + assert_eq!(date_days(&civil_from_days(d)), Some(d)); + } +} diff --git a/docs/design/boards.md b/docs/design/boards.md new file mode 100644 index 000000000..1ca055157 --- /dev/null +++ b/docs/design/boards.md @@ -0,0 +1,256 @@ +# Boards: planning issues and pull requests + +Status: design, 2026-10-27 (UPDATE-3). Owner request: "build out a full, properly designed implementation of issue tracking boards, Jira / Trello ish. Make your own decisions; solve the same user stories as a GitHub project board, Trello and Jira." + +Constraints that shape every decision (`docs/research/platform-constraints.md`): one document operation per state transition; 5 KiB per field and 20 KiB per signed transition; 100 documents per query page; indexed strings ≤ 63 characters; no subscriptions (liveness is polling); **we host nothing** (no server runs automations, sends notifications or keeps a board's state); every write costs the writer credits. + +--- + +## 1. User stories + +The stories GitHub Projects, Trello and Jira all serve, and how Forge answers each. "Board" below is Forge's name for a GitHub *project*, a Trello *board* and a Jira *board*. + +| # | Story | Forge | +|---|---|---| +| U1 | Lay work out in stages (columns) and see at a glance what is where | Board view: one column per status, cards for issues and PRs (§4.1) | +| U2 | Move work between stages and prioritise within a stage by dragging | Drag and drop, and keyboard moves; one cheap write per move (§3.2, §5.2) | +| U3 | New work shows up on the board without anyone adding it | **Sources**: a board includes every issue / PR of the repos and filters it names (§2.3) | +| U4 | Finished work moves to Done by itself; old done work goes away | Closed and merged items show in the Done column; auto-archive after N days (§2.4) | +| U5 | Track more than status: priority, estimate, sprint, dates, free text | Custom fields: single select, number, date, iteration, text (§2.2) | +| U6 | Different people need different cuts of the same work | Saved views: board, table and roadmap layouts, each with a filter, a grouping, swimlanes, a sort (§4) | +| U7 | Filter to "mine", a label, a sprint, a priority | One query language shared with the Issues tab, plus board qualifiers (§4.4) | +| U8 | Plan in sprints; see the current one; carry over unfinished work | Iteration field with a cadence; `iteration:@current`; "move open items to the next iteration" (§2.2, §5.4) | +| U9 | Limit work in progress | Per-column WIP limits, shown and warned on, never blocking (§2.1) | +| U10 | Capture a card quickly | Quick add at the foot of a column: a title makes a real issue, `#12` or a URL adds an existing one (§5.3) | +| U11 | Work on a card without leaving the board | Side panel: body, labels, assignees, fields, state, comments link (§5.5) | +| U12 | From an issue, see which boards it is on and change its status there | Issue and PR sidebar "Boards" section (§5.6) | +| U13 | One board across several repositories | A board lives in a **home repository** and may source and hold items from any repository (§2.5) | +| U14 | Everyone can look; only the team can change it | Public boards in public repos; sealed boards in private repos; writes gated on the home repo's membership at consensus (§3) | +| U15 | See progress: counts, points, sprint burn | Column totals (count and a number field's sum) and an iteration progress bar (§4.5) | +| U16 | Script it | `dg board` (list, view, create, move, set, add, archive, remove) with `--json` (§6) | + +**Deliberately different.** + +- *No draft cards.* Trello cards and GitHub draft issues are a second kind of item that later has to be converted. On Forge an issue costs about as much as a card (0.0010 vs 0.0005 DASH) and already has comments, labels, assignees, a number, a URL and history, so quick add makes a real issue. One item model; nothing to convert. +- *No automation engine.* GitHub's workflows and Jira's automation run on a server when something happens. Forge hosts nothing, so automation is **derived**: rules in the board's definition that every reader applies when it renders (sources, the Done column, auto-archive). They are free (no writes), instant, consistent between the web and the CLI (shared vectors), and can never "fail to run". +- *No configurable workflow transitions* (Jira's "In review may only go to Done"). Statuses are columns; any member may move any card. Transition rules suit a ticketing desk, not a forge, and would be client-only anyway. +- *Board history is not kept.* A card's placement is one mutable document per member (§3.2): a move costs about 0.00003 DASH instead of 0.0005, at the price of no per-move audit trail. Issue state history stays in the issue timeline, which is what matters. + +--- + +## 2. The model + +### 2.1 Board + +A board is a definition: name, description, columns, fields, sources, views and rules. Its **key** is a random u32 chosen at creation (URLs: `/repo/board?owner=&name=&b=`); every revision of the board carries the same key. + +**Columns** (1–20): `{id, name, color?, wip?}`. `id` is 1–255, stable across renames; order is the array order. One column may be the **Done** column (`done`), and one the **default** column (`def`: where an item with no placement shows; 0 = a "No status" column shown only while it holds something). + +### 2.2 Fields + +Up to 12 custom fields `{id, name, type, …}`, `id` 1–255 stable: + +| type | value | notes | +|---|---|---| +| `sel` single select | option id (1–255) | options `{id, name, color?}`, ≤ 30 | +| `num` number | finite number | e.g. Estimate / story points; summed in column totals | +| `date` | `YYYY-MM-DD` | e.g. Start, Target; the roadmap layout plots them | +| `iter` iteration | iteration index ≥ 0 | `start` (`YYYY-MM-DD`) + `days` (1–90); iteration *k* runs from `start + k·days` for `days` days, named " k+1" | +| `text` | string ≤ 200 chars | | + +Built-in fields come from the item itself and are never stored on the board: Title, Number, Repository, State, Author, Assignees, Labels, Milestone, Created, plus Status (the column). + +### 2.3 Sources (auto-include) + +Up to 5 sources `{r, k, q}`: a repository id (`r`, default the home repo), a kind (`i` issues, `p` pull requests, `a` both) and a filter in the board query language (§4.4, default empty = all). Every item a source matches is on the board, open or closed, unless a member removed it (§2.4). A board with no sources holds only the items members added. The new-board template sources the home repository's issues and pull requests. + +### 2.4 Placement: where an item shows + +For each item the reader takes the **newest card** (§3.2) over every member's, by (`$updatedAt`, `$id`). An item is **on the board** when a source matches it or it has a card, and that card is not *removed*. + +Its column: + +1. A **closed or merged** item shows in the Done column, unless its card puts it in a column at or after the Done column in the column order (a "Verified" or "Released" stage after Done keeps its items). +2. Otherwise the card's column, if the board still has that column. +3. Otherwise the default column (or "No status"). + +An open item may sit in Done (a team that marks work done before closing). A board without a Done column applies rule 2 and 3 only. + +**Auto-archive** (`arch`, days, 0 = off): let `closedAt` be the `$createdAt` of the item's latest transition into closed or merged (the transition that made its `sum mod 16` closed or merged). A closed or merged item whose newest card is older than `closedAt` (or which has none) is archived once `now ≥ closedAt + arch` days. `now` is an explicit input of the fold (the vectors pin it). Reopening never clears a card's archived state (as on GitHub). **Archived** items (auto or by a card's state) are hidden unless the view asks for them (`is:archived`). A **removed** item is off the board even if a source matches it; adding it again writes an active card. + +**Order within a column** is by rank (§2.6), ascending; a view may sort by a field instead (§4). + +### 2.5 Home repository and cross-repository boards + +A board's documents carry its home repo's id, and consensus admits them only from that repo's maintainers and members (§3). Its items may be any repository's issues and pull requests: a source may name another repository, and a card may name any item. An "organisation board" is a board in a planning repository (Forge has no organisations; an owner identity's repos are its organisation). + +What a reader may see of a cross-repo item is what that repository shows it: a private repository's issue on a public board shows as "a private item" unless the reader holds that repo's key. + +### 2.6 Rank + +A card's `rank` is a string over the 62 digits `0-9A-Za-z` (ASCII order, so byte order is numeric order), read as a base-62 fraction; an explicit rank never ends in `0` and is at most 63 characters. Items sort by `(rank, item $id)`. + +- **Implicit rank.** An item with no card, or whose newest card has no rank, ranks `V` + the **item's** `$createdAt` in 8 zero-padded base-62 digits + the first 3 bytes of the item's `$id` (big-endian, mod 62⁴) in 4 digits. Sourced items therefore form a pool (`V…`) in creation order, oldest first, almost never two equal (two items of one block whose id prefixes collide mod 62⁴ tie, and sort by `$id`), and a card can be dropped between two of them without ranking either. An implicit rank may end in `0`; only the midpoint arithmetic treats trailing `0`s as absent. +- **Moves.** Dropping between two neighbours writes `rankBetween(a, b)`, a string strictly between them (digit-wise midpoint; vectors `board_rank__*`). **Top** of a column: `rankBetween("", min(first, "V"))`. **Bottom**: `rankBetween(max(last, "W"), "")`. So explicit top and bottom groups bracket the sourced pool, and later sourced items (which join the pool) never pass a card dropped at the bottom. A card dropped between two sourced items gets a `V…` rank, which later sourced items may pass; that is intended (they are newer). +- **Overflow.** A rank that would exceed 63 characters (about 350 drops into one gap) is refused before signing with "Re-rank this column", which rewrites the column's ranks evenly: one write per item, a create (≈ 0.0005 DASH) for each item the signer has no card for, priced before signing. `rerank(n)` spreads them between `0` and `V` (k/(n+1) of the way, in the fewest digits that leave 62 ranks between neighbours), so items sourced later still join below them, in the pool. The pairs with no rank between are equal ranks (two members dropping into one gap at once write the same rank) and `b` = `a` + `0…0` (an explicit rank against an implicit one ending in `0`); both are `re-rank` too. + +### 2.7 Encoding and the rules both clients apply + +Pinned by `forge-web/lib/rules/boards.ts` and forge-core `rules::boards` (vectors `board_spec__*`, `board_query__*`, `board_view__*`). + +- **Spec JSON** (`v: 1`): `{v, desc?, columns, def?, done?, sources?, fields?, views?, arch?}`; a column `{id, name, color?, wip?}`; a field `{id, name, type, options?, start?, days?}` (`options` exactly on `sel`, `start` / `days` exactly on `iter`), an option `{id, name, color?}`; a source `{r?, k, q?}`; a view `{id, name, layout, q?, group?, lane?, sort?, cols?, date?}`. Written canonically: that key order, compact, defaults (0, `""`, `[]`) omitted (an empty `desc` is none), so equal specs are equal bytes. JSON that forge-core's reader (serde_json) refuses is refused by both clients: an unpaired surrogate escape, a number out of range (`1e400`), nesting past 127 levels; forge-core reads numbers exactly (`float_roundtrip`), as `JSON.parse` does. Unknown keys are tolerated on read and dropped on write (a change older editors must keep bumps `v`); a known key of the wrong type refuses the spec, naming the first problem in key order. Colors are `#rrggbb` (the label schema's); `wip` 1–9999; `desc` ≤ 1024 characters; queries ≤ 512 characters; `arch` ≤ 3650. +- **Names** (columns, fields, options, views): 1–63 characters, no control character or `"`, no leading or trailing white space, unique in any letter case. A field name may not contain `:`, start with `-`, or be a query key or built-in field (`is`, `state`, `label(s)`, `assignee(s)`, `author`, `milestone`, `no`, `status`, `repo(sitory)`, `title`, `number`, `created`), so `:` is never ambiguous. +- **View keys**: built-ins by name (`status`, `assignee`, `label`, `milestone`, `repo`, `title`, `number`, `created`, `author`, `state`, `assignees`, `labels`), a custom field as `f`; `sort` takes `-` for descending. The board layout groups by `status` or a `sel` / `iter` field; lanes never by `status` or the grouping; `date` is one `iter` field or two different `date` fields. Every reference must resolve. +- **Field values** (`card.f`): `sel` an option id, `num` finite with |x| ≤ 1e15 and 0 or |x| ≥ 1e-6 (so both clients print it alike, without an exponent: JavaScript's shortest digits, an exact tie to even), `date` a calendar `YYYY-MM-DD`, `iter` 0–65535, `text` 1–200 characters. Anything else is dropped on read. Written ids ascending. +- **Sources** read only the item: a source query's `status:`, field, `is:archived` and `@me` qualifiers are reported, not applied (a source includes the same items for every reader, before any card). +- **Query** additions to §4.4: `is:unmerged` (open or closed, as on the Pull requests tab), `state:` as `is:` for states, a leading `-` on any qualifier (a missing value never matches, so `-priority:P0` matches items with no priority), number and date ranges `a..b` / `*..b` / `a..*`, `@today`, `iteration:N` (iteration N) or by name, `iteration:<@current`, text fields matched as contains. Names and values with spaces are quoted (`"story points":>3`). Before an iteration field's first iteration `@next` is iteration 1 and `@current` / `@previous` match nothing. A token naming nothing on the board is reported, as is a known key with nothing after its colon (`label:`); an unknown key with nothing after it (`note:`) and a URL stay text. Free text matches titles and numbers as the Issues tab's does (no bodies on a board). +- **Groups** (§4.1, §4.2): "No " first, only while it holds an item; then every column, every option, the iterations items name plus the current one, or the distinct assignees / labels / milestones / repositories by code point (an item with two assignees or labels is in both). **Sorts**: items without a value last in both directions; ties by (rank, item id). + +--- + +## 3. Contract: two new forge-meta types (UPDATE-3) + +New document types only, added to forge-meta by `deploy-v2.mjs --update meta` on a registered network (forge-meta v3 on testnet) and part of the registration set elsewhere. Flag `boards` (UPDATE3), four-contract set only, as `passkey_vault`. + +Both types are **mutable and never deleted, one document per (member, board[, item])** (`canBeDeleted: false`: deleting the newest document would silently bring back an older member's, which no poll of `$updatedAt` sees, and a removed member could still delete theirs; `state` 2 is the delete). Every index key and both timestamps are `required` (an unrequired `$updatedAt` is never recorded, and a unique index does not hold a document missing a key part). A member's later write replaces their own document (a replace costs a fraction of a create: the passkey vault measured 3.1M credits against 51.5M), and readers take the newest across members. Both are member-gated like `label`: `ownerRefersTo` a forge-core `maintainer` or a `writer` whose `role` equals the claimed `r`, re-validated on every replace, so a removed member cannot touch their old documents and a role change takes effect on the next write. + +### 3.1 `board` + +| property | type | notes | +|---|---|---| +| `repoId` | id, immutable | the home repository | +| `key` | u32 1–4294967295, immutable | the board | +| `name` | string 1–63 chars, ≤ 252 B, visible character | plaintext boards only | +| `spec` | string ≤ 4096 B | the definition (§2), JSON, `v: 1`; plaintext boards only | +| `state` | integer 0–2 | 0 open, 1 closed (read-only, listed under Closed), 2 deleted | +| `enc`, `epoch` | bytes 29–5120, u32 | a private repo's board: `name` and `spec` sealed together | +| `r` | integer 1–1 (rule `rClaim`: `r = 1`) | maintainers and role-1 writers define boards (a writer may close or delete a maintainer's board, as with labels) | + +Unique index `byKey (repoId, key, $ownerId)`; its `repoId` prefix lists a repo's boards. Rules: `noPlain` (with `enc`, no `name` / `spec`), `hasName` (without `enc`, `name` and `spec`), `dependentRequired enc → epoch`. + +### 3.2 `card` + +A member's placement and field values for one item on one board. + +| property | type | notes | +|---|---|---| +| `repoId` | id, immutable | the board's home repository (the gate) | +| `board` | u32, immutable | the board's key | +| `item` | identifier, immutable, `refersTo` forge-collab `issue` or `patch` (any repository) | | +| `col` | integer 0–255 | column id; 0 = none | +| `rank` | string 1–63 chars, `^[0-9A-Za-z]*[1-9A-Za-z]$` | | +| `f` | string ≤ 2048 B | field values, JSON `{"": value}` | +| `state` | integer 0–2 | 0 active, 1 archived, 2 removed | +| `enc`, `epoch` | bytes 29–2560, u32 | a private repo's card: `col`, `rank`, `f` sealed | +| `r` | integer 1–2 | maintainers, writers and triage place cards | + +Indexes: unique `onItem (item, repoId, board, $ownerId)` (one card per member per item per board; its `item` prefix answers "which boards is this issue on") and `recent (repoId, board, $updatedAt)` (load a board, and poll for what changed since). Rules: `noPlain` (with `enc`, no `col` / `rank` / `f`). + +`state` stays plaintext in a private repo: it tells only that an item was archived or removed. + +**Why one document per member and not one per item.** Platform documents are replaced only by their owner. One document per item would need every member to create a new immutable document per move (0.0005 DASH, forever growing). Per-member mutable documents make every move after a member's first a replace. + +**Concurrent edits.** A card carries all of a member's view of the item (column, rank, fields), and the newest wins whole. A client reads the item's newest card immediately before signing and applies only its own change to it, so two members editing different fields of one card both land unless the second read happens before the first write is visible (the read-to-sign latency, a few seconds); then the last writer wins whole. + +**Gates fixed by this registration** (an update can never add an `ownerRefersTo` operand): only the **home** repository's members place cards (a member of the item's repository who is not one of the home repo's cannot); a card always names an issue or PR (`item` required, with `refersTo`), so there are no item-less notes; writers (role 1) define boards, triage does not. + +### 3.3 Private repositories + +A private repository's boards and cards are sealed with the repository key under the current epoch, with the private-repos per-document framing (`docs/security/private-repos.md` §4.4): new `docType`s `board` and `card`, bound to `u32(key)` and `u32(board) ‖ item (32 B)` respectively, so a sealed payload cannot be moved to another board or item. Readers of a private repo see nothing; the keys, `state` and the item ids are all that is plaintext. + +**What a private board still shows.** `item` is plaintext, immutable and indexed, so a card in a private planning repository that names a *public* repository's issue publishes "private repository R tracks owner/name#12" (and which member wrote it). Clients confirm before writing such a cross-repository card from a private home repo. A public repository's members-only boards (the members key, `enc` v0x03) are possible with this schema and left to a later client. + +--- + +## 4. Views + +A view is `{id, name, layout, q, group, lane, sort, cols?, date?}`, at most 8 per board, saved in the board definition. Unsaved changes live in the URL (`?b=&view=&q=&group=&lane=&sort=`), so any cut can be shared as a link; a member saves it into the definition. + +### 4.1 Board layout + +Columns are the values of the grouping field: Status by default, or any single-select or iteration field (dragging then sets that field). **Swimlanes** (`lane`) split the board horizontally by assignee, label, milestone, repository, a single-select or an iteration field. Cards show the repo (when the board spans several), number, title, state icon, labels, assignees, and the view's chosen fields (`cols`). + +### 4.2 Table layout + +One row per item; columns are the built-in and custom fields the view lists (`cols`); click a header to sort; grouping makes sections with counts and sums; cells of custom fields and Status are edited in place by members. + +### 4.3 Roadmap layout + +A timeline: each item is a bar from its start date to its target date (`date: [startFieldId, endFieldId]`) or across its iteration (`date: [iterFieldId]`); items with no dates are listed beside it. Zoom: weeks, months, quarters. Today and the iterations are marked. + +### 4.4 Query language + +The Issues tab's qualifiers (`is:open|closed|merged`, `is:issue|pr`, `label:`, `-label:`, `no:label`, `assignee:@me`, `no:assignee`, `author:`, `milestone:`, `no:milestone`, free text and `#12`) plus: + +- `status:"In progress"` / `-status:Done` / `no:status` +- `:` for a custom field by name: `priority:P0`, `estimate:>3`, `target:<2026-11-01`, `iteration:@current`, `iteration:@next`, `iteration:@previous`, `no:priority` +- `repo:owner/name` +- `is:archived` (otherwise archived items are hidden) + +Names match case-insensitively; values with spaces are quoted. An unknown field or value is reported under the box, never searched as text. + +### 4.5 Totals and progress + +Each column (and each swimlane and table group) shows its item count, its WIP limit when set (red when over), and the sum of the view's first number field. With an iteration field, the board header shows the current iteration's dates and done / total (count and points). + +--- + +## 5. Interaction + +### 5.1 Who can do what + +| | stranger / reader | triage | writer | maintainer | +|---|---|---|---|---| +| view a public board | yes | yes | yes | yes | +| move, rank, set fields, add, archive, remove items | | yes | yes | yes | +| create, edit, close, delete a board; save views | | | yes | yes | + +The UI offers only what the viewer's role allows and the contract's gate refuses the rest. + +### 5.2 Moving + +Drag a card (pointer or touch); keyboard: focus a card, `Space` to pick it up, arrows to move, `Space` to drop, `Esc` to cancel (with live-region announcements). The board moves the card at once (optimistic), signs one write (`card` create, or replace of the signer's own), and puts it back with the reason if the write is refused. Dropping into a column over its WIP limit warns and still moves. + +### 5.3 Adding + +Quick add at the foot of each column: a title makes an issue in the home repo (or a source repo chosen from a menu) and places it there; `#12`, `owner/name#12` or an issue / PR URL adds that item. "Add items" opens a search over the source repos' issues and PRs not on the board. + +### 5.4 Iterations + +"Move open items to the next iteration" sets the iteration field of every open item of the current iteration that is not in the Done column (one write per item, priced first). + +### 5.5 Item panel + +Clicking a card opens a side panel: title, state, body (markdown), labels, assignees, milestone, the board's fields and status (editable by members), archive / remove, and a link to the issue or PR. Labels and assignees edits are the issue's own events. + +### 5.6 On an issue or pull request + +The sidebar's "Boards" section lists the boards it is on whose home is the item's repository or another repository of the same owner (`card.onItem` with `item ==` the item, filtered by home repo; a stranger's board naming the issue never shows), with its status and fields (editable), and "Add to board" for that repository's other boards. + +### 5.7 Liveness + +An open board polls `card.recent` for cards with `$updatedAt >=` its last read (deduplicated by `$id`: several cards can share a block time) every 20 s while the tab is visible, and re-reads the definition on focus. A refresh control forces both. + +--- + +## 6. CLI + +`dg board list []`, `dg board view [--view ] [--json]`, `dg board create --name [--columns "Todo,In progress,Done"]`, `dg board move <#n> [--top|--bottom|--before <#m>|--after <#m>]`, `dg board set <#n> =…`, `dg board add|archive|remove <#n|owner/name#n>…`. The fold, rank and query rules are shared with the web (`forge-core::rules::boards`, `forge-web/lib/rules/boards.ts`, vectors `forge-contracts/vectors/board_*__*.json`). + +--- + +## 7. Costs + +From the measured model (`forge-web/lib/sdk/cost.ts`): a board definition ≈ 0.0015 DASH to create, ≈ 0.0002 to edit; a member's first card for an item ≈ 0.0005, every later move or field change of it ≈ 0.00003. Sources, Done, auto-archive and views cost nothing. + +## 8. Limits + +| | | +|---|---| +| columns | 20 | +| fields | 12, ≤ 30 options each | +| sources | 5 | +| views | 8 | +| definition | 4096 B of JSON | +| field values per card | 2048 B of JSON | +| items | no cap; a board reads 100 cards per page, so very large boards load progressively | diff --git a/forge-contracts/vectors/board_fold__arch_off.json b/forge-contracts/vectors/board_fold__arch_off.json new file mode 100644 index 000000000..3e10af7dc --- /dev/null +++ b/forge-contracts/vectors/board_fold__arch_off.json @@ -0,0 +1,168 @@ +{ + "name": "arch_off", + "description": "arch 0 turns auto-archive off: an item closed 23 days ago with no card stays in Done.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 0 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "4ffa5ETTYcoqTsb1MHqvKzwPDVT2m6GswoJjQ18swZrm", + "number": 54, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791007200000, + "closedAt": 1791072000000, + "title": "Item 54", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [] + }, + "expected": { + "items": [ + { + "id": "4ffa5ETTYcoqTsb1MHqvKzwPDVT2m6GswoJjQ18swZrm", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 3, + "rank": "V0VWxnglEEyoY", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 1, + "items": [] + }, + { + "id": 2, + "items": [] + }, + { + "id": 3, + "items": [ + "4ffa5ETTYcoqTsb1MHqvKzwPDVT2m6GswoJjQ18swZrm" + ] + }, + { + "id": 4, + "items": [] + } + ] + } +} diff --git a/forge-contracts/vectors/board_fold__auto_archive_boundary.json b/forge-contracts/vectors/board_fold__auto_archive_boundary.json new file mode 100644 index 000000000..ebf475a21 --- /dev/null +++ b/forge-contracts/vectors/board_fold__auto_archive_boundary.json @@ -0,0 +1,361 @@ +{ + "name": "auto_archive_boundary", + "description": "Auto-archive (arch 14) with now pinned: closed exactly 14 days ago → archived (auto); 1 ms later → not; a card written after closing → not; a card written before closing → archived; a card written at the closing instant is not older → not; closedAt unknown → not; open → never. Archived items leave the columns.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "3mXCuXaVT4gZ44rxQzNRQ3nH6M7VayprZVz9usETRkYQ", + "number": 41, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1790960400000, + "closedAt": 1791892800000, + "title": "Item 41", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "3qXrE7xFvG5RPk9aLF6h1RsSVCq9gDhw8SrfFsqihRsf", + "number": 42, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1790964000000, + "closedAt": 1791892800001, + "title": "Item 42", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "3uYVYiL2PTUHjRSCFVpxcoxbt4YomTb1hPjAbtSyy7Cv", + "number": 43, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1790967600000, + "closedAt": 1791374400000, + "title": "Item 43", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "3yZ8sJhnresA56ipAkZEEC3mGvGTrhU6GLbfwu4FEnYB", + "number": 44, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1790971200000, + "closedAt": 1791374400000, + "title": "Item 44", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "43ZnBu5ZKrG2Qn1S61HVqa8vfmz7wwMAqHUBHufWWTsS", + "number": 45, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1790974800000, + "closedAt": 1791374400000, + "title": "Item 45", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "47aRWVTKo3etkTJ41G1mSxE64dhn3BEFQELgdvGmn9Ch", + "number": 46, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1790978400000, + "closedAt": null, + "title": "Item 46", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "4Bb4q5q6GF3m68afvWk34LKFTVRS8R7KyBDByvt33pXx", + "number": 47, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790982000000, + "closedAt": null, + "title": "Item 47", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791460800000, + "item": "3uYVYiL2PTUHjRSCFVpxcoxbt4YomTb1hPjAbtSyy7Cv", + "col": 4, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791288000000, + "item": "3yZ8sJhnresA56ipAkZEEC3mGvGTrhU6GLbfwu4FEnYB", + "col": 2, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791374400000, + "item": "43ZnBu5ZKrG2Qn1S61HVqa8vfmz7wwMAqHUBHufWWTsS", + "col": 3, + "rank": null, + "f": null, + "state": 0 + } + ] + }, + "expected": { + "items": [ + { + "id": "3mXCuXaVT4gZ44rxQzNRQ3nH6M7VayprZVz9usETRkYQ", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 3, + "rank": "V0VWudJwWBJ4f", + "archived": "auto", + "fields": {} + }, + { + "id": "3qXrE7xFvG5RPk9aLF6h1RsSVCq9gDhw8SrfFsqihRsf", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 3, + "rank": "V0VWusQT2Baao", + "archived": null, + "fields": {} + }, + { + "id": "3uYVYiL2PTUHjRSCFVpxcoxbt4YomTb1hPjAbtSyy7Cv", + "on": true, + "sourced": true, + "removed": false, + "card": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 4, + "rank": "V0VWv7WzYBs6x", + "archived": null, + "fields": {} + }, + { + "id": "3yZ8sJhnresA56ipAkZEEC3mGvGTrhU6GLbfwu4FEnYB", + "on": true, + "sourced": true, + "removed": false, + "card": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 3, + "rank": "V0VWvMdW4C9d6", + "archived": "auto", + "fields": {} + }, + { + "id": "43ZnBu5ZKrG2Qn1S61HVqa8vfmz7wwMAqHUBHufWWTsS", + "on": true, + "sourced": true, + "removed": false, + "card": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 3, + "rank": "V0VWvbk2aCR9F", + "archived": null, + "fields": {} + }, + { + "id": "47aRWVTKo3etkTJ41G1mSxE64dhn3BEFQELgdvGmn9Ch", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 3, + "rank": "V0VWvqqZ6CifO", + "archived": null, + "fields": {} + }, + { + "id": "4Bb4q5q6GF3m68afvWk34LKFTVRS8R7KyBDByvt33pXx", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VWw5x5cD0BX", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 1, + "items": [ + "4Bb4q5q6GF3m68afvWk34LKFTVRS8R7KyBDByvt33pXx" + ] + }, + { + "id": 2, + "items": [] + }, + { + "id": 3, + "items": [ + "3qXrE7xFvG5RPk9aLF6h1RsSVCq9gDhw8SrfFsqihRsf", + "43ZnBu5ZKrG2Qn1S61HVqa8vfmz7wwMAqHUBHufWWTsS", + "47aRWVTKo3etkTJ41G1mSxE64dhn3BEFQELgdvGmn9Ch" + ] + }, + { + "id": 4, + "items": [ + "3uYVYiL2PTUHjRSCFVpxcoxbt4YomTb1hPjAbtSyy7Cv" + ] + } + ] + } +} diff --git a/forge-contracts/vectors/board_fold__bad_rank_and_values.json b/forge-contracts/vectors/board_fold__bad_rank_and_values.json new file mode 100644 index 000000000..a568306ce --- /dev/null +++ b/forge-contracts/vectors/board_fold__bad_rank_and_values.json @@ -0,0 +1,268 @@ +{ + "name": "bad_rank_and_values", + "description": "A card whose rank is absent or not an explicit rank (ends in 0, a bad digit) ranks as if it had none (implicit); a card whose f is not JSON has no values. Repeated items count once.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "5qqdEAo4aP1w1P5JbecQqeta1fms6Dez2fuUtznBZyJE", + "number": 71, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791068400000, + "closedAt": null, + "title": "Item 71", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "5urGYmAq3aQoM4MvWuLgT2yjQXVXBTY4bcmzF1PSqedV", + "number": 72, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791072000000, + "closedAt": null, + "title": "Item 72", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "5yrusMYbWmofgjeYSA4x4R4toPDBGhR9AZeVb1zi7Kxk", + "number": 73, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791075600000, + "closedAt": null, + "title": "Item 73", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "5qqdEAo4aP1w1P5JbecQqeta1fms6Dez2fuUtznBZyJE", + "number": 71, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791068400000, + "closedAt": null, + "title": "Item 71", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "5qqdEAo4aP1w1P5JbecQqeta1fms6Dez2fuUtznBZyJE", + "col": 2, + "rank": "AB0", + "f": "{\"2\":", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "5urGYmAq3aQoM4MvWuLgT2yjQXVXBTY4bcmzF1PSqedV", + "col": 2, + "rank": "A-B", + "f": null, + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "5yrusMYbWmofgjeYSA4x4R4toPDBGhR9AZeVb1zi7Kxk", + "col": 2, + "rank": "A", + "f": null, + "state": 0 + } + ] + }, + "expected": { + "items": [ + { + "id": "5qqdEAo4aP1w1P5JbecQqeta1fms6Dez2fuUtznBZyJE", + "on": true, + "sourced": true, + "removed": false, + "card": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "V0VX1wTg0JmYt", + "archived": null, + "fields": {} + }, + { + "id": "5urGYmAq3aQoM4MvWuLgT2yjQXVXBTY4bcmzF1PSqedV", + "on": true, + "sourced": true, + "removed": false, + "card": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "V0VX2BaCWK452", + "archived": null, + "fields": {} + }, + { + "id": "5yrusMYbWmofgjeYSA4x4R4toPDBGhR9AZeVb1zi7Kxk", + "on": true, + "sourced": true, + "removed": false, + "card": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 2, + "rank": "A", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 1, + "items": [] + }, + { + "id": 2, + "items": [ + "5yrusMYbWmofgjeYSA4x4R4toPDBGhR9AZeVb1zi7Kxk", + "5qqdEAo4aP1w1P5JbecQqeta1fms6Dez2fuUtznBZyJE", + "5urGYmAq3aQoM4MvWuLgT2yjQXVXBTY4bcmzF1PSqedV" + ] + }, + { + "id": 3, + "items": [] + }, + { + "id": 4, + "items": [] + } + ] + } +} diff --git a/forge-contracts/vectors/board_fold__boards_newest.json b/forge-contracts/vectors/board_fold__boards_newest.json new file mode 100644 index 000000000..6ee07c4ea --- /dev/null +++ b/forge-contracts/vectors/board_fold__boards_newest.json @@ -0,0 +1,78 @@ +{ + "name": "boards_newest", + "description": "Board revisions: per key the newest over every member's by ($updatedAt, $id), ascending by key; a newest revision with state 2 deletes the board (another member's older open revision does not bring it back); an older deleted revision does not.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "boards", + "docs": [ + { + "id": "CZAKsFwL5dVHb1TA5jaZrrkF8PUZybTyDd3A4YBfbkVQ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800100, + "key": 7, + "state": 0, + "name": "B7", + "spec": null + }, + { + "id": "CdAyBrK6Ypt9vgjmzzJqUEqQXFCE4qM3nZufQYnvsRpf", + "ownerId": "FFftTC944VmyJQ2VaUDieXSMpssQULQkDB9odPorkphY", + "updatedAt": 1790812800150, + "key": 7, + "state": 2, + "name": "B7", + "spec": null + }, + { + "id": "AhBcWSgs22H2GN2PvF375cvZv6utA5E8MWnAkZQC979v", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800050, + "key": 3, + "state": 0, + "name": "B3", + "spec": null + }, + { + "id": "bhBcWSgs22H2GN2PvF375cvZv6utA5E8MWnAkZQC979v", + "ownerId": "FFftTC944VmyJQ2VaUDieXSMpssQULQkDB9odPorkphY", + "updatedAt": 1790812800050, + "key": 3, + "state": 1, + "name": "B3", + "spec": null + }, + { + "id": "D7Eb8ru2td9a5RMt4ondt5tyNrLVVZvNByoMTSMbo3wY", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800010, + "key": 9, + "state": 1, + "name": "B9", + "spec": null + }, + { + "id": "D3DwpGXGRRkhjk5G9Z4NGhooyzcqQL3Hd2vr7RkLXNcH", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800005, + "key": 9, + "state": 2, + "name": "B9", + "spec": null + } + ], + "withDeleted": false + }, + "expected": [ + { + "key": 3, + "id": "bhBcWSgs22H2GN2PvF375cvZv6utA5E8MWnAkZQC979v", + "state": 1 + }, + { + "key": 9, + "id": "D7Eb8ru2td9a5RMt4ondt5tyNrLVVZvNByoMTSMbo3wY", + "state": 1 + } + ] +} diff --git a/forge-contracts/vectors/board_fold__boards_with_deleted.json b/forge-contracts/vectors/board_fold__boards_with_deleted.json new file mode 100644 index 000000000..84df77dd1 --- /dev/null +++ b/forge-contracts/vectors/board_fold__boards_with_deleted.json @@ -0,0 +1,83 @@ +{ + "name": "boards_with_deleted", + "description": "The same revisions with the deleted boards kept.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "boards", + "docs": [ + { + "id": "CZAKsFwL5dVHb1TA5jaZrrkF8PUZybTyDd3A4YBfbkVQ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800100, + "key": 7, + "state": 0, + "name": "B7", + "spec": null + }, + { + "id": "CdAyBrK6Ypt9vgjmzzJqUEqQXFCE4qM3nZufQYnvsRpf", + "ownerId": "FFftTC944VmyJQ2VaUDieXSMpssQULQkDB9odPorkphY", + "updatedAt": 1790812800150, + "key": 7, + "state": 2, + "name": "B7", + "spec": null + }, + { + "id": "AhBcWSgs22H2GN2PvF375cvZv6utA5E8MWnAkZQC979v", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800050, + "key": 3, + "state": 0, + "name": "B3", + "spec": null + }, + { + "id": "bhBcWSgs22H2GN2PvF375cvZv6utA5E8MWnAkZQC979v", + "ownerId": "FFftTC944VmyJQ2VaUDieXSMpssQULQkDB9odPorkphY", + "updatedAt": 1790812800050, + "key": 3, + "state": 1, + "name": "B3", + "spec": null + }, + { + "id": "D7Eb8ru2td9a5RMt4ondt5tyNrLVVZvNByoMTSMbo3wY", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800010, + "key": 9, + "state": 1, + "name": "B9", + "spec": null + }, + { + "id": "D3DwpGXGRRkhjk5G9Z4NGhooyzcqQL3Hd2vr7RkLXNcH", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800005, + "key": 9, + "state": 2, + "name": "B9", + "spec": null + } + ], + "withDeleted": true + }, + "expected": [ + { + "key": 3, + "id": "bhBcWSgs22H2GN2PvF375cvZv6utA5E8MWnAkZQC979v", + "state": 1 + }, + { + "key": 7, + "id": "CdAyBrK6Ypt9vgjmzzJqUEqQXFCE4qM3nZufQYnvsRpf", + "state": 2 + }, + { + "key": 9, + "id": "D7Eb8ru2td9a5RMt4ondt5tyNrLVVZvNByoMTSMbo3wY", + "state": 1 + } + ] +} diff --git a/forge-contracts/vectors/board_fold__newest_card.json b/forge-contracts/vectors/board_fold__newest_card.json new file mode 100644 index 000000000..fe91cc9b6 --- /dev/null +++ b/forge-contracts/vectors/board_fold__newest_card.json @@ -0,0 +1,248 @@ +{ + "name": "newest_card", + "description": "The newest card over every member's wins whole, by ($updatedAt, $id): a later card of another member replaces the column and the field values; on equal $updatedAt the greater $id (by code point) wins. A card's values for unknown fields or options are dropped.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "2TDdSJqfuYnZuDdmvNgZxBJqNcCTh5uRMf5mt35Mi7mW", + "number": 21, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790888400000, + "closedAt": null, + "title": "Item 21", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "2XEGkuDSNkBSEtvPqdQqZZPzmTv7nKnVvbxHE3gcyo6m", + "number": 22, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790892000000, + "closedAt": null, + "title": "Item 22", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800100, + "item": "2TDdSJqfuYnZuDdmvNgZxBJqNcCTh5uRMf5mt35Mi7mW", + "col": 2, + "rank": null, + "f": "{\"1\":1,\"2\":5}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FFftTC944VmyJQ2VaUDieXSMpssQULQkDB9odPorkphY", + "updatedAt": 1790812800200, + "item": "2TDdSJqfuYnZuDdmvNgZxBJqNcCTh5uRMf5mt35Mi7mW", + "col": 4, + "rank": null, + "f": "{\"2\":3,\"1\":9,\"7\":1}", + "state": 0 + }, + { + "id": "56whRx6fB5hignpPAMtzugSQknH7HWZYrxxPBW7Jtdiu", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800300, + "item": "2XEGkuDSNkBSEtvPqdQqZZPzmTv7nKnVvbxHE3gcyo6m", + "col": 2, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "z6whRx6fB5hignpPAMtzugSQknH7HWZYrxxPBW7Jtdiu", + "ownerId": "FFftTC944VmyJQ2VaUDieXSMpssQULQkDB9odPorkphY", + "updatedAt": 1790812800300, + "item": "2XEGkuDSNkBSEtvPqdQqZZPzmTv7nKnVvbxHE3gcyo6m", + "col": 4, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "A6whRx6fB5hignpPAMtzugSQknH7HWZYrxxPBW7Jtdiu", + "ownerId": "FFftTC944VmyJQ2VaUDieXSMpssQULQkDB9odPorkphY", + "updatedAt": 1790812800300, + "item": "2XEGkuDSNkBSEtvPqdQqZZPzmTv7nKnVvbxHE3gcyo6m", + "col": 1, + "rank": null, + "f": null, + "state": 0 + } + ] + }, + "expected": { + "items": [ + { + "id": "2TDdSJqfuYnZuDdmvNgZxBJqNcCTh5uRMf5mt35Mi7mW", + "on": true, + "sourced": true, + "removed": false, + "card": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 4, + "rank": "V0VWplDSC5vov", + "archived": null, + "fields": { + "2": 3 + } + }, + { + "id": "2XEGkuDSNkBSEtvPqdQqZZPzmTv7nKnVvbxHE3gcyo6m", + "on": true, + "sourced": true, + "removed": false, + "card": "z6whRx6fB5hignpPAMtzugSQknH7HWZYrxxPBW7Jtdiu", + "col": 4, + "rank": "V0VWq0Jyi6DL4", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 1, + "items": [] + }, + { + "id": 2, + "items": [] + }, + { + "id": 3, + "items": [] + }, + { + "id": 4, + "items": [ + "2TDdSJqfuYnZuDdmvNgZxBJqNcCTh5uRMf5mt35Mi7mW", + "2XEGkuDSNkBSEtvPqdQqZZPzmTv7nKnVvbxHE3gcyo6m" + ] + } + ] + } +} diff --git a/forge-contracts/vectors/board_fold__no_done_no_default.json b/forge-contracts/vectors/board_fold__no_done_no_default.json new file mode 100644 index 000000000..9ffc3b8fd --- /dev/null +++ b/forge-contracts/vectors/board_fold__no_done_no_default.json @@ -0,0 +1,182 @@ +{ + "name": "no_done_no_default", + "description": "A board without a Done column applies only \"the card's column, else the default\"; with default 0 the items without a column show in \"No status\" (column 0, listed first while it holds an item).", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Backlog" + }, + { + "id": 2, + "name": "Doing" + } + ], + "sources": [ + { + "k": "i" + } + ] + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "59jC2F3PtR5FccD7R7Kijqzx56bJBprCMDCRSthYsBye", + "number": 61, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791032400000, + "closedAt": null, + "title": "Item 61", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "5DjqLqRAMcU7xHVjLN3zME67TxJxH4jGvA4vnuJp8sJu", + "number": 62, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791036000000, + "closedAt": 1793016000000, + "title": "Item 62", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "5HkUfRnvporzHxnMFcnFxcBGrp2cNJcMV6wS8uv5QYeA", + "number": 63, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791039600000, + "closedAt": 1793016000000, + "title": "Item 63", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "5Mm7z2AhJ1Frde4yAsWXZzGSFfkGTYVS43owUvXLgDyR", + "number": 64, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791043200000, + "closedAt": null, + "title": "Item 64", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "5HkUfRnvporzHxnMFcnFxcBGrp2cNJcMV6wS8uv5QYeA", + "col": 2, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "5Mm7z2AhJ1Frde4yAsWXZzGSFfkGTYVS43owUvXLgDyR", + "col": 1, + "rank": null, + "f": null, + "state": 0 + } + ] + }, + "expected": { + "items": [ + { + "id": "59jC2F3PtR5FccD7R7Kijqzx56bJBprCMDCRSthYsBye", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 0, + "rank": "V0VWzVQQqGxNR", + "archived": null, + "fields": {} + }, + { + "id": "5DjqLqRAMcU7xHVjLN3zME67TxJxH4jGvA4vnuJp8sJu", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 0, + "rank": "V0VWzkWxMHEta", + "archived": null, + "fields": {} + }, + { + "id": "5HkUfRnvporzHxnMFcnFxcBGrp2cNJcMV6wS8uv5QYeA", + "on": true, + "sourced": true, + "removed": false, + "card": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "V0VWzzdTsHWPj", + "archived": null, + "fields": {} + }, + { + "id": "5Mm7z2AhJ1Frde4yAsWXZzGSFfkGTYVS43owUvXLgDyR", + "on": true, + "sourced": false, + "removed": false, + "card": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 1, + "rank": "V0VX0Ek0OHnvs", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 0, + "items": [ + "59jC2F3PtR5FccD7R7Kijqzx56bJBprCMDCRSthYsBye", + "5DjqLqRAMcU7xHVjLN3zME67TxJxH4jGvA4vnuJp8sJu" + ] + }, + { + "id": 1, + "items": [ + "5Mm7z2AhJ1Frde4yAsWXZzGSFfkGTYVS43owUvXLgDyR" + ] + }, + { + "id": 2, + "items": [ + "5HkUfRnvporzHxnMFcnFxcBGrp2cNJcMV6wS8uv5QYeA" + ] + } + ] + } +} diff --git a/forge-contracts/vectors/board_fold__placement.json b/forge-contracts/vectors/board_fold__placement.json new file mode 100644 index 000000000..33c1e34b1 --- /dev/null +++ b/forge-contracts/vectors/board_fold__placement.json @@ -0,0 +1,484 @@ +{ + "name": "placement", + "description": "Columns (§2.4): no card → default (Todo); a card's column; closed → Done; merged with a card in Verified (after Done) stays; closed with a card before Done → Done; open in Done stays; another repo's item added by a card shows; another repo's item with no card is off (no source matches it); a card naming a column the spec no longer has, or none (0), → default. Each column in rank order (cards' ranks, else implicit).", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "51eKbNmUCPsLgHcvFjGcP6APrif6Et5ZwsWM1cGGgLG", + "number": 1, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790816400000, + "closedAt": null, + "title": "Item 1", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "92HeBkXwPnjgMaEqWTYDmBKniSKBUmA8tk1h2DXYMfX", + "number": 2, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790820000000, + "closedAt": null, + "title": "Item 2", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "D2vxn8JQbBc22rrkmBoq9GVBa9yGieEhqcX32pnp2zn", + "number": 3, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1790823600000, + "closedAt": 1793016000000, + "title": "Item 3", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "H3aHNW4snaUMi9Ug1v5SXMeaRsdMxXKGnV2P3S45iL3", + "number": 4, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1790827200000, + "closedAt": 1793016000000, + "title": "Item 4", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "M4DbxsqLyyLhPS6bGeM3uSoyHbHTCQPqjMXj43KMPfJ", + "number": 5, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1790830800000, + "closedAt": 1793016000000, + "title": "Item 5", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "R4rvZFbpBND34iiWXNcfHXyN9JwYSHUQgE354ead4zZ", + "number": 6, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790834400000, + "closedAt": null, + "title": "Item 6", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "V5WF9dNHNm5Nk1LRn6tGfd8m12bdgAYyd6YR5FqtkKp", + "number": 7, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1790838000000, + "closedAt": null, + "title": "Item 7", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "Z69Zk18ka9wiRHxM2q9t3iJ9rkFiv3dYZy3m5s7ARf5", + "number": 8, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1790841600000, + "closedAt": null, + "title": "Item 8", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "d6ntLNuDmYp46aaGHZRVRoTYiTup9vi7WqZ76UNS6zL", + "number": 9, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790845200000, + "closedAt": null, + "title": "Item 9", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "h7SCvkfgxwgPmsCBYHh6otcwaBZuPongTi4T75dhnKb", + "number": 10, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790848800000, + "closedAt": null, + "title": "Item 10", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "92HeBkXwPnjgMaEqWTYDmBKniSKBUmA8tk1h2DXYMfX", + "col": 2, + "rank": "F", + "f": null, + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "H3aHNW4snaUMi9Ug1v5SXMeaRsdMxXKGnV2P3S45iL3", + "col": 4, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "M4DbxsqLyyLhPS6bGeM3uSoyHbHTCQPqjMXj43KMPfJ", + "col": 2, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "R4rvZFbpBND34iiWXNcfHXyN9JwYSHUQgE354ead4zZ", + "col": 3, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "V5WF9dNHNm5Nk1LRn6tGfd8m12bdgAYyd6YR5FqtkKp", + "col": 2, + "rank": "l", + "f": null, + "state": 0 + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244806000, + "item": "d6ntLNuDmYp46aaGHZRVRoTYiTup9vi7WqZ76UNS6zL", + "col": 9, + "rank": "G", + "f": null, + "state": 0 + }, + { + "id": "8GJcXjVigTj9N4WARNLVBoE38jJ5E15SkSY75oyKeLBL", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244807000, + "item": "h7SCvkfgxwgPmsCBYHh6otcwaBZuPongTi4T75dhnKb", + "col": 0, + "rank": null, + "f": null, + "state": 0 + } + ] + }, + "expected": { + "items": [ + { + "id": "51eKbNmUCPsLgHcvFjGcP6APrif6Et5ZwsWM1cGGgLG", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VWkt6xs0HW9", + "archived": null, + "fields": {} + }, + { + "id": "92HeBkXwPnjgMaEqWTYDmBKniSKBUmA8tk1h2DXYMfX", + "on": true, + "sourced": true, + "removed": false, + "card": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "F", + "archived": null, + "fields": {} + }, + { + "id": "D2vxn8JQbBc22rrkmBoq9GVBa9yGieEhqcX32pnp2zn", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 3, + "rank": "V0VWlNK0u0qYR", + "archived": null, + "fields": {} + }, + { + "id": "H3aHNW4snaUMi9Ug1v5SXMeaRsdMxXKGnV2P3S45iL3", + "on": true, + "sourced": true, + "removed": false, + "card": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 4, + "rank": "V0VWlcQXQ184a", + "archived": null, + "fields": {} + }, + { + "id": "M4DbxsqLyyLhPS6bGeM3uSoyHbHTCQPqjMXj43KMPfJ", + "on": true, + "sourced": true, + "removed": false, + "card": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 3, + "rank": "V0VWlrX3w1Paj", + "archived": null, + "fields": {} + }, + { + "id": "R4rvZFbpBND34iiWXNcfHXyN9JwYSHUQgE354ead4zZ", + "on": true, + "sourced": true, + "removed": false, + "card": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 3, + "rank": "V0VWm6daS1h6s", + "archived": null, + "fields": {} + }, + { + "id": "V5WF9dNHNm5Nk1LRn6tGfd8m12bdgAYyd6YR5FqtkKp", + "on": true, + "sourced": false, + "removed": false, + "card": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 2, + "rank": "l", + "archived": null, + "fields": {} + }, + { + "id": "Z69Zk18ka9wiRHxM2q9t3iJ9rkFiv3dYZy3m5s7ARf5", + "on": false, + "sourced": false, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VWmaqdU2G9A", + "archived": null, + "fields": {} + }, + { + "id": "d6ntLNuDmYp46aaGHZRVRoTYiTup9vi7WqZ76UNS6zL", + "on": true, + "sourced": true, + "removed": false, + "card": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "col": 1, + "rank": "G", + "archived": null, + "fields": {} + }, + { + "id": "h7SCvkfgxwgPmsCBYHh6otcwaBZuPongTi4T75dhnKb", + "on": true, + "sourced": true, + "removed": false, + "card": "8GJcXjVigTj9N4WARNLVBoE38jJ5E15SkSY75oyKeLBL", + "col": 1, + "rank": "V0VWn53gW2pBS", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 1, + "items": [ + "d6ntLNuDmYp46aaGHZRVRoTYiTup9vi7WqZ76UNS6zL", + "51eKbNmUCPsLgHcvFjGcP6APrif6Et5ZwsWM1cGGgLG", + "h7SCvkfgxwgPmsCBYHh6otcwaBZuPongTi4T75dhnKb" + ] + }, + { + "id": 2, + "items": [ + "92HeBkXwPnjgMaEqWTYDmBKniSKBUmA8tk1h2DXYMfX", + "V5WF9dNHNm5Nk1LRn6tGfd8m12bdgAYyd6YR5FqtkKp" + ] + }, + { + "id": 3, + "items": [ + "D2vxn8JQbBc22rrkmBoq9GVBa9yGieEhqcX32pnp2zn", + "M4DbxsqLyyLhPS6bGeM3uSoyHbHTCQPqjMXj43KMPfJ", + "R4rvZFbpBND34iiWXNcfHXyN9JwYSHUQgE354ead4zZ" + ] + }, + { + "id": 4, + "items": [ + "H3aHNW4snaUMi9Ug1v5SXMeaRsdMxXKGnV2P3S45iL3" + ] + } + ] + } +} diff --git a/forge-contracts/vectors/board_fold__removed.json b/forge-contracts/vectors/board_fold__removed.json new file mode 100644 index 000000000..ef29cd7d3 --- /dev/null +++ b/forge-contracts/vectors/board_fold__removed.json @@ -0,0 +1,271 @@ +{ + "name": "removed", + "description": "A removed card (state 2) takes the item off the board even though a source matches it; an older member's active card does not bring it back; a newer active card (adding it again) does. An unsourced item whose newest card is removed is off too.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "39L4eEbLbWjFHzVy6uyG3zCTKBP2bUiD37nqL99zQu66", + "number": 31, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790924400000, + "closedAt": null, + "title": "Item 31", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "3DLhxpy74i87dfnb2AhXfNHci36ggibHc4fLg9mFgaRM", + "number": 32, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790928000000, + "closedAt": null, + "title": "Item 32", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "3HMMHRLsXuWyyM5CwRRoGkNn6tpLmxUNB1Xr2ANWxFkc", + "number": 33, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790931600000, + "closedAt": null, + "title": "Item 33", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800100, + "item": "39L4eEbLbWjFHzVy6uyG3zCTKBP2bUiD37nqL99zQu66", + "col": 2, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FFftTC944VmyJQ2VaUDieXSMpssQULQkDB9odPorkphY", + "updatedAt": 1790812800200, + "item": "39L4eEbLbWjFHzVy6uyG3zCTKBP2bUiD37nqL99zQu66", + "col": null, + "rank": null, + "f": null, + "state": 2 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FFftTC944VmyJQ2VaUDieXSMpssQULQkDB9odPorkphY", + "updatedAt": 1790812800100, + "item": "3DLhxpy74i87dfnb2AhXfNHci36ggibHc4fLg9mFgaRM", + "col": null, + "rank": null, + "f": null, + "state": 2 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800200, + "item": "3DLhxpy74i87dfnb2AhXfNHci36ggibHc4fLg9mFgaRM", + "col": 2, + "rank": null, + "f": null, + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1790812800100, + "item": "3HMMHRLsXuWyyM5CwRRoGkNn6tpLmxUNB1Xr2ANWxFkc", + "col": 2, + "rank": null, + "f": null, + "state": 2 + } + ] + }, + "expected": { + "items": [ + { + "id": "39L4eEbLbWjFHzVy6uyG3zCTKBP2bUiD37nqL99zQu66", + "on": false, + "sourced": true, + "removed": true, + "card": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 1, + "rank": "V0VWsCGhM8l0N", + "archived": null, + "fields": {} + }, + { + "id": "3DLhxpy74i87dfnb2AhXfNHci36ggibHc4fLg9mFgaRM", + "on": true, + "sourced": true, + "removed": false, + "card": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": "V0VWsRNDs92WW", + "archived": null, + "fields": {} + }, + { + "id": "3HMMHRLsXuWyyM5CwRRoGkNn6tpLmxUNB1Xr2ANWxFkc", + "on": false, + "sourced": false, + "removed": true, + "card": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 2, + "rank": "V0VWsgTkO9K2f", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 1, + "items": [] + }, + { + "id": 2, + "items": [ + "3DLhxpy74i87dfnb2AhXfNHci36ggibHc4fLg9mFgaRM" + ] + }, + { + "id": 3, + "items": [] + }, + { + "id": 4, + "items": [] + } + ] + } +} diff --git a/forge-contracts/vectors/board_fold__reopened_archived.json b/forge-contracts/vectors/board_fold__reopened_archived.json new file mode 100644 index 000000000..6555465b4 --- /dev/null +++ b/forge-contracts/vectors/board_fold__reopened_archived.json @@ -0,0 +1,241 @@ +{ + "name": "reopened_archived", + "description": "Reopening never clears a card's archived state: a reopened item whose newest card is archived (state 1) stays archived (card). Auto-archive reads only closed and merged items: one closed 23 days ago is archived (auto), and a reopened one with an old active card is not.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "4Tde7TLA92dESqj9bXf7Vrfu2vJ4VNdeExhDMyK68Xrz", + "number": 51, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790996400000, + "closedAt": null, + "title": "Item 51", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "4XeHS3hvcE26nX1mWnPP7Em4Rn1iacWiouZihyvMQDCF", + "number": 52, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791000000000, + "closedAt": 1791072000000, + "title": "Item 52", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "4bevke5h5RQy8CJPS37eicrDpdjNfrPoNrSE3zXcftXW", + "number": 53, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791003600000, + "closedAt": null, + "title": "Item 53", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791158400000, + "item": "4Tde7TLA92dESqj9bXf7Vrfu2vJ4VNdeExhDMyK68Xrz", + "col": 2, + "rank": null, + "f": null, + "state": 1 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791158400000, + "item": "4bevke5h5RQy8CJPS37eicrDpdjNfrPoNrSE3zXcftXW", + "col": 2, + "rank": null, + "f": null, + "state": 0 + } + ] + }, + "expected": { + "items": [ + { + "id": "4Tde7TLA92dESqj9bXf7Vrfu2vJ4VNdeExhDMyK68Xrz", + "on": true, + "sourced": true, + "removed": false, + "card": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "V0VWx4NBgE8G7", + "archived": "card", + "fields": {} + }, + { + "id": "4XeHS3hvcE26nX1mWnPP7Em4Rn1iacWiouZihyvMQDCF", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 3, + "rank": "V0VWxJTiCEPmG", + "archived": "auto", + "fields": {} + }, + { + "id": "4bevke5h5RQy8CJPS37eicrDpdjNfrPoNrSE3zXcftXW", + "on": true, + "sourced": true, + "removed": false, + "card": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "V0VWxYaEiEhIP", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 1, + "items": [] + }, + { + "id": 2, + "items": [ + "4bevke5h5RQy8CJPS37eicrDpdjNfrPoNrSE3zXcftXW" + ] + }, + { + "id": 3, + "items": [] + }, + { + "id": 4, + "items": [] + } + ] + } +} diff --git a/forge-contracts/vectors/board_fold__same_block.json b/forge-contracts/vectors/board_fold__same_block.json new file mode 100644 index 000000000..e8aadf7a5 --- /dev/null +++ b/forge-contracts/vectors/board_fold__same_block.json @@ -0,0 +1,260 @@ +{ + "name": "same_block", + "description": "Items created in one block (equal $createdAt) and no cards: their implicit ranks differ by the first bytes of their ids, so their order is fixed; a card dropped between two of them (rankBetween of their implicit ranks) lands between.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "m85XX8SAALYjT9p6o1xiBynLRuDzdgsFQaZo7gtyTer", + "number": 11, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790812800000, + "closedAt": null, + "title": "Item 11", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "q8ir7WCdMjR58SS23kEKa4wjHct5sZwpMT598JAF8z7", + "number": 12, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790812800000, + "closedAt": null, + "title": "Item 12", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "u9NAhsy6Z8HQoj3wJUVvxA789LYB7T2PJKaV8uRWpKN", + "number": 13, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790812800000, + "closedAt": null, + "title": "Item 13", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "yA1VJFjZkX9kV1frZCmYLFGX14CGML6xFC5q9WgnVed", + "number": 14, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1790812800001, + "closedAt": null, + "title": "Item 14", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "yA1VJFjZkX9kV1frZCmYLFGX14CGML6xFC5q9WgnVed", + "col": 1, + "rank": "V0VWke0RM3O", + "f": null, + "state": 0 + } + ] + }, + "expected": { + "items": [ + { + "id": "m85XX8SAALYjT9p6o1xiBynLRuDzdgsFQaZo7gtyTer", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VWke0RM36hb", + "archived": null, + "fields": {} + }, + { + "id": "q8ir7WCdMjR58SS23kEKa4wjHct5sZwpMT598JAF8z7", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VWke0RM3ODk", + "archived": null, + "fields": {} + }, + { + "id": "u9NAhsy6Z8HQoj3wJUVvxA789LYB7T2PJKaV8uRWpKN", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VWke0RM3fjt", + "archived": null, + "fields": {} + }, + { + "id": "yA1VJFjZkX9kV1frZCmYLFGX14CGML6xFC5q9WgnVed", + "on": true, + "sourced": true, + "removed": false, + "card": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 1, + "rank": "V0VWke0RM3O", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 1, + "items": [ + "m85XX8SAALYjT9p6o1xiBynLRuDzdgsFQaZo7gtyTer", + "yA1VJFjZkX9kV1frZCmYLFGX14CGML6xFC5q9WgnVed", + "q8ir7WCdMjR58SS23kEKa4wjHct5sZwpMT598JAF8z7", + "u9NAhsy6Z8HQoj3wJUVvxA789LYB7T2PJKaV8uRWpKN" + ] + }, + { + "id": 2, + "items": [] + }, + { + "id": 3, + "items": [] + }, + { + "id": 4, + "items": [] + } + ] + } +} diff --git a/forge-contracts/vectors/board_fold__sources.json b/forge-contracts/vectors/board_fold__sources.json new file mode 100644 index 000000000..52269301e --- /dev/null +++ b/forge-contracts/vectors/board_fold__sources.json @@ -0,0 +1,309 @@ +{ + "name": "sources", + "description": "Sources (§2.3): issues of the home repo labelled bug, and open PRs of another repo. A source query applies only item qualifiers: its status: and field qualifiers are ignored (unresolved), so \"status:Todo label:bug\" includes every home issue labelled bug. A PR of the home repo does not match an issues source.", + "case": "board_fold", + "rules": "v2", + "input": { + "op": "fold", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "i", + "q": "status:Todo LABEL:bug" + }, + { + "r": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "k": "p", + "q": "is:open" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "items": [ + { + "id": "6U2mVTnDRvyEmTSHuj1aBiUPnqWL5imdZ46oUireapkY", + "number": 81, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791104400000, + "closedAt": null, + "title": "Item 81", + "labels": [ + "Bug" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "6Y3Qp49yu8N778iupyjqo6ZZBhDzAxei7zyJpjTurW5o", + "number": 82, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791108000000, + "closedAt": null, + "title": "Item 82", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "6c448eXkNKkySp1XkEU7QUeiaYweGCXngwqpAk5B8BR4", + "number": 83, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791111600000, + "closedAt": null, + "title": "Item 83", + "labels": [ + "bug" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "6g4hTEuWqX9qnVJ9fVCP1rjsyQfJMSQsFtiKWkgSPrkK", + "number": 84, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791115200000, + "closedAt": null, + "title": "Item 84", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "6k5LmqHHJiYi8AamajvedEq3NGNxSgHwpqaprmHhfY5a", + "number": 85, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1791118800000, + "closedAt": 1793016000000, + "title": "Item 85", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "6p5z6Rf3muwaTqsPVzevEcvCm86cXvB2PnTLCmtxwDQq", + "number": 86, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791122400000, + "closedAt": null, + "title": "Item 86", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [] + }, + "expected": { + "items": [ + { + "id": "6U2mVTnDRvyEmTSHuj1aBiUPnqWL5imdZ46oUireapkY", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VX4NWvAMKdB", + "archived": null, + "fields": {} + }, + { + "id": "6Y3Qp49yu8N778iupyjqo6ZZBhDzAxei7zyJpjTurW5o", + "on": false, + "sourced": false, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VX4cdRgMc9K", + "archived": null, + "fields": {} + }, + { + "id": "6c448eXkNKkySp1XkEU7QUeiaYweGCXngwqpAk5B8BR4", + "on": false, + "sourced": false, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VX4rjyCMtfT", + "archived": null, + "fields": {} + }, + { + "id": "6g4hTEuWqX9qnVJ9fVCP1rjsyQfJMSQsFtiKWkgSPrkK", + "on": true, + "sourced": true, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VX56qUiNBBc", + "archived": null, + "fields": {} + }, + { + "id": "6k5LmqHHJiYi8AamajvedEq3NGNxSgHwpqaprmHhfY5a", + "on": false, + "sourced": false, + "removed": false, + "card": null, + "col": 3, + "rank": "V0VX5Lx1ENShl", + "archived": null, + "fields": {} + }, + { + "id": "6p5z6Rf3muwaTqsPVzevEcvCm86cXvB2PnTLCmtxwDQq", + "on": false, + "sourced": false, + "removed": false, + "card": null, + "col": 1, + "rank": "V0VX5b3XkNkDu", + "archived": null, + "fields": {} + } + ], + "columns": [ + { + "id": 1, + "items": [ + "6U2mVTnDRvyEmTSHuj1aBiUPnqWL5imdZ46oUireapkY", + "6g4hTEuWqX9qnVJ9fVCP1rjsyQfJMSQsFtiKWkgSPrkK" + ] + }, + { + "id": 2, + "items": [] + }, + { + "id": 3, + "items": [] + }, + { + "id": 4, + "items": [] + } + ] + } +} diff --git a/forge-contracts/vectors/board_iteration__at.json b/forge-contracts/vectors/board_iteration__at.json new file mode 100644 index 000000000..dde6e00da --- /dev/null +++ b/forge-contracts/vectors/board_iteration__at.json @@ -0,0 +1,134 @@ +{ + "name": "at", + "description": "iterationAt: the iteration holding a time (UTC days): none before the first; the last millisecond of iteration 0; the first of 1; far later; past index 65535 none.", + "case": "board_iteration", + "rules": "v2", + "input": { + "op": "at", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "field": 3, + "dates": [ + 1791763199999, + 1791763200000, + 1792972799999, + 1792972800000, + 1793102400000, + 1798761600000, + 81062899200000, + 81064108800000 + ] + }, + "expected": [ + null, + 0, + 0, + 1, + 1, + 5, + 65535, + null + ] +} diff --git a/forge-contracts/vectors/board_iteration__range.json b/forge-contracts/vectors/board_iteration__range.json new file mode 100644 index 000000000..18e1dbe86 --- /dev/null +++ b/forge-contracts/vectors/board_iteration__range.json @@ -0,0 +1,158 @@ +{ + "name": "range", + "description": "iterationRange: iteration k runs from start + k·days for days days, named \" k+1\"; across a year end; the last index; past it none.", + "case": "board_iteration", + "rules": "v2", + "input": { + "op": "range", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "field": 3, + "ks": [ + 0, + 1, + 6, + 65535, + 65536, + -1 + ] + }, + "expected": [ + { + "index": 0, + "name": "Iteration 1", + "start": "2026-10-12", + "end": "2026-10-25", + "startMs": 1791763200000, + "endMs": 1792972800000 + }, + { + "index": 1, + "name": "Iteration 2", + "start": "2026-10-26", + "end": "2026-11-08", + "startMs": 1792972800000, + "endMs": 1794182400000 + }, + { + "index": 6, + "name": "Iteration 7", + "start": "2027-01-04", + "end": "2027-01-17", + "startMs": 1799020800000, + "endMs": 1800230400000 + }, + { + "index": 65535, + "name": "Iteration 65536", + "start": "4538-10-13", + "end": "4538-10-26", + "startMs": 81062899200000, + "endMs": 81064108800000 + }, + null, + null + ] +} diff --git a/forge-contracts/vectors/board_iteration__range_leap_year.json b/forge-contracts/vectors/board_iteration__range_leap_year.json new file mode 100644 index 000000000..a5c4ac299 --- /dev/null +++ b/forge-contracts/vectors/board_iteration__range_leap_year.json @@ -0,0 +1,50 @@ +{ + "name": "range_leap_year", + "description": "Ten-day iterations from 2024-02-20 cross 29 February.", + "case": "board_iteration", + "rules": "v2", + "input": { + "op": "range", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "C1" + } + ], + "fields": [ + { + "id": 1, + "name": "Sprint", + "type": "iter", + "start": "2024-02-20", + "days": 10 + } + ] + }, + "field": 1, + "ks": [ + 0, + 1 + ] + }, + "expected": [ + { + "index": 0, + "name": "Sprint 1", + "start": "2024-02-20", + "end": "2024-02-29", + "startMs": 1708387200000, + "endMs": 1709251200000 + }, + { + "index": 1, + "name": "Sprint 2", + "start": "2024-03-01", + "end": "2024-03-10", + "startMs": 1709251200000, + "endMs": 1710115200000 + } + ] +} diff --git a/forge-contracts/vectors/board_query__match_archive_and_state.json b/forge-contracts/vectors/board_query__match_archive_and_state.json new file mode 100644 index 000000000..c4a529de2 --- /dev/null +++ b/forge-contracts/vectors/board_query__match_archive_and_state.json @@ -0,0 +1,334 @@ +{ + "name": "match_archive_and_state", + "description": "Archived items are hidden unless the query has is:archived (then only they show); removed and off-board items never match; is:closed is closed or merged, is:unmerged open or closed; -is:archived is the default.", + "case": "board_query", + "rules": "v2", + "input": { + "op": "match", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "number": 91, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791140400000, + "closedAt": null, + "title": "Crash on start", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "number": 12, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791144000000, + "closedAt": null, + "title": "Docs: exact phrase here", + "labels": [], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "number": 93, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1791147600000, + "closedAt": 1793016000000, + "title": "Refactor", + "labels": [], + "assignees": [], + "milestone": null, + "author": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "id": "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u", + "number": 94, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791151200000, + "closedAt": 1791374400000, + "title": "Old crash", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "number": 95, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "Bob/Lib", + "kind": "issue", + "state": "open", + "createdAt": 1791154800000, + "closedAt": null, + "title": "Other repo thing", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "number": 96, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791158400000, + "closedAt": null, + "title": "Removed one", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g", + "number": 97, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791162000000, + "closedAt": null, + "title": "No fields", + "labels": [], + "assignees": [], + "milestone": "V1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "col": 2, + "rank": null, + "f": "{\"1\":1,\"2\":5,\"3\":1,\"4\":\"2026-10-27\",\"5\":\"needs review soon\"}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "col": 1, + "rank": null, + "f": "{\"1\":2,\"2\":3,\"3\":0,\"4\":\"2026-11-15\"}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "col": 4, + "rank": null, + "f": "{\"1\":1,\"2\":8,\"3\":2,\"4\":\"2026-10-01\"}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "col": 1, + "rank": null, + "f": "{\"2\":1.5,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "col": null, + "rank": null, + "f": null, + "state": 2 + } + ], + "texts": [ + "", + "is:archived", + "-is:archived", + "is:closed", + "is:unmerged", + "is:merged", + "is:pr", + "-is:issue" + ] + }, + "expected": [ + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ] + ] +} diff --git a/forge-contracts/vectors/board_query__match_before_first_iteration.json b/forge-contracts/vectors/board_query__match_before_first_iteration.json new file mode 100644 index 000000000..0973c7cae --- /dev/null +++ b/forge-contracts/vectors/board_query__match_before_first_iteration.json @@ -0,0 +1,308 @@ +{ + "name": "match_before_first_iteration", + "description": "Before an iteration field's first iteration there is no current or previous one, and the next is the first (index 0).", + "case": "board_query", + "rules": "v2", + "input": { + "op": "match", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1791720000000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "number": 91, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791140400000, + "closedAt": null, + "title": "Crash on start", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "number": 12, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791144000000, + "closedAt": null, + "title": "Docs: exact phrase here", + "labels": [], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "number": 93, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1791147600000, + "closedAt": 1793016000000, + "title": "Refactor", + "labels": [], + "assignees": [], + "milestone": null, + "author": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "id": "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u", + "number": 94, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791151200000, + "closedAt": 1791374400000, + "title": "Old crash", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "number": 95, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "Bob/Lib", + "kind": "issue", + "state": "open", + "createdAt": 1791154800000, + "closedAt": null, + "title": "Other repo thing", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "number": 96, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791158400000, + "closedAt": null, + "title": "Removed one", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g", + "number": 97, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791162000000, + "closedAt": null, + "title": "No fields", + "labels": [], + "assignees": [], + "milestone": "V1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "col": 2, + "rank": null, + "f": "{\"1\":1,\"2\":5,\"3\":1,\"4\":\"2026-10-27\",\"5\":\"needs review soon\"}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "col": 1, + "rank": null, + "f": "{\"1\":2,\"2\":3,\"3\":0,\"4\":\"2026-11-15\"}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "col": 4, + "rank": null, + "f": "{\"1\":1,\"2\":8,\"3\":2,\"4\":\"2026-10-01\"}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "col": 1, + "rank": null, + "f": "{\"2\":1.5,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "col": null, + "rank": null, + "f": null, + "state": 2 + } + ], + "texts": [ + "iteration:@current", + "iteration:@next", + "iteration:@previous", + "-iteration:@previous" + ] + }, + "expected": [ + [], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ] + ] +} diff --git a/forge-contracts/vectors/board_query__match_dates.json b/forge-contracts/vectors/board_query__match_dates.json new file mode 100644 index 000000000..2876f6c88 --- /dev/null +++ b/forge-contracts/vectors/board_query__match_dates.json @@ -0,0 +1,315 @@ +{ + "name": "match_dates", + "description": "Dates: <, >=, a range, and @today (now's UTC date, 2026-10-27).", + "case": "board_query", + "rules": "v2", + "input": { + "op": "match", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "number": 91, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791140400000, + "closedAt": null, + "title": "Crash on start", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "number": 12, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791144000000, + "closedAt": null, + "title": "Docs: exact phrase here", + "labels": [], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "number": 93, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1791147600000, + "closedAt": 1793016000000, + "title": "Refactor", + "labels": [], + "assignees": [], + "milestone": null, + "author": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "id": "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u", + "number": 94, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791151200000, + "closedAt": 1791374400000, + "title": "Old crash", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "number": 95, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "Bob/Lib", + "kind": "issue", + "state": "open", + "createdAt": 1791154800000, + "closedAt": null, + "title": "Other repo thing", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "number": 96, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791158400000, + "closedAt": null, + "title": "Removed one", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g", + "number": 97, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791162000000, + "closedAt": null, + "title": "No fields", + "labels": [], + "assignees": [], + "milestone": "V1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "col": 2, + "rank": null, + "f": "{\"1\":1,\"2\":5,\"3\":1,\"4\":\"2026-10-27\",\"5\":\"needs review soon\"}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "col": 1, + "rank": null, + "f": "{\"1\":2,\"2\":3,\"3\":0,\"4\":\"2026-11-15\"}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "col": 4, + "rank": null, + "f": "{\"1\":1,\"2\":8,\"3\":2,\"4\":\"2026-10-01\"}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "col": 1, + "rank": null, + "f": "{\"2\":1.5,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "col": null, + "rank": null, + "f": null, + "state": 2 + } + ], + "texts": [ + "target:<2026-11-01", + "target:@today", + "target:>=@today", + "target:2026-10-01..2026-10-27", + "no:target" + ] + }, + "expected": [ + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ] + ] +} diff --git a/forge-contracts/vectors/board_query__match_fields.json b/forge-contracts/vectors/board_query__match_fields.json new file mode 100644 index 000000000..55c08e570 --- /dev/null +++ b/forge-contracts/vectors/board_query__match_fields.json @@ -0,0 +1,345 @@ +{ + "name": "match_fields", + "description": "Field qualifiers: a select option; numbers compared (a missing value never matches, so -priority:P0 matches items without one); ranges inclusive; no:; text fields contain (any case); status by column; no:status.", + "case": "board_query", + "rules": "v2", + "input": { + "op": "match", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "number": 91, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791140400000, + "closedAt": null, + "title": "Crash on start", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "number": 12, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791144000000, + "closedAt": null, + "title": "Docs: exact phrase here", + "labels": [], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "number": 93, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1791147600000, + "closedAt": 1793016000000, + "title": "Refactor", + "labels": [], + "assignees": [], + "milestone": null, + "author": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "id": "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u", + "number": 94, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791151200000, + "closedAt": 1791374400000, + "title": "Old crash", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "number": 95, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "Bob/Lib", + "kind": "issue", + "state": "open", + "createdAt": 1791154800000, + "closedAt": null, + "title": "Other repo thing", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "number": 96, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791158400000, + "closedAt": null, + "title": "Removed one", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g", + "number": 97, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791162000000, + "closedAt": null, + "title": "No fields", + "labels": [], + "assignees": [], + "milestone": "V1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "col": 2, + "rank": null, + "f": "{\"1\":1,\"2\":5,\"3\":1,\"4\":\"2026-10-27\",\"5\":\"needs review soon\"}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "col": 1, + "rank": null, + "f": "{\"1\":2,\"2\":3,\"3\":0,\"4\":\"2026-11-15\"}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "col": 4, + "rank": null, + "f": "{\"1\":1,\"2\":8,\"3\":2,\"4\":\"2026-10-01\"}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "col": 1, + "rank": null, + "f": "{\"2\":1.5,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "col": null, + "rank": null, + "f": null, + "state": 2 + } + ], + "texts": [ + "priority:P0", + "-priority:P0", + "estimate:>3", + "estimate:>=5", + "estimate:1..3", + "estimate:*..1.5", + "no:priority", + "no:estimate", + "notes:REVIEW", + "status:\"In progress\"", + "-status:Todo", + "no:status" + ] + }, + "expected": [ + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA" + ], + [ + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA" + ], + [ + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [] + ] +} diff --git a/forge-contracts/vectors/board_query__match_iterations.json b/forge-contracts/vectors/board_query__match_iterations.json new file mode 100644 index 000000000..43ef56077 --- /dev/null +++ b/forge-contracts/vectors/board_query__match_iterations.json @@ -0,0 +1,328 @@ +{ + "name": "match_iterations", + "description": "Iterations (start 2026-10-12, 14 days; now 2026-10-27 is in iteration index 1): @current, @next, @previous, <@current, by number (iteration:1 is index 0) and by name.", + "case": "board_query", + "rules": "v2", + "input": { + "op": "match", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "number": 91, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791140400000, + "closedAt": null, + "title": "Crash on start", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "number": 12, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791144000000, + "closedAt": null, + "title": "Docs: exact phrase here", + "labels": [], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "number": 93, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1791147600000, + "closedAt": 1793016000000, + "title": "Refactor", + "labels": [], + "assignees": [], + "milestone": null, + "author": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "id": "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u", + "number": 94, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791151200000, + "closedAt": 1791374400000, + "title": "Old crash", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "number": 95, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "Bob/Lib", + "kind": "issue", + "state": "open", + "createdAt": 1791154800000, + "closedAt": null, + "title": "Other repo thing", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "number": 96, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791158400000, + "closedAt": null, + "title": "Removed one", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g", + "number": 97, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791162000000, + "closedAt": null, + "title": "No fields", + "labels": [], + "assignees": [], + "milestone": "V1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "col": 2, + "rank": null, + "f": "{\"1\":1,\"2\":5,\"3\":1,\"4\":\"2026-10-27\",\"5\":\"needs review soon\"}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "col": 1, + "rank": null, + "f": "{\"1\":2,\"2\":3,\"3\":0,\"4\":\"2026-11-15\"}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "col": 4, + "rank": null, + "f": "{\"1\":1,\"2\":8,\"3\":2,\"4\":\"2026-10-01\"}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "col": 1, + "rank": null, + "f": "{\"2\":1.5,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "col": null, + "rank": null, + "f": null, + "state": 2 + } + ], + "texts": [ + "iteration:@current", + "iteration:@next", + "iteration:@previous", + "iteration:<@current", + "iteration:>=@current", + "iteration:1", + "iteration:\"iteration 3\"", + "-iteration:@current" + ] + }, + "expected": [ + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA" + ], + [ + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [ + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ] + ] +} diff --git a/forge-contracts/vectors/board_query__match_no_viewer.json b/forge-contracts/vectors/board_query__match_no_viewer.json new file mode 100644 index 000000000..045a6c7de --- /dev/null +++ b/forge-contracts/vectors/board_query__match_no_viewer.json @@ -0,0 +1,301 @@ +{ + "name": "match_no_viewer", + "description": "Without a viewer @me matches nobody (and -assignee:@me everybody).", + "case": "board_query", + "rules": "v2", + "input": { + "op": "match", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": null, + "items": [ + { + "id": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "number": 91, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791140400000, + "closedAt": null, + "title": "Crash on start", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "number": 12, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791144000000, + "closedAt": null, + "title": "Docs: exact phrase here", + "labels": [], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "number": 93, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1791147600000, + "closedAt": 1793016000000, + "title": "Refactor", + "labels": [], + "assignees": [], + "milestone": null, + "author": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "id": "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u", + "number": 94, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791151200000, + "closedAt": 1791374400000, + "title": "Old crash", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "number": 95, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "Bob/Lib", + "kind": "issue", + "state": "open", + "createdAt": 1791154800000, + "closedAt": null, + "title": "Other repo thing", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "number": 96, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791158400000, + "closedAt": null, + "title": "Removed one", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g", + "number": 97, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791162000000, + "closedAt": null, + "title": "No fields", + "labels": [], + "assignees": [], + "milestone": "V1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "col": 2, + "rank": null, + "f": "{\"1\":1,\"2\":5,\"3\":1,\"4\":\"2026-10-27\",\"5\":\"needs review soon\"}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "col": 1, + "rank": null, + "f": "{\"1\":2,\"2\":3,\"3\":0,\"4\":\"2026-11-15\"}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "col": 4, + "rank": null, + "f": "{\"1\":1,\"2\":8,\"3\":2,\"4\":\"2026-10-01\"}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "col": 1, + "rank": null, + "f": "{\"2\":1.5,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "col": null, + "rank": null, + "f": null, + "state": 2 + } + ], + "texts": [ + "assignee:@me", + "-assignee:@me" + ] + }, + "expected": [ + [], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ] + ] +} diff --git a/forge-contracts/vectors/board_query__match_people_and_repo.json b/forge-contracts/vectors/board_query__match_people_and_repo.json new file mode 100644 index 000000000..3742d161c --- /dev/null +++ b/forge-contracts/vectors/board_query__match_people_and_repo.json @@ -0,0 +1,344 @@ +{ + "name": "match_people_and_repo", + "description": "assignee:@me is the viewer (none without one), author:, no:assignee, milestone in any case, repo by owner/name in any case or by id, -repo.", + "case": "board_query", + "rules": "v2", + "input": { + "op": "match", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "number": 91, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791140400000, + "closedAt": null, + "title": "Crash on start", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "number": 12, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791144000000, + "closedAt": null, + "title": "Docs: exact phrase here", + "labels": [], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "number": 93, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1791147600000, + "closedAt": 1793016000000, + "title": "Refactor", + "labels": [], + "assignees": [], + "milestone": null, + "author": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "id": "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u", + "number": 94, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791151200000, + "closedAt": 1791374400000, + "title": "Old crash", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "number": 95, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "Bob/Lib", + "kind": "issue", + "state": "open", + "createdAt": 1791154800000, + "closedAt": null, + "title": "Other repo thing", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "number": 96, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791158400000, + "closedAt": null, + "title": "Removed one", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g", + "number": 97, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791162000000, + "closedAt": null, + "title": "No fields", + "labels": [], + "assignees": [], + "milestone": "V1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "col": 2, + "rank": null, + "f": "{\"1\":1,\"2\":5,\"3\":1,\"4\":\"2026-10-27\",\"5\":\"needs review soon\"}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "col": 1, + "rank": null, + "f": "{\"1\":2,\"2\":3,\"3\":0,\"4\":\"2026-11-15\"}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "col": 4, + "rank": null, + "f": "{\"1\":1,\"2\":8,\"3\":2,\"4\":\"2026-10-01\"}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "col": 1, + "rank": null, + "f": "{\"2\":1.5,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "col": null, + "rank": null, + "f": null, + "state": 2 + } + ], + "texts": [ + "assignee:@me", + "assignee:Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "author:Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "no:assignee", + "milestone:v1.0", + "repo:bob/lib", + "repo:EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "-repo:bob/lib", + "label:BUG", + "no:label" + ] + }, + "expected": [ + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [ + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje" + ], + [ + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g" + ] + ] +} diff --git a/forge-contracts/vectors/board_query__match_text.json b/forge-contracts/vectors/board_query__match_text.json new file mode 100644 index 000000000..6b640e06a --- /dev/null +++ b/forge-contracts/vectors/board_query__match_text.json @@ -0,0 +1,319 @@ +{ + "name": "match_text", + "description": "Free text: title words (any case), a quoted phrase, #12 is the number only, a bare 12 the number or the title, -word excludes; an unresolved qualifier does not filter.", + "case": "board_query", + "rules": "v2", + "input": { + "op": "match", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "number": 91, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791140400000, + "closedAt": null, + "title": "Crash on start", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "number": 12, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791144000000, + "closedAt": null, + "title": "Docs: exact phrase here", + "labels": [], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "number": 93, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "merged", + "createdAt": 1791147600000, + "closedAt": 1793016000000, + "title": "Refactor", + "labels": [], + "assignees": [], + "milestone": null, + "author": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "id": "7NB8fAfBXV6XBGALr2V57fdVuyqsFqDewMRNxrm56e4u", + "number": 94, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791151200000, + "closedAt": 1791374400000, + "title": "Old crash", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "number": 95, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "Bob/Lib", + "kind": "issue", + "state": "open", + "createdAt": 1791154800000, + "closedAt": null, + "title": "Other repo thing", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "number": 96, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791158400000, + "closedAt": null, + "title": "Removed one", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7aD4cwnUw5H8CJ2Cbnfswotz6YzqXYrteC2tztarug4g", + "number": 97, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791162000000, + "closedAt": null, + "title": "No fields", + "labels": [], + "assignees": [], + "milestone": "V1.0", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58", + "col": 2, + "rank": null, + "f": "{\"1\":1,\"2\":5,\"3\":1,\"4\":\"2026-10-27\",\"5\":\"needs review soon\"}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP", + "col": 1, + "rank": null, + "f": "{\"1\":2,\"2\":3,\"3\":0,\"4\":\"2026-11-15\"}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7JAVLaHR4HheqasivmkoWHYLX88DAbLaNQYscr9opxje", + "col": 4, + "rank": null, + "f": "{\"1\":1,\"2\":8,\"3\":2,\"4\":\"2026-10-01\"}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "7SBmym2wzgVPWwSxmHDLj3ifJqZXM56jWJHtJsNLNKQA", + "col": 1, + "rank": null, + "f": "{\"2\":1.5,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "7WCRJMQiTstFrcjagXwcLRophhHBSJyp5FAPesybdzjR", + "col": null, + "rank": null, + "f": null, + "state": 2 + } + ], + "texts": [ + "crash", + "\"exact phrase\"", + "#12", + "12", + "#91", + "crash -old", + "priority:P9 crash" + ] + }, + "expected": [ + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [ + "7E9r1yueb6JnVub71X2XtuTB8GQZ5MTVoTgNGqYYZHQP" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58" + ], + [ + "7A9ChPXt7tuvAEJV6GJGHXN1jQgtz7aREWorvpwHHc58" + ] + ] +} diff --git a/forge-contracts/vectors/board_query__parse_board_qualifiers.json b/forge-contracts/vectors/board_query__parse_board_qualifiers.json new file mode 100644 index 000000000..9bececca3 --- /dev/null +++ b/forge-contracts/vectors/board_query__parse_board_qualifiers.json @@ -0,0 +1,287 @@ +{ + "name": "parse_board_qualifiers", + "description": "Board qualifiers: status by column name (any case, quoted), -status, no:status; a select field by option name; number comparisons (>3 >=3 <3 <=2.5 1..5 *..5 2..*); date comparisons and ranges, @today; iterations by @current/@next/@previous, number, or name; no:; text fields (has); a quoted field name with a space.", + "case": "board_query", + "rules": "v2", + "input": { + "op": "parse", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "text": "status:\"in progress\" -status:Done no:status priority:p0 -Priority:P1 estimate:>3 estimate:>=3 estimate:<3 estimate:<=2.5 estimate:1..5 estimate:*..5 estimate:-2..* target:<2026-11-01 target:2026-10-01..2026-10-31 target:>=@today iteration:@current iteration:@NEXT iteration:@previous iteration:2 iteration:\"Iteration 3\" iteration:<@current no:priority notes:\"Needs Review\" \"story points\":>=8" + }, + "expected": { + "preds": [ + { + "k": "status", + "not": false, + "v": 2 + }, + { + "k": "status", + "not": true, + "v": 3 + }, + { + "k": "no", + "not": false, + "v": "status" + }, + { + "k": "field", + "not": false, + "f": 1, + "op": "eq", + "v": 1 + }, + { + "k": "field", + "not": true, + "f": 1, + "op": "eq", + "v": 2 + }, + { + "k": "field", + "not": false, + "f": 2, + "op": "gt", + "v": 3 + }, + { + "k": "field", + "not": false, + "f": 2, + "op": "ge", + "v": 3 + }, + { + "k": "field", + "not": false, + "f": 2, + "op": "lt", + "v": 3 + }, + { + "k": "field", + "not": false, + "f": 2, + "op": "le", + "v": 2.5 + }, + { + "k": "field", + "not": false, + "f": 2, + "op": "range", + "v": 1, + "v2": 5 + }, + { + "k": "field", + "not": false, + "f": 2, + "op": "le", + "v": 5 + }, + { + "k": "field", + "not": false, + "f": 2, + "op": "ge", + "v": -2 + }, + { + "k": "field", + "not": false, + "f": 4, + "op": "lt", + "v": "2026-11-01" + }, + { + "k": "field", + "not": false, + "f": 4, + "op": "range", + "v": "2026-10-01", + "v2": "2026-10-31" + }, + { + "k": "field", + "not": false, + "f": 4, + "op": "ge", + "v": "@today" + }, + { + "k": "field", + "not": false, + "f": 3, + "op": "eq", + "v": "@current" + }, + { + "k": "field", + "not": false, + "f": 3, + "op": "eq", + "v": "@next" + }, + { + "k": "field", + "not": false, + "f": 3, + "op": "eq", + "v": "@previous" + }, + { + "k": "field", + "not": false, + "f": 3, + "op": "eq", + "v": 1 + }, + { + "k": "field", + "not": false, + "f": 3, + "op": "eq", + "v": 2 + }, + { + "k": "field", + "not": false, + "f": 3, + "op": "lt", + "v": "@current" + }, + { + "k": "no", + "not": false, + "v": "f1" + }, + { + "k": "field", + "not": false, + "f": 5, + "op": "has", + "v": "needs review" + }, + { + "k": "field", + "not": false, + "f": 6, + "op": "ge", + "v": 8 + } + ], + "text": "", + "unresolved": [] + } +} diff --git a/forge-contracts/vectors/board_query__parse_issue_qualifiers.json b/forge-contracts/vectors/board_query__parse_issue_qualifiers.json new file mode 100644 index 000000000..1f14ae0d8 --- /dev/null +++ b/forge-contracts/vectors/board_query__parse_issue_qualifiers.json @@ -0,0 +1,180 @@ +{ + "name": "parse_issue_qualifiers", + "description": "The Issues tab's qualifiers in a board query: is:/state:, label (quoted), -label, no:, assignee:@me, author:, milestone (quoted), repo:, is:archived; keys in any case; the rest is free text (#12, -word).", + "case": "board_query", + "rules": "v2", + "input": { + "op": "parse", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "text": "IS:Open -label:wontfix label:\"good first\" no:assignee assignee:@ME author:Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r milestone:\"v1.0\" repo:alice/forge state:merged is:archived -is:pr crash #12 -windows" + }, + "expected": { + "preds": [ + { + "k": "is", + "not": false, + "v": "open" + }, + { + "k": "label", + "not": true, + "v": "wontfix" + }, + { + "k": "label", + "not": false, + "v": "good first" + }, + { + "k": "no", + "not": false, + "v": "assignee" + }, + { + "k": "assignee", + "not": false, + "v": "me" + }, + { + "k": "author", + "not": false, + "v": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "k": "milestone", + "not": false, + "v": "v1.0" + }, + { + "k": "repo", + "not": false, + "v": "alice/forge" + }, + { + "k": "is", + "not": false, + "v": "merged" + }, + { + "k": "is", + "not": false, + "v": "archived" + }, + { + "k": "is", + "not": true, + "v": "pr" + } + ], + "text": "crash #12 -windows", + "unresolved": [] + } +} diff --git a/forge-contracts/vectors/board_query__parse_source.json b/forge-contracts/vectors/board_query__parse_source.json new file mode 100644 index 000000000..41f2e544c --- /dev/null +++ b/forge-contracts/vectors/board_query__parse_source.json @@ -0,0 +1,152 @@ +{ + "name": "parse_source", + "description": "A source's query keeps only what the item itself answers: status:, custom fields, no:status / no:, is:archived and @me are reported (a source is the same for every reader, before any card).", + "case": "board_query", + "rules": "v2", + "input": { + "op": "source", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "text": "label:bug status:Todo priority:P0 no:priority no:status no:label assignee:@me author:Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r -is:archived is:open fix" + }, + "expected": { + "preds": [ + { + "k": "label", + "not": false, + "v": "bug" + }, + { + "k": "no", + "not": false, + "v": "label" + }, + { + "k": "author", + "not": false, + "v": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r" + }, + { + "k": "is", + "not": false, + "v": "open" + } + ], + "text": "fix", + "unresolved": [ + "status:Todo", + "priority:P0", + "no:priority", + "no:status", + "assignee:@me", + "-is:archived" + ] + } +} diff --git a/forge-contracts/vectors/board_query__parse_unresolved.json b/forge-contracts/vectors/board_query__parse_unresolved.json new file mode 100644 index 000000000..2548ff411 --- /dev/null +++ b/forge-contracts/vectors/board_query__parse_unresolved.json @@ -0,0 +1,144 @@ +{ + "name": "parse_unresolved", + "description": "What names nothing on this board is reported, never searched as text: an unknown field, option or column, a value of the wrong shape, an empty value of a known key, a DPNS name (resolve it first), is:draft, -no: is applied (NOT). A key with nothing after the colon and a URL stay text.", + "case": "board_query", + "rules": "v2", + "input": { + "op": "parse", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Story points", + "type": "num" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "text": "foo:bar priority:P9 status:Nope estimate:abc estimate:*..* estimate:1e3 iteration:0 target:2026-13-01 is:draft state:issue assignee:alice.dash label: -no:label note: https://example.com/x \"story pts\":3 plain" + }, + "expected": { + "preds": [ + { + "k": "no", + "not": true, + "v": "label" + } + ], + "text": "note: https://example.com/x plain", + "unresolved": [ + "foo:bar", + "priority:P9", + "status:Nope", + "estimate:abc", + "estimate:*..*", + "estimate:1e3", + "iteration:0", + "target:2026-13-01", + "is:draft", + "state:issue", + "assignee:alice.dash", + "label:", + "\"story pts\":3" + ] + } +} diff --git a/forge-contracts/vectors/board_rank__between.json b/forge-contracts/vectors/board_rank__between.json new file mode 100644 index 000000000..889933525 --- /dev/null +++ b/forge-contracts/vectors/board_rank__between.json @@ -0,0 +1,167 @@ +{ + "name": "between", + "description": "rankBetween(a, b): strictly between in byte order, never ending in 0, the midpoint of the free digits (\"\" is open at either end). Prefix pairs (V / V1, V1 / V11), neighbours with no digit between (A / B: one more digit), the top (z) and bottom (0) of the alphabet.", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "between", + "pairs": [ + [ + "", + "" + ], + [ + null, + null + ], + [ + "", + "V" + ], + [ + "W", + "" + ], + [ + "A", + "C" + ], + [ + "A", + "B" + ], + [ + "Az", + "B" + ], + [ + "U", + "V1" + ], + [ + "V", + "V1" + ], + [ + "V", + "W" + ], + [ + "V1", + "V11" + ], + [ + "V1", + "V2" + ], + [ + "0", + "1" + ], + [ + "", + "1" + ], + [ + "", + "01" + ], + [ + "", + "001" + ], + [ + "z", + "" + ], + [ + "zz", + "" + ], + [ + "y", + "z" + ], + [ + "yz", + "z" + ], + [ + "F", + "F1" + ], + [ + "F", + "F01" + ] + ] + }, + "expected": [ + { + "rank": "V" + }, + { + "rank": "V" + }, + { + "rank": "F" + }, + { + "rank": "l" + }, + { + "rank": "B" + }, + { + "rank": "AV" + }, + { + "rank": "AzV" + }, + { + "rank": "V" + }, + { + "rank": "V0V" + }, + { + "rank": "VV" + }, + { + "rank": "V10V" + }, + { + "rank": "V1V" + }, + { + "rank": "0V" + }, + { + "rank": "0V" + }, + { + "rank": "00V" + }, + { + "rank": "000V" + }, + { + "rank": "zV" + }, + { + "rank": "zzV" + }, + { + "rank": "yV" + }, + { + "rank": "yzV" + }, + { + "rank": "F0V" + }, + { + "rank": "F00V" + } + ] +} diff --git a/forge-contracts/vectors/board_rank__between_implicit_bounds.json b/forge-contracts/vectors/board_rank__between_implicit_bounds.json new file mode 100644 index 000000000..94762fee0 --- /dev/null +++ b/forge-contracts/vectors/board_rank__between_implicit_bounds.json @@ -0,0 +1,55 @@ +{ + "name": "between_implicit_bounds", + "description": "Bounds that are implicit ranks (13 digits, may end in 0): between two sourced items of one block, between a card and a sourced item, and below / above one.", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "between", + "pairs": [ + [ + "V0ABCDEFG1230", + "V0ABCDEFG1231" + ], + [ + "V0ABCDEFG1230", + "V0ABCDEFG1300" + ], + [ + "V0ABCDEFGzzz0", + "V0ABCDEFH0000" + ], + [ + "F", + "V0ABCDEFG1230" + ], + [ + "V0ABCDEFG1230", + "l" + ], + [ + "V0ABCDEFG1230", + "V0ABCDEFG12300V" + ] + ] + }, + "expected": [ + { + "rank": "V0ABCDEFG1230V" + }, + { + "rank": "V0ABCDEFG13" + }, + { + "rank": "V0ABCDEFH" + }, + { + "rank": "N" + }, + { + "rank": "d" + }, + { + "rank": "V0ABCDEFG12300F" + } + ] +} diff --git a/forge-contracts/vectors/board_rank__between_refused.json b/forge-contracts/vectors/board_rank__between_refused.json new file mode 100644 index 000000000..1937ce718 --- /dev/null +++ b/forge-contracts/vectors/board_rank__between_refused.json @@ -0,0 +1,111 @@ +{ + "name": "between_refused", + "description": "Refusals: the lower bound above the upper (order); equal bounds (two members dropped into one gap at once and wrote one rank) are re-rank; a bound that is not rank digits or over 63 (invalid), and no rank of at most 63 digits between (re-rank): b = a + 0…0 (V / V0, \"\" / 0) and a 63-digit lower bound with nothing above it in 63 digits.", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "between", + "pairs": [ + [ + "B", + "A" + ], + [ + "A", + "A" + ], + [ + "V1", + "V" + ], + [ + "a-b", + "" + ], + [ + "", + "é" + ], + [ + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV", + "" + ], + [ + "V", + "V0" + ], + [ + "V1", + "V100" + ], + [ + "", + "0" + ], + [ + "", + "000" + ], + [ + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", + "" + ], + [ + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", + "" + ], + [ + "", + "000000000000000000000000000000000000000000000000000000000000001" + ], + [ + "V0ABCDEFG1230", + "V0ABCDEFG1230" + ] + ] + }, + "expected": [ + { + "error": "order" + }, + { + "error": "re-rank" + }, + { + "error": "order" + }, + { + "error": "invalid" + }, + { + "error": "invalid" + }, + { + "error": "invalid" + }, + { + "error": "re-rank" + }, + { + "error": "re-rank" + }, + { + "error": "re-rank" + }, + { + "error": "re-rank" + }, + { + "error": "re-rank" + }, + { + "rank": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzV" + }, + { + "error": "re-rank" + }, + { + "error": "re-rank" + } + ] +} diff --git a/forge-contracts/vectors/board_rank__bottom.json b/forge-contracts/vectors/board_rank__bottom.json new file mode 100644 index 000000000..63af66b56 --- /dev/null +++ b/forge-contracts/vectors/board_rank__bottom.json @@ -0,0 +1,45 @@ +{ + "name": "bottom", + "description": "bottomRank(last) = rankBetween(max(last, \"W\"), \"\"): below the column and the sourced pool, so later sourced items (V…) never pass it.", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "bottom", + "lasts": [ + null, + "V", + "W", + "l", + "z", + "zz", + "V0ABCDEFG1230", + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + ] + }, + "expected": [ + { + "rank": "l" + }, + { + "rank": "l" + }, + { + "rank": "l" + }, + { + "rank": "s" + }, + { + "rank": "zV" + }, + { + "rank": "zzV" + }, + { + "rank": "l" + }, + { + "error": "re-rank" + } + ] +} diff --git a/forge-contracts/vectors/board_rank__implicit.json b/forge-contracts/vectors/board_rank__implicit.json new file mode 100644 index 000000000..43ebeffcc --- /dev/null +++ b/forge-contracts/vectors/board_rank__implicit.json @@ -0,0 +1,48 @@ +{ + "name": "implicit", + "description": "Implicit ranks: V + $createdAt in 8 base-62 digits + the first 3 bytes of the item $id (big-endian, mod 62^4) in 4. Items of one block (same $createdAt) differ by id; 0xFFFFFF wraps mod 62^4; leading zero bytes (base58 \"1…\"); a time past 62^8 clamps; an id that is not base58 reads as zero bytes.", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "implicit", + "items": [ + { + "createdAt": 0, + "id": "1113eKEmP3gmGaNeoKSVoYwPpyfTmrmizMbi1TqGj2" + }, + { + "createdAt": 1793102400000, + "id": "4wBqjG7ot2Yh7rmZH2TnTTiNfnkjtVZAZBzCrpAzziV" + }, + { + "createdAt": 1793102400000, + "id": "4wC3PxcZmLQCWc587TrKavgTRYrW4VEZtLuPrrc4QAv" + }, + { + "createdAt": 1793102400000, + "id": "JEKNJMGgDzL9VWNzXbjVraMJri27JLwhwLkBfTRecuQw" + }, + { + "createdAt": 1793102400000, + "id": "112QabqpfPtBDgyDYU5suefhVfk1HR3Gs6i8bH6kHjz" + }, + { + "createdAt": 218340105584901, + "id": "R4rvZFbpBND34iiWXNcfHXyN9JwYSHUQgE354ead4zZ" + }, + { + "createdAt": 1793102400000, + "id": "not-base58-0OIl" + } + ] + }, + "expected": [ + "V000000000000", + "V0VZFavzc0HBL", + "V0VZFavzc0HBM", + "V0VZFavzc8OWF", + "V0VZFavzc0007", + "Vzzzzzzzz1h6s", + "V0VZFavzc0000" + ] +} diff --git a/forge-contracts/vectors/board_rank__rerank_empty.json b/forge-contracts/vectors/board_rank__rerank_empty.json new file mode 100644 index 000000000..fe780da02 --- /dev/null +++ b/forge-contracts/vectors/board_rank__rerank_empty.json @@ -0,0 +1,13 @@ +{ + "name": "rerank_empty", + "description": "rerank(0): no ranks.", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "rerank", + "n": 0 + }, + "expected": { + "ranks": [] + } +} diff --git a/forge-contracts/vectors/board_rank__rerank_three.json b/forge-contracts/vectors/board_rank__rerank_three.json new file mode 100644 index 000000000..be78e79e7 --- /dev/null +++ b/forge-contracts/vectors/board_rank__rerank_three.json @@ -0,0 +1,17 @@ +{ + "name": "rerank_three", + "description": "rerank(3): k/4 of the way from 0 to V in 2 digits (31·62 = 1922 ≥ 62·4), trailing zeros dropped: all below the sourced pool.", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "rerank", + "n": 3 + }, + "expected": { + "ranks": [ + "7k", + "FV", + "NF" + ] + } +} diff --git a/forge-contracts/vectors/board_rank__rerank_too_many.json b/forge-contracts/vectors/board_rank__rerank_too_many.json new file mode 100644 index 000000000..5f12aa473 --- /dev/null +++ b/forge-contracts/vectors/board_rank__rerank_too_many.json @@ -0,0 +1,13 @@ +{ + "name": "rerank_too_many", + "description": "rerank past 1 000 000 items is refused (invalid).", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "rerank", + "n": 1000001 + }, + "expected": { + "error": "invalid" + } +} diff --git a/forge-contracts/vectors/board_rank__rerank_wide.json b/forge-contracts/vectors/board_rank__rerank_wide.json new file mode 100644 index 000000000..6bbbd3a79 --- /dev/null +++ b/forge-contracts/vectors/board_rank__rerank_wide.json @@ -0,0 +1,45 @@ +{ + "name": "rerank_wide", + "description": "rerank(31): 2 digits would leave under 62 ranks between neighbours (1922 < 62·32), so 3 digits.", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "rerank", + "n": 31 + }, + "expected": { + "ranks": [ + "0y3", + "1w7", + "2uB", + "3sF", + "4qJ", + "5oN", + "6mR", + "7kV", + "8iY", + "9gc", + "Aeg", + "Bck", + "Cao", + "DYs", + "EWw", + "FV", + "GT3", + "HR7", + "IPB", + "JNF", + "KLJ", + "LJN", + "MHR", + "NFV", + "ODY", + "PBc", + "Q9g", + "R7k", + "S5o", + "T3s", + "U1w" + ] + } +} diff --git a/forge-contracts/vectors/board_rank__top.json b/forge-contracts/vectors/board_rank__top.json new file mode 100644 index 000000000..395ee5156 --- /dev/null +++ b/forge-contracts/vectors/board_rank__top.json @@ -0,0 +1,49 @@ +{ + "name": "top", + "description": "topRank(first) = rankBetween(\"\", min(first, \"V\")): above the column and the sourced pool; an empty column (null) as below \"V\".", + "case": "board_rank", + "rules": "v2", + "input": { + "op": "top", + "firsts": [ + null, + "V", + "W", + "z", + "F", + "5", + "1", + "01", + "V0ABCDEFG1230" + ] + }, + "expected": [ + { + "rank": "F" + }, + { + "rank": "F" + }, + { + "rank": "F" + }, + { + "rank": "F" + }, + { + "rank": "7" + }, + { + "rank": "2" + }, + { + "rank": "0V" + }, + { + "rank": "00V" + }, + { + "rank": "F" + } + ] +} diff --git a/forge-contracts/vectors/board_spec__default_template.json b/forge-contracts/vectors/board_spec__default_template.json new file mode 100644 index 000000000..160ae5452 --- /dev/null +++ b/forge-contracts/vectors/board_spec__default_template.json @@ -0,0 +1,14 @@ +{ + "name": "default_template", + "description": "The new-board template (§2): Todo / In progress / Done, Done = done column, default = Todo, the home repo's issues and PRs, Priority P0-P3 + Estimate + a 14-day Iteration from the Monday of the creation week (2026-10-27 is a Tuesday: 2026-10-26), Board / Table / Roadmap views, auto-archive 14 days; canonical JSON.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "default", + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000 + }, + "expected": { + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3,\"sources\":[{\"r\":\"EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h\",\"k\":\"a\"}],\"fields\":[{\"id\":1,\"name\":\"Priority\",\"type\":\"sel\",\"options\":[{\"id\":1,\"name\":\"P0\",\"color\":\"#d1242f\"},{\"id\":2,\"name\":\"P1\",\"color\":\"#fb8f44\"},{\"id\":3,\"name\":\"P2\",\"color\":\"#d4a72c\"},{\"id\":4,\"name\":\"P3\",\"color\":\"#8c959f\"}]},{\"id\":2,\"name\":\"Estimate\",\"type\":\"num\"},{\"id\":3,\"name\":\"Iteration\",\"type\":\"iter\",\"start\":\"2026-10-26\",\"days\":14}],\"views\":[{\"id\":1,\"name\":\"Board\",\"layout\":\"board\"},{\"id\":2,\"name\":\"Table\",\"layout\":\"table\",\"cols\":[\"title\",\"status\",\"assignees\",\"f1\",\"f2\",\"f3\"]},{\"id\":3,\"name\":\"Roadmap\",\"layout\":\"roadmap\",\"date\":[3]}],\"arch\":14}" + } +} diff --git a/forge-contracts/vectors/board_spec__parse_canonical.json b/forge-contracts/vectors/board_spec__parse_canonical.json new file mode 100644 index 000000000..ea3210deb --- /dev/null +++ b/forge-contracts/vectors/board_spec__parse_canonical.json @@ -0,0 +1,61 @@ +{ + "name": "parse_canonical", + "description": "A spec in any key order, with white space, an unknown key (tolerated, dropped), defaults written out and 1.0 for an id, reads back as canonical JSON: the declared key order, defaults (def/done/arch 0, empty q, empty lists) omitted.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "parse", + "cases": [ + { + "name": "scrambled", + "json": "{ \"arch\": 0, \"future\": {\"x\": 1}, \"views\": [{\"q\": \"\", \"layout\": \"table\", \"name\": \"T\", \"id\": 1.0, \"sort\": \"-f1\", \"cols\": [\"title\", \"f1\"]}],\n \"fields\": [{\"type\": \"num\", \"name\": \"Estimate\", \"id\": 1}], \"sources\": [], \"done\": 2, \"def\": 0,\n \"columns\": [{\"wip\": 3, \"name\": \"Todo\", \"id\": 1, \"color\": \"#AbCdEf\"}, {\"name\": \"Done\", \"id\": 2}], \"v\": 1 }" + }, + { + "name": "minimal", + "json": "{\"v\":1,\"columns\":[{\"id\":7,\"name\":\"Only\"}]}" + }, + { + "name": "source_defaults", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"sources\":[{\"k\":\"i\",\"q\":\"\"},{\"k\":\"p\",\"r\":\"EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx\",\"q\":\"label:bug\"}]}" + }, + { + "name": "unicode_names", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\"},{\"id\":2,\"name\":\"Ünïcødé\"}]}" + }, + { + "name": "desc", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"desc\":\"Line one\\nline \\\"two\\\"\"}" + }, + { + "name": "views_all_keys", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"Pri\",\"type\":\"sel\",\"options\":[{\"id\":1,\"name\":\"High\",\"color\":\"#ff0000\"}]},{\"id\":2,\"name\":\"Start\",\"type\":\"date\"},{\"id\":3,\"name\":\"End\",\"type\":\"date\"},{\"id\":4,\"name\":\"Sprint\",\"type\":\"iter\",\"start\":\"2026-01-05\",\"days\":7}],\"views\":[{\"id\":1,\"name\":\"B\",\"layout\":\"board\",\"group\":\"f1\",\"lane\":\"assignee\",\"q\":\"is:open\"},{\"id\":2,\"name\":\"R\",\"layout\":\"roadmap\",\"date\":[2,3]},{\"id\":3,\"name\":\"S\",\"layout\":\"roadmap\",\"date\":[4],\"group\":\"f4\"},{\"id\":4,\"name\":\"T\",\"layout\":\"table\",\"group\":\"milestone\",\"lane\":\"f4\",\"sort\":\"created\"}]}" + } + ] + }, + "expected": [ + { + "name": "scrambled", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\",\"color\":\"#AbCdEf\",\"wip\":3},{\"id\":2,\"name\":\"Done\"}],\"done\":2,\"fields\":[{\"id\":1,\"name\":\"Estimate\",\"type\":\"num\"}],\"views\":[{\"id\":1,\"name\":\"T\",\"layout\":\"table\",\"sort\":\"-f1\",\"cols\":[\"title\",\"f1\"]}]}" + }, + { + "name": "minimal", + "json": "{\"v\":1,\"columns\":[{\"id\":7,\"name\":\"Only\"}]}" + }, + { + "name": "source_defaults", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"sources\":[{\"k\":\"i\"},{\"r\":\"EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx\",\"k\":\"p\",\"q\":\"label:bug\"}]}" + }, + { + "name": "unicode_names", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\"},{\"id\":2,\"name\":\"Ünïcødé\"}]}" + }, + { + "name": "desc", + "json": "{\"v\":1,\"desc\":\"Line one\\nline \\\"two\\\"\",\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}]}" + }, + { + "name": "views_all_keys", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"Pri\",\"type\":\"sel\",\"options\":[{\"id\":1,\"name\":\"High\",\"color\":\"#ff0000\"}]},{\"id\":2,\"name\":\"Start\",\"type\":\"date\"},{\"id\":3,\"name\":\"End\",\"type\":\"date\"},{\"id\":4,\"name\":\"Sprint\",\"type\":\"iter\",\"start\":\"2026-01-05\",\"days\":7}],\"views\":[{\"id\":1,\"name\":\"B\",\"layout\":\"board\",\"q\":\"is:open\",\"group\":\"f1\",\"lane\":\"assignee\"},{\"id\":2,\"name\":\"R\",\"layout\":\"roadmap\",\"date\":[2,3]},{\"id\":3,\"name\":\"S\",\"layout\":\"roadmap\",\"group\":\"f4\",\"date\":[4]},{\"id\":4,\"name\":\"T\",\"layout\":\"table\",\"group\":\"milestone\",\"lane\":\"f4\",\"sort\":\"created\"}]}" + } + ] +} diff --git a/forge-contracts/vectors/board_spec__parse_refused.json b/forge-contracts/vectors/board_spec__parse_refused.json new file mode 100644 index 000000000..ef46a057f --- /dev/null +++ b/forge-contracts/vectors/board_spec__parse_refused.json @@ -0,0 +1,501 @@ +{ + "name": "parse_refused", + "description": "Every refusal names the first problem in the canonical key order: not JSON / not an object (json), v not 1 (version), over 4096 bytes (size), a list over its limit (columns, fields, sources, views), a malformed or repeated entry (an id, or a name in any letter case) (column, field, options, source, view), a dangling def / done, arch, desc.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "parse", + "cases": [ + { + "name": "not_json", + "json": "{\"v\":1," + }, + { + "name": "array", + "json": "[1]" + }, + { + "name": "version_2", + "json": "{\"v\":2,\"columns\":[{\"id\":1,\"name\":\"C1\"}]}" + }, + { + "name": "version_missing", + "json": "{\"columns\":[{\"id\":1,\"name\":\"C1\"}]}" + }, + { + "name": "oversize", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"desc\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"table\",\"q\":\"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\"}],\"sources\":[{\"k\":\"a\",\"q\":\"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\"},{\"k\":\"a\",\"q\":\"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\"},{\"k\":\"a\",\"q\":\"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\"},{\"k\":\"a\",\"q\":\"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\"},{\"k\":\"a\",\"q\":\"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\"}]}" + }, + { + "name": "no_columns", + "json": "{\"v\":1,\"columns\":[]}" + }, + { + "name": "columns_21", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"C1\"},{\"id\":2,\"name\":\"C2\"},{\"id\":3,\"name\":\"C3\"},{\"id\":4,\"name\":\"C4\"},{\"id\":5,\"name\":\"C5\"},{\"id\":6,\"name\":\"C6\"},{\"id\":7,\"name\":\"C7\"},{\"id\":8,\"name\":\"C8\"},{\"id\":9,\"name\":\"C9\"},{\"id\":10,\"name\":\"C10\"},{\"id\":11,\"name\":\"C11\"},{\"id\":12,\"name\":\"C12\"},{\"id\":13,\"name\":\"C13\"},{\"id\":14,\"name\":\"C14\"},{\"id\":15,\"name\":\"C15\"},{\"id\":16,\"name\":\"C16\"},{\"id\":17,\"name\":\"C17\"},{\"id\":18,\"name\":\"C18\"},{\"id\":19,\"name\":\"C19\"},{\"id\":20,\"name\":\"C20\"},{\"id\":21,\"name\":\"C21\"}]}" + }, + { + "name": "columns_20", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"C1\"},{\"id\":2,\"name\":\"C2\"},{\"id\":3,\"name\":\"C3\"},{\"id\":4,\"name\":\"C4\"},{\"id\":5,\"name\":\"C5\"},{\"id\":6,\"name\":\"C6\"},{\"id\":7,\"name\":\"C7\"},{\"id\":8,\"name\":\"C8\"},{\"id\":9,\"name\":\"C9\"},{\"id\":10,\"name\":\"C10\"},{\"id\":11,\"name\":\"C11\"},{\"id\":12,\"name\":\"C12\"},{\"id\":13,\"name\":\"C13\"},{\"id\":14,\"name\":\"C14\"},{\"id\":15,\"name\":\"C15\"},{\"id\":16,\"name\":\"C16\"},{\"id\":17,\"name\":\"C17\"},{\"id\":18,\"name\":\"C18\"},{\"id\":19,\"name\":\"C19\"},{\"id\":20,\"name\":\"C20\"}]}" + }, + { + "name": "column_id_0", + "json": "{\"v\":1,\"columns\":[{\"id\":0,\"name\":\"C0\"}]}" + }, + { + "name": "column_id_256", + "json": "{\"v\":1,\"columns\":[{\"id\":256,\"name\":\"C256\"}]}" + }, + { + "name": "column_id_fraction", + "json": "{\"v\":1,\"columns\":[{\"id\":1.5,\"name\":\"C1.5\"}]}" + }, + { + "name": "column_id_repeated", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"},{\"id\":1,\"name\":\"B\"}]}" + }, + { + "name": "column_name_repeated_case", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"TODO\"}]}" + }, + { + "name": "column_name_quote", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"say \\\"hi\\\"\"}]}" + }, + { + "name": "column_name_leading_space", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\" Todo\"}]}" + }, + { + "name": "column_name_nbsp_end", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo \"}]}" + }, + { + "name": "column_name_control", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"To\\u0007do\"}]}" + }, + { + "name": "column_name_64", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\"}]}" + }, + { + "name": "column_name_empty", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"\"}]}" + }, + { + "name": "column_color", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\",\"color\":\"red\"}]}" + }, + { + "name": "column_color_null", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\",\"color\":null}]}" + }, + { + "name": "column_wip_0", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\",\"wip\":0}]}" + }, + { + "name": "def_missing_column", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"def\":9}" + }, + { + "name": "done_missing_column", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"done\":9}" + }, + { + "name": "done_string", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"done\":\"2\"}" + }, + { + "name": "sources_6", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"sources\":[{\"k\":\"a\"},{\"k\":\"a\"},{\"k\":\"a\"},{\"k\":\"a\"},{\"k\":\"a\"},{\"k\":\"a\"}]}" + }, + { + "name": "source_kind", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"sources\":[{\"k\":\"x\"}]}" + }, + { + "name": "source_repo_not_id", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"sources\":[{\"k\":\"a\",\"r\":\"alice/forge\"}]}" + }, + { + "name": "source_query_513", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"sources\":[{\"k\":\"a\",\"q\":\"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\"}]}" + }, + { + "name": "fields_13", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"F0\",\"type\":\"num\"},{\"id\":2,\"name\":\"F1\",\"type\":\"num\"},{\"id\":3,\"name\":\"F2\",\"type\":\"num\"},{\"id\":4,\"name\":\"F3\",\"type\":\"num\"},{\"id\":5,\"name\":\"F4\",\"type\":\"num\"},{\"id\":6,\"name\":\"F5\",\"type\":\"num\"},{\"id\":7,\"name\":\"F6\",\"type\":\"num\"},{\"id\":8,\"name\":\"F7\",\"type\":\"num\"},{\"id\":9,\"name\":\"F8\",\"type\":\"num\"},{\"id\":10,\"name\":\"F9\",\"type\":\"num\"},{\"id\":11,\"name\":\"F10\",\"type\":\"num\"},{\"id\":12,\"name\":\"F11\",\"type\":\"num\"},{\"id\":13,\"name\":\"F12\",\"type\":\"num\"}]}" + }, + { + "name": "field_reserved_status", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"Status\",\"type\":\"sel\",\"options\":[]}]}" + }, + { + "name": "field_reserved_labels", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"labels\",\"type\":\"text\"}]}" + }, + { + "name": "field_name_colon", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"a:b\",\"type\":\"text\"}]}" + }, + { + "name": "field_name_dash", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"-x\",\"type\":\"text\"}]}" + }, + { + "name": "field_type", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"X\",\"type\":\"multi\"}]}" + }, + { + "name": "field_options_on_num", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"X\",\"type\":\"num\",\"options\":[]}]}" + }, + { + "name": "field_sel_without_options", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"X\",\"type\":\"sel\"}]}" + }, + { + "name": "field_start_on_date", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"X\",\"type\":\"date\",\"start\":\"2026-01-01\"}]}" + }, + { + "name": "field_repeated_name", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"Pts\",\"type\":\"num\"},{\"id\":2,\"name\":\"pts\",\"type\":\"text\"}]}" + }, + { + "name": "options_31", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"X\",\"type\":\"sel\",\"options\":[{\"id\":1,\"name\":\"o0\"},{\"id\":2,\"name\":\"o1\"},{\"id\":3,\"name\":\"o2\"},{\"id\":4,\"name\":\"o3\"},{\"id\":5,\"name\":\"o4\"},{\"id\":6,\"name\":\"o5\"},{\"id\":7,\"name\":\"o6\"},{\"id\":8,\"name\":\"o7\"},{\"id\":9,\"name\":\"o8\"},{\"id\":10,\"name\":\"o9\"},{\"id\":11,\"name\":\"o10\"},{\"id\":12,\"name\":\"o11\"},{\"id\":13,\"name\":\"o12\"},{\"id\":14,\"name\":\"o13\"},{\"id\":15,\"name\":\"o14\"},{\"id\":16,\"name\":\"o15\"},{\"id\":17,\"name\":\"o16\"},{\"id\":18,\"name\":\"o17\"},{\"id\":19,\"name\":\"o18\"},{\"id\":20,\"name\":\"o19\"},{\"id\":21,\"name\":\"o20\"},{\"id\":22,\"name\":\"o21\"},{\"id\":23,\"name\":\"o22\"},{\"id\":24,\"name\":\"o23\"},{\"id\":25,\"name\":\"o24\"},{\"id\":26,\"name\":\"o25\"},{\"id\":27,\"name\":\"o26\"},{\"id\":28,\"name\":\"o27\"},{\"id\":29,\"name\":\"o28\"},{\"id\":30,\"name\":\"o29\"},{\"id\":31,\"name\":\"o30\"}]}]}" + }, + { + "name": "options_repeated", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"X\",\"type\":\"sel\",\"options\":[{\"id\":1,\"name\":\"a\"},{\"id\":2,\"name\":\"A\"}]}]}" + }, + { + "name": "options_0_ok", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"X\",\"type\":\"sel\",\"options\":[]}]}" + }, + { + "name": "iter_no_start", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"It\",\"type\":\"iter\",\"days\":14}]}" + }, + { + "name": "iter_days_91", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"It\",\"type\":\"iter\",\"start\":\"2026-01-05\",\"days\":91}]}" + }, + { + "name": "iter_start_feb_30", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"It\",\"type\":\"iter\",\"start\":\"2026-02-30\",\"days\":14}]}" + }, + { + "name": "views_9", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"views\":[{\"id\":1,\"name\":\"V0\",\"layout\":\"table\"},{\"id\":2,\"name\":\"V1\",\"layout\":\"table\"},{\"id\":3,\"name\":\"V2\",\"layout\":\"table\"},{\"id\":4,\"name\":\"V3\",\"layout\":\"table\"},{\"id\":5,\"name\":\"V4\",\"layout\":\"table\"},{\"id\":6,\"name\":\"V5\",\"layout\":\"table\"},{\"id\":7,\"name\":\"V6\",\"layout\":\"table\"},{\"id\":8,\"name\":\"V7\",\"layout\":\"table\"},{\"id\":9,\"name\":\"V8\",\"layout\":\"table\"}]}" + }, + { + "name": "view_layout", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"kanban\"}]}" + }, + { + "name": "view_board_group_assignee", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"board\",\"group\":\"assignee\"}]}" + }, + { + "name": "view_lane_is_group", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"table\",\"group\":\"label\",\"lane\":\"label\"}]}" + }, + { + "name": "view_lane_status", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"board\",\"lane\":\"status\"}]}" + }, + { + "name": "view_group_num_field", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"E\",\"type\":\"num\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"table\",\"group\":\"f1\"}]}" + }, + { + "name": "view_sort_unknown", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"table\",\"sort\":\"priority\"}]}" + }, + { + "name": "view_sort_missing_field", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"table\",\"sort\":\"-f9\"}]}" + }, + { + "name": "view_cols_repeated", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"table\",\"cols\":[\"title\",\"title\"]}]}" + }, + { + "name": "view_cols_f01", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"E\",\"type\":\"num\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"table\",\"cols\":[\"f01\"]}]}" + }, + { + "name": "view_date_num_field", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"E\",\"type\":\"num\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"roadmap\",\"date\":[1]}]}" + }, + { + "name": "view_repeated_name", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"views\":[{\"id\":1,\"name\":\"V\",\"layout\":\"table\"},{\"id\":2,\"name\":\"v\",\"layout\":\"board\"}]}" + }, + { + "name": "arch_3651", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"arch\":3651}" + }, + { + "name": "desc_type", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"desc\":5}" + }, + { + "name": "desc_1025", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"desc\":\"ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd\"}" + }, + { + "name": "view_date_same_field", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"Start\",\"type\":\"date\"}],\"views\":[{\"id\":1,\"name\":\"R\",\"layout\":\"roadmap\",\"date\":[1,1]}]}" + } + ] + }, + "expected": [ + { + "name": "not_json", + "error": "json" + }, + { + "name": "array", + "error": "json" + }, + { + "name": "version_2", + "error": "version" + }, + { + "name": "version_missing", + "error": "version" + }, + { + "name": "oversize", + "error": "size" + }, + { + "name": "no_columns", + "error": "columns" + }, + { + "name": "columns_21", + "error": "columns" + }, + { + "name": "columns_20", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"C1\"},{\"id\":2,\"name\":\"C2\"},{\"id\":3,\"name\":\"C3\"},{\"id\":4,\"name\":\"C4\"},{\"id\":5,\"name\":\"C5\"},{\"id\":6,\"name\":\"C6\"},{\"id\":7,\"name\":\"C7\"},{\"id\":8,\"name\":\"C8\"},{\"id\":9,\"name\":\"C9\"},{\"id\":10,\"name\":\"C10\"},{\"id\":11,\"name\":\"C11\"},{\"id\":12,\"name\":\"C12\"},{\"id\":13,\"name\":\"C13\"},{\"id\":14,\"name\":\"C14\"},{\"id\":15,\"name\":\"C15\"},{\"id\":16,\"name\":\"C16\"},{\"id\":17,\"name\":\"C17\"},{\"id\":18,\"name\":\"C18\"},{\"id\":19,\"name\":\"C19\"},{\"id\":20,\"name\":\"C20\"}]}" + }, + { + "name": "column_id_0", + "error": "column" + }, + { + "name": "column_id_256", + "error": "column" + }, + { + "name": "column_id_fraction", + "error": "column" + }, + { + "name": "column_id_repeated", + "error": "column" + }, + { + "name": "column_name_repeated_case", + "error": "column" + }, + { + "name": "column_name_quote", + "error": "column" + }, + { + "name": "column_name_leading_space", + "error": "column" + }, + { + "name": "column_name_nbsp_end", + "error": "column" + }, + { + "name": "column_name_control", + "error": "column" + }, + { + "name": "column_name_64", + "error": "column" + }, + { + "name": "column_name_empty", + "error": "column" + }, + { + "name": "column_color", + "error": "column" + }, + { + "name": "column_color_null", + "error": "column" + }, + { + "name": "column_wip_0", + "error": "column" + }, + { + "name": "def_missing_column", + "error": "def" + }, + { + "name": "done_missing_column", + "error": "done" + }, + { + "name": "done_string", + "error": "done" + }, + { + "name": "sources_6", + "error": "sources" + }, + { + "name": "source_kind", + "error": "source" + }, + { + "name": "source_repo_not_id", + "error": "source" + }, + { + "name": "source_query_513", + "error": "source" + }, + { + "name": "fields_13", + "error": "fields" + }, + { + "name": "field_reserved_status", + "error": "field" + }, + { + "name": "field_reserved_labels", + "error": "field" + }, + { + "name": "field_name_colon", + "error": "field" + }, + { + "name": "field_name_dash", + "error": "field" + }, + { + "name": "field_type", + "error": "field" + }, + { + "name": "field_options_on_num", + "error": "field" + }, + { + "name": "field_sel_without_options", + "error": "field" + }, + { + "name": "field_start_on_date", + "error": "field" + }, + { + "name": "field_repeated_name", + "error": "field" + }, + { + "name": "options_31", + "error": "options" + }, + { + "name": "options_repeated", + "error": "options" + }, + { + "name": "options_0_ok", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"Done\"}],\"fields\":[{\"id\":1,\"name\":\"X\",\"type\":\"sel\",\"options\":[]}]}" + }, + { + "name": "iter_no_start", + "error": "field" + }, + { + "name": "iter_days_91", + "error": "field" + }, + { + "name": "iter_start_feb_30", + "error": "field" + }, + { + "name": "views_9", + "error": "views" + }, + { + "name": "view_layout", + "error": "view" + }, + { + "name": "view_board_group_assignee", + "error": "view" + }, + { + "name": "view_lane_is_group", + "error": "view" + }, + { + "name": "view_lane_status", + "error": "view" + }, + { + "name": "view_group_num_field", + "error": "view" + }, + { + "name": "view_sort_unknown", + "error": "view" + }, + { + "name": "view_sort_missing_field", + "error": "view" + }, + { + "name": "view_cols_repeated", + "error": "view" + }, + { + "name": "view_cols_f01", + "error": "view" + }, + { + "name": "view_date_num_field", + "error": "view" + }, + { + "name": "view_repeated_name", + "error": "view" + }, + { + "name": "arch_3651", + "error": "arch" + }, + { + "name": "desc_type", + "error": "desc" + }, + { + "name": "desc_1025", + "error": "desc" + }, + { + "name": "view_date_same_field", + "error": "view" + } + ] +} diff --git a/forge-contracts/vectors/board_spec__parse_serde_refusals.json b/forge-contracts/vectors/board_spec__parse_serde_refusals.json new file mode 100644 index 000000000..29b278e3c --- /dev/null +++ b/forge-contracts/vectors/board_spec__parse_serde_refusals.json @@ -0,0 +1,85 @@ +{ + "name": "parse_serde_refusals", + "description": "What forge-core's JSON reader (serde_json) refuses, the web refuses too, anywhere in the spec (an unknown key included): an unpaired surrogate escape, a number out of range (JavaScript would read 1e400 as Infinity), nesting past 127 levels. 127 levels read; an empty desc is none.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "parse", + "cases": [ + { + "name": "lone_surrogate_unknown_key", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}],\"x\":\"\\ud800\"}" + }, + { + "name": "lone_trailing_surrogate_name", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"a\\udc00\"}]}" + }, + { + "name": "lone_surrogate_desc", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}],\"desc\":\"\\ud800x\"}" + }, + { + "name": "surrogate_pair_ok", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}],\"desc\":\"\\ud83d\\ude80\"}" + }, + { + "name": "number_out_of_range", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}],\"x\":1e400}" + }, + { + "name": "arch_out_of_range", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}],\"arch\":-1e400}" + }, + { + "name": "depth_127", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}],\"x\":[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]}" + }, + { + "name": "depth_128", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}],\"x\":[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]}" + }, + { + "name": "empty_desc", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}],\"desc\":\"\"}" + } + ] + }, + "expected": [ + { + "name": "lone_surrogate_unknown_key", + "error": "json" + }, + { + "name": "lone_trailing_surrogate_name", + "error": "json" + }, + { + "name": "lone_surrogate_desc", + "error": "json" + }, + { + "name": "surrogate_pair_ok", + "json": "{\"v\":1,\"desc\":\"🚀\",\"columns\":[{\"id\":1,\"name\":\"A\"}]}" + }, + { + "name": "number_out_of_range", + "error": "json" + }, + { + "name": "arch_out_of_range", + "error": "json" + }, + { + "name": "depth_127", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}]}" + }, + { + "name": "depth_128", + "error": "json" + }, + { + "name": "empty_desc", + "json": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"A\"}]}" + } + ] +} diff --git a/forge-contracts/vectors/board_spec__values_dropped.json b/forge-contracts/vectors/board_spec__values_dropped.json new file mode 100644 index 000000000..847ee0ba9 --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_dropped.json @@ -0,0 +1,125 @@ +{ + "name": "values_dropped", + "description": "A card's field values keep only fields the spec has, with a value of the field's type: an unknown field or option, a wrong type, a non-canonical key (\"01\"), a number past ±1e15 or below 1e-6, a bad date, a negative or fractional iteration, empty or 201-character text are dropped; -0 reads as 0; ids ascending.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Summary", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "f": "{\"1\":7,\"2\":-0,\"3\":1.5,\"4\":\"2026-02-30\",\"5\":\"\",\"6\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"9\":1,\"01\":2}" + }, + "expected": { + "values": { + "2": 0 + }, + "json": "{\"2\":0}" + } +} diff --git a/forge-contracts/vectors/board_spec__values_escapes.json b/forge-contracts/vectors/board_spec__values_escapes.json new file mode 100644 index 000000000..6ba60323d --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_escapes.json @@ -0,0 +1,125 @@ +{ + "name": "values_escapes", + "description": "Text with quotes, backslashes, a newline and a control character round-trips with the same JSON escapes in both clients.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Summary", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "f": "{\"5\":\"a\\\"b\\\\c\\nd\\u0001e
\"}" + }, + "expected": { + "values": { + "5": "a\"b\\c\nd\u0001e
" + }, + "json": "{\"5\":\"a\\\"b\\\\c\\nd\\u0001e
\"}" + } +} diff --git a/forge-contracts/vectors/board_spec__values_exact_numbers.json b/forge-contracts/vectors/board_spec__values_exact_numbers.json new file mode 100644 index 000000000..0de3ba7d5 --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_exact_numbers.json @@ -0,0 +1,50 @@ +{ + "name": "values_exact_numbers", + "description": "Numbers read exactly (forge-core reads JSON with float_roundtrip, as JSON.parse does) and are written with JavaScript's shortest digits, an exact tie to even: 71292843364840.125 is written 71292843364840.12.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "C1" + } + ], + "fields": [ + { + "id": 1, + "name": "N1", + "type": "num" + }, + { + "id": 2, + "name": "N2", + "type": "num" + }, + { + "id": 3, + "name": "N3", + "type": "num" + }, + { + "id": 4, + "name": "N4", + "type": "num" + } + ] + }, + "f": "{\"1\":989238.7673074775,\"2\":123456789012345.67,\"3\":71292843364840.125,\"4\":1e-400}" + }, + "expected": { + "values": { + "1": 989238.7673074775, + "2": 123456789012345.67, + "3": 71292843364840.12, + "4": 0 + }, + "json": "{\"1\":989238.7673074775,\"2\":123456789012345.67,\"3\":71292843364840.12,\"4\":0}" + } +} diff --git a/forge-contracts/vectors/board_spec__values_kept.json b/forge-contracts/vectors/board_spec__values_kept.json new file mode 100644 index 000000000..f890745dc --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_kept.json @@ -0,0 +1,130 @@ +{ + "name": "values_kept", + "description": "Valid values of every type survive (text up to 200 characters), and serialize canonically: ids ascending, numbers as JavaScript writes them.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Summary", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "f": "{\"6\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"5\":\"Ship it\",\"4\":\"2026-11-01\",\"3\":2,\"2\":2.5,\"1\":3}" + }, + "expected": { + "values": { + "1": 3, + "2": 2.5, + "3": 2, + "4": "2026-11-01", + "5": "Ship it", + "6": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + }, + "json": "{\"1\":3,\"2\":2.5,\"3\":2,\"4\":\"2026-11-01\",\"5\":\"Ship it\",\"6\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}" + } +} diff --git a/forge-contracts/vectors/board_spec__values_lone_surrogate.json b/forge-contracts/vectors/board_spec__values_lone_surrogate.json new file mode 100644 index 000000000..e72a0e3cf --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_lone_surrogate.json @@ -0,0 +1,123 @@ +{ + "name": "values_lone_surrogate", + "description": "An unpaired surrogate anywhere in f: no values.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Summary", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "f": "{\"1\":1,\"5\":\"a\\udc00\"}" + }, + "expected": { + "values": {}, + "json": "{}" + } +} diff --git a/forge-contracts/vectors/board_spec__values_not_json.json b/forge-contracts/vectors/board_spec__values_not_json.json new file mode 100644 index 000000000..9dc699192 --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_not_json.json @@ -0,0 +1,123 @@ +{ + "name": "values_not_json", + "description": "f that is not JSON reads as no values.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Summary", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "f": "{\"1\":" + }, + "expected": { + "values": {}, + "json": "{}" + } +} diff --git a/forge-contracts/vectors/board_spec__values_not_object.json b/forge-contracts/vectors/board_spec__values_not_object.json new file mode 100644 index 000000000..b6ad171f4 --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_not_object.json @@ -0,0 +1,123 @@ +{ + "name": "values_not_object", + "description": "f that is not JSON, or not an object, reads as no values.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Summary", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "f": "[1,2]" + }, + "expected": { + "values": {}, + "json": "{}" + } +} diff --git a/forge-contracts/vectors/board_spec__values_null.json b/forge-contracts/vectors/board_spec__values_null.json new file mode 100644 index 000000000..2a1878ce1 --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_null.json @@ -0,0 +1,123 @@ +{ + "name": "values_null", + "description": "A card without f has no values.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Summary", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "f": null + }, + "expected": { + "values": {}, + "json": "{}" + } +} diff --git a/forge-contracts/vectors/board_spec__values_numbers.json b/forge-contracts/vectors/board_spec__values_numbers.json new file mode 100644 index 000000000..2c16dbaa4 --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_numbers.json @@ -0,0 +1,60 @@ +{ + "name": "values_numbers", + "description": "Number fields: 1e15 and 1.5e-6 are kept (written without an exponent), 1e16 and 1e-7 dropped.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "C1" + } + ], + "fields": [ + { + "id": 1, + "name": "N1", + "type": "num" + }, + { + "id": 2, + "name": "N2", + "type": "num" + }, + { + "id": 3, + "name": "N3", + "type": "num" + }, + { + "id": 4, + "name": "N4", + "type": "num" + }, + { + "id": 5, + "name": "N5", + "type": "num" + }, + { + "id": 6, + "name": "N6", + "type": "num" + } + ] + }, + "f": "{\"1\":1e15,\"2\":1.5e-6,\"3\":1e16,\"4\":1e-7,\"5\":-123456.789,\"6\":0.1}" + }, + "expected": { + "values": { + "1": 1000000000000000, + "2": 0.0000015, + "5": -123456.789, + "6": 0.1 + }, + "json": "{\"1\":1000000000000000,\"2\":0.0000015,\"5\":-123456.789,\"6\":0.1}" + } +} diff --git a/forge-contracts/vectors/board_spec__values_overflow.json b/forge-contracts/vectors/board_spec__values_overflow.json new file mode 100644 index 000000000..fbfbd20ea --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_overflow.json @@ -0,0 +1,62 @@ +{ + "name": "values_overflow", + "description": "Six 200-character text values of a two-byte letter are 2400+ bytes: they read, but writing them is refused (size, over 2048 bytes).", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "C1" + } + ], + "fields": [ + { + "id": 1, + "name": "T1", + "type": "text" + }, + { + "id": 2, + "name": "T2", + "type": "text" + }, + { + "id": 3, + "name": "T3", + "type": "text" + }, + { + "id": 4, + "name": "T4", + "type": "text" + }, + { + "id": 5, + "name": "T5", + "type": "text" + }, + { + "id": 6, + "name": "T6", + "type": "text" + } + ] + }, + "f": "{\"1\":\"éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé\",\"2\":\"éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé\",\"3\":\"éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé\",\"4\":\"éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé\",\"5\":\"éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé\",\"6\":\"éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé\"}" + }, + "expected": { + "values": { + "1": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé", + "2": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé", + "3": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé", + "4": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé", + "5": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé", + "6": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + }, + "error": "size" + } +} diff --git a/forge-contracts/vectors/board_spec__values_serde_refusals.json b/forge-contracts/vectors/board_spec__values_serde_refusals.json new file mode 100644 index 000000000..df0421e07 --- /dev/null +++ b/forge-contracts/vectors/board_spec__values_serde_refusals.json @@ -0,0 +1,123 @@ +{ + "name": "values_serde_refusals", + "description": "Field values forge-core's JSON reader would refuse (a number out of range, an unpaired surrogate) read as none in both clients.", + "case": "board_spec", + "rules": "v2", + "input": { + "op": "values", + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + }, + { + "id": 6, + "name": "Summary", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "f": "{\"1\":1,\"2\":1e400}" + }, + "expected": { + "values": {}, + "json": "{}" + } +} diff --git a/forge-contracts/vectors/board_view__group_assignee.json b/forge-contracts/vectors/board_view__group_assignee.json new file mode 100644 index 000000000..bf6951942 --- /dev/null +++ b/forge-contracts/vectors/board_view__group_assignee.json @@ -0,0 +1,298 @@ +{ + "name": "group_assignee", + "description": "Grouped by assignee: an item with two assignees is in both groups; no assignee first; ids by code point.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "group", + "by": "assignee" + }, + "expected": [ + { + "key": null, + "items": [ + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ] + }, + { + "key": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3" + ] + }, + { + "key": "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "items": [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn" + ] + } + ] +} diff --git a/forge-contracts/vectors/board_view__group_iteration.json b/forge-contracts/vectors/board_view__group_iteration.json new file mode 100644 index 000000000..b22b9fac8 --- /dev/null +++ b/forge-contracts/vectors/board_view__group_iteration.json @@ -0,0 +1,298 @@ +{ + "name": "group_iteration", + "description": "Grouped by an iteration field: no value first, then the iterations items name and the current one (index 1), ascending.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "-iteration:@current", + "op": "group", + "by": "f3" + }, + "expected": [ + { + "key": null, + "items": [ + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ] + }, + { + "key": 0, + "items": [ + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp" + ] + }, + { + "key": 1, + "items": [] + }, + { + "key": 2, + "items": [ + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ" + ] + } + ] +} diff --git a/forge-contracts/vectors/board_view__group_label.json b/forge-contracts/vectors/board_view__group_label.json new file mode 100644 index 000000000..720598c85 --- /dev/null +++ b/forge-contracts/vectors/board_view__group_label.json @@ -0,0 +1,298 @@ +{ + "name": "group_label", + "description": "Grouped by label: each of an item's labels, by code point.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "group", + "by": "label" + }, + "expected": [ + { + "key": null, + "items": [ + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp" + ] + }, + { + "key": "bug", + "items": [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3" + ] + }, + { + "key": "ui", + "items": [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ] + } + ] +} diff --git a/forge-contracts/vectors/board_view__group_milestone.json b/forge-contracts/vectors/board_view__group_milestone.json new file mode 100644 index 000000000..49e07737d --- /dev/null +++ b/forge-contracts/vectors/board_view__group_milestone.json @@ -0,0 +1,297 @@ +{ + "name": "group_milestone", + "description": "Grouped by milestone: none first, then titles by code point.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "group", + "by": "milestone" + }, + "expected": [ + { + "key": null, + "items": [ + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ] + }, + { + "key": "v1", + "items": [ + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3" + ] + }, + { + "key": "v2", + "items": [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn" + ] + } + ] +} diff --git a/forge-contracts/vectors/board_view__group_repo.json b/forge-contracts/vectors/board_view__group_repo.json new file mode 100644 index 000000000..5cc488cab --- /dev/null +++ b/forge-contracts/vectors/board_view__group_repo.json @@ -0,0 +1,292 @@ +{ + "name": "group_repo", + "description": "Grouped by repository (by id).", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "group", + "by": "repo" + }, + "expected": [ + { + "key": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "items": [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ] + }, + { + "key": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "items": [ + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ" + ] + } + ] +} diff --git a/forge-contracts/vectors/board_view__group_select.json b/forge-contracts/vectors/board_view__group_select.json new file mode 100644 index 000000000..607ebce9f --- /dev/null +++ b/forge-contracts/vectors/board_view__group_select.json @@ -0,0 +1,306 @@ +{ + "name": "group_select", + "description": "Grouped by a select field: \"No Priority\" (null) first while it holds an item, then every option in order.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "group", + "by": "f1" + }, + "expected": [ + { + "key": null, + "items": [ + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ] + }, + { + "key": 1, + "items": [ + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3" + ] + }, + { + "key": 2, + "items": [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn" + ] + }, + { + "key": 3, + "items": [] + }, + { + "key": 4, + "items": [ + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ" + ] + } + ] +} diff --git a/forge-contracts/vectors/board_view__group_status.json b/forge-contracts/vectors/board_view__group_status.json new file mode 100644 index 000000000..e6eef67b0 --- /dev/null +++ b/forge-contracts/vectors/board_view__group_status.json @@ -0,0 +1,301 @@ +{ + "name": "group_status", + "description": "Grouped by status: every column in order (empty ones too), items in input order; No status only while it holds an item (default Todo here, so none).", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "group", + "by": "status" + }, + "expected": [ + { + "key": 1, + "items": [ + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ] + }, + { + "key": 2, + "items": [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3" + ] + }, + { + "key": 3, + "items": [ + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp" + ] + }, + { + "key": 4, + "items": [] + } + ] +} diff --git a/forge-contracts/vectors/board_view__group_unknown.json b/forge-contracts/vectors/board_view__group_unknown.json new file mode 100644 index 000000000..876ea8843 --- /dev/null +++ b/forge-contracts/vectors/board_view__group_unknown.json @@ -0,0 +1,287 @@ +{ + "name": "group_unknown", + "description": "A key that does not group (a number field) is one group of everything.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "group", + "by": "f2" + }, + "expected": [ + { + "key": null, + "items": [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ] + } + ] +} diff --git a/forge-contracts/vectors/board_view__progress.json b/forge-contracts/vectors/board_view__progress.json new file mode 100644 index 000000000..c081cd8b6 --- /dev/null +++ b/forge-contracts/vectors/board_view__progress.json @@ -0,0 +1,282 @@ +{ + "name": "progress", + "description": "Iteration progress (index 1): done is in the Done column or closed/merged; points from Estimate.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "progress", + "field": 3, + "k": 1, + "points": 2 + }, + "expected": { + "total": 3, + "done": 1, + "points": 9, + "donePoints": 1 + } +} diff --git a/forge-contracts/vectors/board_view__progress_no_points.json b/forge-contracts/vectors/board_view__progress_no_points.json new file mode 100644 index 000000000..ad01e5c29 --- /dev/null +++ b/forge-contracts/vectors/board_view__progress_no_points.json @@ -0,0 +1,282 @@ +{ + "name": "progress_no_points", + "description": "Iteration progress without a points field: counts only.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "progress", + "field": 3, + "k": 0, + "points": null + }, + "expected": { + "total": 1, + "done": 1, + "points": null, + "donePoints": null + } +} diff --git a/forge-contracts/vectors/board_view__sort.json b/forge-contracts/vectors/board_view__sort.json new file mode 100644 index 000000000..0a2f40476 --- /dev/null +++ b/forge-contracts/vectors/board_view__sort.json @@ -0,0 +1,394 @@ +{ + "name": "sort", + "description": "Sorts: rank (the default, and -rank), title (any case), -estimate (missing last), priority by option order, status by column order, number, created, -created; ties by (rank, id).", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "sort", + "sorts": [ + null, + "rank", + "-rank", + "title", + "-f2", + "f2", + "f1", + "-f1", + "status", + "number", + "-created", + "repo", + "milestone" + ] + }, + "expected": [ + [ + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ], + [ + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ], + [ + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3" + ], + [ + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ], + [ + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ], + [ + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ], + [ + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ], + [ + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ], + [ + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp" + ], + [ + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ], + [ + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn" + ], + [ + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ" + ], + [ + "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5" + ] + ] +} diff --git a/forge-contracts/vectors/board_view__totals.json b/forge-contracts/vectors/board_view__totals.json new file mode 100644 index 000000000..b8dcc5387 --- /dev/null +++ b/forge-contracts/vectors/board_view__totals.json @@ -0,0 +1,304 @@ +{ + "name": "totals", + "description": "Column totals: count and the sum of the view's first number field (Table: Estimate), the WIP limit and over it (In progress: 3 items, limit 1).", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "", + "op": "totals", + "view": 2 + }, + "expected": [ + { + "id": 1, + "count": 2, + "sum": 2.5, + "wip": null, + "over": false + }, + { + "id": 2, + "count": 2, + "sum": 8, + "wip": 1, + "over": true + }, + { + "id": 3, + "count": 2, + "sum": 9, + "wip": null, + "over": false + }, + { + "id": 4, + "count": 0, + "sum": 0, + "wip": null, + "over": false + } + ] +} diff --git a/forge-contracts/vectors/board_view__totals_default_view.json b/forge-contracts/vectors/board_view__totals_default_view.json new file mode 100644 index 000000000..164dab39b --- /dev/null +++ b/forge-contracts/vectors/board_view__totals_default_view.json @@ -0,0 +1,304 @@ +{ + "name": "totals_default_view", + "description": "With no view the spec's first number field is summed.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "label:bug", + "op": "totals", + "view": null + }, + "expected": [ + { + "id": 1, + "count": 0, + "sum": 0, + "wip": null, + "over": false + }, + { + "id": 2, + "count": 2, + "sum": 8, + "wip": 1, + "over": true + }, + { + "id": 3, + "count": 0, + "sum": 0, + "wip": null, + "over": false + }, + { + "id": 4, + "count": 0, + "sum": 0, + "wip": null, + "over": false + } + ] +} diff --git a/forge-contracts/vectors/board_view__totals_no_number_field.json b/forge-contracts/vectors/board_view__totals_no_number_field.json new file mode 100644 index 000000000..d6a719eb8 --- /dev/null +++ b/forge-contracts/vectors/board_view__totals_no_number_field.json @@ -0,0 +1,304 @@ +{ + "name": "totals_no_number_field", + "description": "A view whose fields have no number field sums nothing (null); no view sums the spec's first number field.", + "case": "board_view", + "rules": "v2", + "input": { + "spec": { + "v": 1, + "columns": [ + { + "id": 1, + "name": "Todo" + }, + { + "id": 2, + "name": "In progress", + "wip": 1 + }, + { + "id": 3, + "name": "Done" + }, + { + "id": 4, + "name": "Verified" + } + ], + "def": 1, + "done": 3, + "sources": [ + { + "k": "a" + } + ], + "fields": [ + { + "id": 1, + "name": "Priority", + "type": "sel", + "options": [ + { + "id": 1, + "name": "P0" + }, + { + "id": 2, + "name": "P1" + }, + { + "id": 3, + "name": "P2" + }, + { + "id": 4, + "name": "P3" + } + ] + }, + { + "id": 2, + "name": "Estimate", + "type": "num" + }, + { + "id": 3, + "name": "Iteration", + "type": "iter", + "start": "2026-10-12", + "days": 14 + }, + { + "id": 4, + "name": "Target", + "type": "date" + }, + { + "id": 5, + "name": "Notes", + "type": "text" + } + ], + "views": [ + { + "id": 1, + "name": "Board", + "layout": "board" + }, + { + "id": 2, + "name": "Table", + "layout": "table", + "cols": [ + "title", + "status", + "f1", + "f2" + ] + }, + { + "id": 3, + "name": "Plain", + "layout": "table", + "cols": [ + "title", + "f5" + ] + } + ], + "arch": 14 + }, + "home": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "now": 1793102400000, + "me": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb", + "items": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "number": 101, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791176400000, + "closedAt": null, + "title": "banana", + "labels": [ + "ui", + "bug" + ], + "assignees": [ + "Fss2iV8Cv3jH4UPUtYcszb2Bc3bsTqXPjZM8D7tKmg9r", + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v2", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "number": 102, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791180000000, + "closedAt": null, + "title": "Apple", + "labels": [ + "bug" + ], + "assignees": [ + "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + ], + "milestone": "v1", + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "number": 103, + "repoId": "EZZTFGPPNXqHudAJPvw2YiYjtJgqZwbxXiSkBHjE43Nx", + "repo": "bob/lib", + "kind": "issue", + "state": "open", + "createdAt": 1791183600000, + "closedAt": null, + "title": "cherry", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "number": 104, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "closed", + "createdAt": 1791187200000, + "closedAt": 1793016000000, + "title": "date", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "number": 105, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "pr", + "state": "open", + "createdAt": 1791190800000, + "closedAt": null, + "title": "elder", + "labels": [], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + }, + { + "id": "8CHyD97xDGLH2PDYW7cDaR8sjsaR8mCNBVfbjoN4Ner5", + "number": 106, + "repoId": "EVYovg1cuLSRZwsgUgCkwLTaVSyBUhisxmaEqH7xnN3h", + "repo": "alice/forge", + "kind": "issue", + "state": "open", + "createdAt": 1791194400000, + "closedAt": null, + "title": "fig", + "labels": [ + "ui" + ], + "assignees": [], + "milestone": null, + "author": "ForPPtkSSrLQio6ryHtcPCw2DBtDNbeKAcUcs7H4Vzpb" + } + ], + "cards": [ + { + "id": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244801000, + "item": "7rEkcBF7sHMwKznSuqxsXWh4maz8gZnyLmK51kKk2GBn", + "col": 2, + "rank": "G", + "f": "{\"1\":2,\"2\":3,\"3\":1}", + "state": 0 + }, + { + "id": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244802000, + "item": "7vFPvmctLUkofg54q6h98tnEAShnmog3uiBaMkw1HwX3", + "col": 2, + "rank": "F", + "f": "{\"1\":1,\"2\":5,\"3\":1}", + "state": 0 + }, + { + "id": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244803000, + "item": "7zG3FMzeog9g1MMgkMRQkGsPZJRSs3Z8Uf45hmYGZcrJ", + "col": 1, + "rank": null, + "f": "{\"2\":2.5,\"3\":2}", + "state": 0 + }, + { + "id": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244804000, + "item": "84GgZxNRGsYYM2eJfc9gMexYxA96xHSD3bvb3n9XqJBZ", + "col": 2, + "rank": null, + "f": "{\"1\":4,\"2\":1,\"3\":1}", + "state": 0 + }, + { + "id": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "ownerId": "FBfF8bmHbJP6xijsfDVT39MCS29kP6XfeEHJHPCbV9NH", + "updatedAt": 1791244805000, + "item": "88HKtYkBk4wQghvvarswy33iM1rm3XKHcYo6Pnko6yWp", + "col": 3, + "rank": null, + "f": "{\"2\":8,\"3\":0}", + "state": 0 + } + ], + "q": "is:open", + "op": "totals", + "view": 3 + }, + "expected": [ + { + "id": 1, + "count": 2, + "sum": null, + "wip": null, + "over": false + }, + { + "id": 2, + "count": 2, + "sum": null, + "wip": 1, + "over": true + }, + { + "id": 3, + "count": 1, + "sum": null, + "wip": null, + "over": false + }, + { + "id": 4, + "count": 0, + "sum": null, + "wip": null, + "over": false + } + ] +} diff --git a/forge-web/lib/rules/boards.conformance.test.ts b/forge-web/lib/rules/boards.conformance.test.ts new file mode 100644 index 000000000..6bee1efa0 --- /dev/null +++ b/forge-web/lib/rules/boards.conformance.test.ts @@ -0,0 +1,172 @@ +/** + * THE PARITY PROOF for boards (`docs/design/boards.md`): every `board_*__*.json` vector in + * `forge-contracts/vectors/` run against `./boards`. forge-core + * `rules::boards::tests::board_vectors` runs the same files with the same input and output + * shapes, so `dg board` and the web agree on specs, ranks, placement, queries, iterations and + * the view helpers. + */ + +import { readFileSync, readdirSync } from 'node:fs' +import { resolve } from 'node:path' +import { describe, expect, it } from 'vitest' + +import { + bottomRank, + columnTotals, + defaultSpec, + foldBoard, + groupRows, + implicitRankOf, + iterationAt, + iterationProgress, + iterationRange, + matchesBoardQuery, + newestBoards, + parseBoardQuery, + parseFieldValues, + parseSourceQuery, + parseSpec, + rankBetween, + rerank, + serializeFieldValues, + serializeSpec, + sortRows, + sumFieldOf, + topRank, + type BoardDoc, + type BoardFold, + type BoardItem, + type BoardRow, + type BoardSpec, + type CardDoc, +} from './boards' + +type Json = null | boolean | number | string | Json[] | { [k: string]: Json } +type Obj = { readonly [k: string]: Json } + +interface Vector { + readonly name: string + readonly case: string + readonly rules?: string + readonly input: Obj + readonly expected: Json +} + +const VECTORS_DIR = resolve(process.cwd(), '..', 'forge-contracts', 'vectors') +const FILES = readdirSync(VECTORS_DIR) + .filter((f) => f.startsWith('board_') && f.endsWith('.json')) + .sort() + +const arr = (j: Json | undefined): Json[] => j as Json[] + +function specOf(j: Json | undefined): BoardSpec { + const r = parseSpec(JSON.stringify(j)) + if ('error' in r) throw new Error(`vector spec refused: ${r.error}`) + return r.spec +} + +function canonical(spec: BoardSpec): string { + const r = serializeSpec(spec) + if ('error' in r) throw new Error(`spec did not serialize: ${r.error}`) + return r.json +} + +function foldOf(i: Obj): { spec: BoardSpec; items: BoardItem[]; fold: BoardFold } { + const spec = specOf(i.spec) + const items = i.items as unknown as BoardItem[] + const fold = foldBoard({ spec, home: i.home as string, items, cards: i.cards as unknown as CardDoc[], now: i.now as number }) + return { spec, items, fold } +} + +/** The rows a query keeps, in input order. */ +function rowsOf(i: Obj, q: string, spec: BoardSpec, items: readonly BoardItem[], fold: BoardFold): BoardRow[] { + const query = parseBoardQuery(q, spec) + const ctx = { me: (i.me as string | null | undefined) ?? null, now: i.now as number } + return items.map((item, n) => ({ item, placement: fold.items[n]! })).filter((r) => matchesBoardQuery(r.item, r.placement, spec, query, ctx)) +} + +/** JSON as both clients compare it (`undefined` members dropped). */ +const plain = (v: unknown): Json => JSON.parse(JSON.stringify(v)) as Json + +function run(v: Vector): Json { + const i = v.input + switch (`${v.case}/${i.op as string}`) { + case 'board_spec/parse': + return arr(i.cases).map((c): Json => { + const { name, json } = c as Obj + const r = parseSpec(json as string) + return 'error' in r ? { name: name as string, error: r.error } : { name: name as string, json: canonical(r.spec) } + }) + case 'board_spec/default': + return { json: canonical(defaultSpec(i.home as string, i.now as number)) } + case 'board_spec/values': { + const spec = specOf(i.spec) + const values = parseFieldValues(i.f as string | null, spec) + const out = serializeFieldValues(values, spec) + return plain({ values, ...out }) + } + case 'board_rank/between': + return plain(arr(i.pairs).map((p) => rankBetween((p as Json[])[0] as string | null, (p as Json[])[1] as string | null))) + case 'board_rank/top': + return plain(arr(i.firsts).map((f) => topRank(f as string | null))) + case 'board_rank/bottom': + return plain(arr(i.lasts).map((l) => bottomRank(l as string | null))) + case 'board_rank/implicit': + return arr(i.items).map((x) => implicitRankOf((x as Obj).createdAt as number, (x as Obj).id as string)) + case 'board_rank/rerank': + return plain(rerank(i.n as number)) + case 'board_fold/fold': + return plain(foldOf(i).fold) + case 'board_fold/boards': + return newestBoards(i.docs as unknown as BoardDoc[], i.withDeleted === true).map((d) => ({ key: d.key, id: d.id, state: d.state })) + case 'board_query/parse': + return plain(parseBoardQuery(i.text as string, specOf(i.spec))) + case 'board_query/source': + return plain(parseSourceQuery(i.text as string, specOf(i.spec))) + case 'board_query/match': { + const { spec, items, fold } = foldOf(i) + return arr(i.texts).map((t) => rowsOf(i, t as string, spec, items, fold).map((r) => r.item.id)) + } + case 'board_iteration/at': + case 'board_iteration/range': { + const field = specOf(i.spec).fields.find((f) => f.id === i.field)! + return i.op === 'at' ? arr(i.dates).map((d) => iterationAt(field, d as number)) : plain(arr(i.ks).map((k) => iterationRange(field, k as number))) + } + default: { + expect(v.case).toBe('board_view') + const { spec, items, fold } = foldOf(i) + const rows = rowsOf(i, (i.q as string | undefined) ?? '', spec, items, fold) + switch (i.op) { + case 'group': + return plain(groupRows(rows, i.by as string, spec, i.now as number)) + case 'sort': + return arr(i.sorts).map((s) => sortRows(rows, (s as string | null) ?? undefined, spec).map((r) => r.item.id)) + case 'totals': { + const view = spec.views.find((w) => w.id === i.view) ?? null + return plain(columnTotals(rows, spec, sumFieldOf(spec, view))) + } + case 'progress': + return plain(iterationProgress(rows, spec, i.field as number, i.k as number, (i.points as number | null | undefined) ?? null)) + default: + throw new Error(`unknown board vector ${v.case} op ${String(i.op)}`) + } + } + } +} + +describe('board vectors', () => { + const vectors = FILES.map((f) => ({ file: f, v: JSON.parse(readFileSync(resolve(VECTORS_DIR, f), 'utf8')) as Vector })) + + it('loads every family', () => { + expect(vectors.length).toBeGreaterThanOrEqual(30) + const cases = new Set(vectors.map(({ v }) => v.case)) + for (const c of ['board_rank', 'board_spec', 'board_fold', 'board_query', 'board_iteration', 'board_view']) expect(cases.has(c), c).toBe(true) + for (const { file, v } of vectors) expect(file.startsWith(`${v.case}__`), file).toBe(true) + }) + + for (const { file, v } of vectors) { + it(file, () => { + expect(run(v)).toEqual(v.expected) + }) + } +}) diff --git a/forge-web/lib/rules/boards.test.ts b/forge-web/lib/rules/boards.test.ts new file mode 100644 index 000000000..8b8644aa0 --- /dev/null +++ b/forge-web/lib/rules/boards.test.ts @@ -0,0 +1,135 @@ +/** + * Properties of the board rules the vectors cannot list case by case (forge-core + * `rules::boards::tests` checks the same, with the same PRNG): `rankBetween` is strictly + * between for every pair, specs round-trip, dates and Mondays. + */ + +import { describe, expect, it } from 'vitest' + +import { compareStrings } from './oid' +import { RANK_DIGITS, RANK_MAX, RERANK_MAX, dateDays, dateOf, defaultSpec, isExplicitRank, mondayOf, parseSpec, rankBetween, rerank, serializeSpec } from './boards' + +const DAY = 86_400_000 + +/** splitmix64, the same as the Rust test's `Rng`. */ +class Rng { + private s: bigint + constructor(seed: bigint) { + this.s = seed + } + next(): bigint { + const M = (1n << 64n) - 1n + this.s = (this.s + 0x9e3779b97f4a7c15n) & M + let z = this.s + z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & M + z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & M + return z ^ (z >> 31n) + } + below(n: number): number { + return Number(this.next() % BigInt(n)) + } + /** 0-`max` rank digits, biased to `0`, `1`, `y`, `z` (the edges). */ + digits(max: number): string { + const len = this.below(max + 1) + let out = '' + for (let i = 0; i < len; i++) out += this.below(4) === 0 ? '01yz'[this.below(4)] : RANK_DIGITS[this.below(62)] + return out + } +} + +/** Whether nothing lies strictly between `a` < `b`: `b` is `a` and only `0`s. */ +const nothingBetween = (a: string, b: string) => b.length > a.length && b.startsWith(a) && /^0+$/.test(b.slice(a.length)) + +function checkBetween(a: string, b: string): void { + const r = rankBetween(a, b) + if ('rank' in r) { + expect(compareStrings(a, r.rank), `${a} < ${r.rank}`).toBeLessThan(0) + if (b !== '') expect(compareStrings(r.rank, b), `${r.rank} < ${b}`).toBeLessThan(0) + expect(isExplicitRank(r.rank)).toBe(true) + expect(r.rank.length).toBeLessThanOrEqual(Math.max(a.length, b.length) + 1) + } else { + expect(r.error, `${a} ${b}`).toBe('re-rank') + expect(nothingBetween(a, b) || Math.max(a.length, b.length) >= RANK_MAX, `${a} ${b}`).toBe(true) + } +} + +describe('rankBetween', () => { + it('is strictly between, for every pair (prefix relations included)', () => { + const rng = new Rng(0x00b0a2d5n) + for (let n = 0; n < 20_000; n++) { + let x = rng.digits(6) + let y = rng.digits(6) + // half the pairs share a prefix, so prefix relations (V / V1 / V10) are common + if (rng.below(2) === 0) { + const p = rng.digits(4) + x = p + x + y = p + y + } + const c = compareStrings(x, y) + if (c < 0) checkBetween(x, y) + else if (c > 0) checkBetween(y, x) + else expect(rankBetween(x, y)).toEqual(x === '' ? { rank: 'V' } : { error: 're-rank' }) + checkBetween(x, '') + if (x !== '') checkBetween('', x) + } + }) + + it('handles implicit bounds ending in 0', () => { + for (const [a, b] of [['V', 'V0'], ['V1', 'V10'], ['V1', 'V100'], ['V10', 'V1000'], ['', '0'], ['', '00']]) expect(rankBetween(a!, b!)).toEqual({ error: 're-rank' }) + expect(rankBetween('V1', 'V101')).toEqual({ rank: 'V100V' }) + expect(rankBetween('V', 'V01')).toEqual({ rank: 'V00V' }) + }) + + it('runs out after a few hundred drops into one gap', () => { + let hi = 'V' + let drops = 0 + for (let r = rankBetween('', hi); 'rank' in r; r = rankBetween('', hi)) { + hi = r.rank + drops++ + } + expect(drops).toBeGreaterThanOrEqual(300) + expect(drops).toBeLessThanOrEqual(400) + }) +}) + +describe('rerank', () => { + it('spreads ranks below the pool with room between', () => { + for (const n of [0, 1, 2, 3, 30, 31, 100, 1921, 1922, 5000]) { + const r = rerank(n) + if (!('ranks' in r)) throw new Error('refused') + expect(r.ranks.length).toBe(n) + for (let i = 1; i < r.ranks.length; i++) { + expect(compareStrings(r.ranks[i - 1]!, r.ranks[i]!)).toBeLessThan(0) + expect('rank' in rankBetween(r.ranks[i - 1]!, r.ranks[i]!)).toBe(true) + } + expect(r.ranks.every((x) => isExplicitRank(x) && compareStrings(x, 'V') < 0)).toBe(true) + } + expect(rerank(RERANK_MAX + 1)).toEqual({ error: 'invalid' }) + expect(rerank(1.5)).toEqual({ error: 'invalid' }) + }) +}) + +describe('spec', () => { + it('round-trips the template within 4096 bytes', () => { + const spec = defaultSpec('4tJ7mVo5yJm4b6rKZ2SRsG6YqfJHFDLC2kUwD3nAhZ7b', Date.UTC(2026, 9, 30)) + const out = serializeSpec(spec) + if (!('json' in out)) throw new Error(out.error) + const back = parseSpec(out.json) + expect(back).toEqual({ spec }) + expect(serializeSpec(spec)).toEqual(out) + expect(new TextEncoder().encode(out.json).length).toBeLessThanOrEqual(4096) + }) +}) + +describe('dates', () => { + it('reads calendar dates and finds Mondays (UTC)', () => { + expect(dateDays('1970-01-01')).toBe(0) + expect(dateDays('2024-02-29')).toBe(19_782) + expect(dateDays('2023-02-29')).toBeNull() + expect(dateOf(19_782 * DAY)).toBe('2024-02-29') + expect(mondayOf(0)).toBe('1969-12-29') + expect(mondayOf(dateDays('2026-10-27')! * DAY + 5)).toBe('2026-10-26') + expect(mondayOf(dateDays('2026-10-26')! * DAY)).toBe('2026-10-26') + for (const d of [-719_162, -700_000, -1, 0, 59, 60, 10_000, 2_932_896]) expect(dateDays(dateOf(d * DAY))).toBe(d) + }) +}) diff --git a/forge-web/lib/rules/boards.ts b/forge-web/lib/rules/boards.ts new file mode 100644 index 000000000..2a3668ade --- /dev/null +++ b/forge-web/lib/rules/boards.ts @@ -0,0 +1,1535 @@ +/** + * Boards (`docs/design/boards.md`): the pure rules every client applies to a board's documents, + * so the web and `dg board` show the same board. The Rust half is forge-core + * `rules::boards`; the `board_*__*.json` vectors in `forge-contracts/vectors/` pin the two + * together (`./boards.conformance.test.ts` here, `rules::boards::tests::board_vectors` there). + * + * - **Spec** (§2.1–§2.3, §4, §8): the board definition a `board` document's `spec` holds, parsed + * strictly ({@link parseSpec}) and written canonically ({@link serializeSpec}); a card's field + * values ({@link parseFieldValues}, {@link serializeFieldValues}). + * - **Rank** (§2.6): base-62 fractional ranks ({@link rankBetween}, {@link implicitRank}, + * {@link topRank}, {@link bottomRank}, {@link rerank}). + * - **Fold** (§2.4): where every item shows ({@link foldBoard}), and the newest board revision + * per key ({@link newestBoards}). + * - **Query** (§4.4): {@link parseBoardQuery}, {@link matchesBoardQuery}. + * - **Iterations** (§2.2): {@link iterationAt}, {@link iterationRange}. + * - **Views** (§4.1–§4.5): {@link groupRows}, {@link sortRows}, {@link columnTotals}, + * {@link iterationProgress}. + * + * Everything is pure: no SDK, no clock (`now` is an input), no I/O. + */ + +import { base58Decode } from '../auth/base58' +import { compareStrings } from './oid' +import { searchTerms, searchTokens } from './search-terms' + +// --------------------------------------------------------------------------------------------- +// Limits (§8) and shared value shapes +// --------------------------------------------------------------------------------------------- + +/** A `board.spec` holds at most this many UTF-8 bytes (the contract's `maxBytes`). */ +export const SPEC_MAX_BYTES = 4096 +/** A `card.f` holds at most this many UTF-8 bytes. */ +export const FIELD_VALUES_MAX_BYTES = 2048 +export const MAX_COLUMNS = 20 +export const MAX_FIELDS = 12 +export const MAX_OPTIONS = 30 +export const MAX_SOURCES = 5 +export const MAX_VIEWS = 8 +/** A view lists at most this many table columns. */ +export const MAX_VIEW_COLS = 24 +/** Column, field, option and view names: 1-63 characters. */ +export const NAME_MAX = 63 +/** A board's description: at most this many characters. */ +export const DESC_MAX = 1024 +/** A source's or view's query: at most this many characters (the issue list's `Q_MAX`). */ +export const QUERY_MAX = 512 +/** A text field's value: 1-200 characters. */ +export const TEXT_VALUE_MAX = 200 +/** A column's WIP limit: 1-9999. */ +export const WIP_MAX = 9999 +/** An iteration field's length: 1-90 days. */ +export const ITER_DAYS_MAX = 90 +/** The highest iteration index a card may name. */ +export const ITER_INDEX_MAX = 65535 +/** Auto-archive after at most this many days (0 = off). */ +export const ARCH_MAX = 3650 +/** A number field's value: finite, |x| ≤ 1e15, and 0 or |x| ≥ 1e-6 (both clients print it alike). */ +export const NUM_ABS_MAX = 1e15 +export const NUM_ABS_MIN = 1e-6 +/** An explicit rank is at most 63 characters (the `card.rank` schema). */ +export const RANK_MAX = 63 +/** Ranks are re-spread for at most this many items at once. */ +export const RERANK_MAX = 1_000_000 + +const DAY_MS = 86_400_000 + +/** `s`'s length in UTF-8 bytes (what the contract's `maxBytes` counts). */ +function utf8Length(s: string): number { + return new TextEncoder().encode(s).length +} + +/** `s`'s length in code points (what the contract's `maxLength` counts). */ +function charLength(s: string): number { + let n = 0 + for (const _ of s) n++ + return n +} + +/** Whether `s` holds an unpaired surrogate (a string Rust could not hold). */ +function hasLoneSurrogate(s: string): boolean { + return /[\ud800-\udbff](?![\udc00-\udfff])|(?= 0x2000 && cp <= 0x200a) || cp === 0x2028 || cp === 0x2029 || cp === 0x202f || cp === 0x205f || cp === 0x3000 || cp === 0xfeff +} + +/** C0, DEL and C1 control characters. */ +function isControl(cp: number): boolean { + return cp < 0x20 || (cp >= 0x7f && cp <= 0x9f) +} + +/** + * A column, field, option or view name: 1-63 characters, no control character or `"` (a query + * quotes names with `"`), not starting or ending with white space. + */ +function nameOk(s: unknown): s is string { + if (typeof s !== 'string' || hasLoneSurrogate(s)) return false + const cps = [...s].map((c) => c.codePointAt(0) as number) + if (cps.length < 1 || cps.length > NAME_MAX) return false + if (cps.some((cp) => isControl(cp) || cp === 0x22)) return false + return !isSpace(cps[0] as number) && !isSpace(cps[cps.length - 1] as number) +} + +/** A string of at most `max` characters with no unpaired surrogate. */ +function textOk(s: unknown, max: number): s is string { + return typeof s === 'string' && !hasLoneSurrogate(s) && charLength(s) <= max +} + +function isInt(v: unknown, min: number, max: number): v is number { + return typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max +} + +/** The deepest nesting serde_json (forge-core's reader) reads: its recursion limit of 128 refuses the 128th level. */ +const JSON_DEPTH_MAX = 127 + +/** + * Whether forge-core's serde_json reads what `JSON.parse` read: it refuses a number out of range + * (`1e400`, which JavaScript reads as Infinity), an unpaired surrogate escape, and nesting past + * 127 levels. Refusing them here as well keeps the two clients' answers equal. + */ +function serdeReads(v: unknown, depth = 0): boolean { + if (typeof v === 'number') return Number.isFinite(v) + if (typeof v === 'string') return !hasLoneSurrogate(v) + if (typeof v !== 'object' || v === null) return true + if (depth >= JSON_DEPTH_MAX) return false + if (Array.isArray(v)) return v.every((x) => serdeReads(x, depth + 1)) + return Object.entries(v).every(([k, x]) => !hasLoneSurrogate(k) && serdeReads(x, depth + 1)) +} + +/** `JSON.parse`, or undefined when it (or forge-core's serde_json, {@link serdeReads}) would refuse the text. */ +function readJson(text: string): unknown { + let raw: unknown + try { + raw = JSON.parse(text) + } catch { + return undefined + } + return serdeReads(raw) ? raw : undefined +} + +function isObject(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v) +} + +const COLOR = /^#[0-9a-fA-F]{6}$/ +/** An identity or document id: 42-44 base58 characters (the web's `isIdentityId`). */ +const IDENTIFIER = /^[1-9A-HJ-NP-Za-km-z]{42,44}$/ +const DATE = /^(\d{4})-(\d{2})-(\d{2})$/ + +/** Days since 1970-01-01 of a proleptic Gregorian date (Hinnant's `days_from_civil`). */ +function daysFromCivil(y: number, m: number, d: number): number { + const yy = m <= 2 ? y - 1 : y + const era = Math.floor(yy / 400) + const yoe = yy - era * 400 + const doy = Math.floor((153 * (m + (m > 2 ? -3 : 9)) + 2) / 5) + d - 1 + const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy + return era * 146097 + doe - 719468 +} + +/** The date `days` after 1970-01-01, as `YYYY-MM-DD` (Hinnant's `civil_from_days`). */ +function civilFromDays(days: number): string { + const z = days + 719468 + const era = Math.floor(z / 146097) + const doe = z - era * 146097 + const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365) + const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100)) + const mp = Math.floor((5 * doy + 2) / 153) + const d = doy - Math.floor((153 * mp + 2) / 5) + 1 + const m = mp < 10 ? mp + 3 : mp - 9 + const y = yoe + era * 400 + (m <= 2 ? 1 : 0) + return `${String(y).padStart(4, '0')}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}` +} + +/** A `YYYY-MM-DD` calendar date's day number (days since 1970-01-01), or null when it is not one. */ +export function dateDays(s: unknown): number | null { + if (typeof s !== 'string') return null + const m = DATE.exec(s) + if (!m) return null + const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])] + if (y < 1 || mo < 1 || mo > 12 || d < 1) return null + const leap = (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0 + const len = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1] as number + return d <= len ? daysFromCivil(y, mo, d) : null +} + +/** The UTC date of a millisecond time, as `YYYY-MM-DD`. */ +export function dateOf(ms: number): string { + return civilFromDays(Math.floor(ms / DAY_MS)) +} + +// --------------------------------------------------------------------------------------------- +// Spec (§2.1-§2.3, §4) +// --------------------------------------------------------------------------------------------- + +/** A status column (§2.1): `id` 1-255 stable across renames; order is the array order. */ +export interface BoardColumn { + readonly id: number + readonly name: string + /** `#rrggbb`. */ + readonly color?: string + /** WIP limit (§4.5): shown and warned on, never blocking. */ + readonly wip?: number +} + +/** The custom field types (§2.2). */ +export type FieldType = 'sel' | 'num' | 'date' | 'iter' | 'text' + +/** A single-select option. */ +export interface FieldOption { + readonly id: number + readonly name: string + readonly color?: string +} + +/** + * A custom field (§2.2). `options` is present exactly for `sel`; `start` (`YYYY-MM-DD`) and + * `days` (1-90) exactly for `iter`. + */ +export interface BoardField { + readonly id: number + readonly name: string + readonly type: FieldType + readonly options?: readonly FieldOption[] + readonly start?: string + readonly days?: number +} + +/** A source's kind: issues, pull requests, or both. */ +export type SourceKind = 'i' | 'p' | 'a' + +/** + * An auto-include rule (§2.3): every item of repository `r` (absent: the home repository) of + * kind `k` that query `q` matches is on the board. A source query reads only the item itself + * ({@link parseSourceQuery}). + */ +export interface BoardSource { + readonly r?: string + readonly k: SourceKind + readonly q: string +} + +export type ViewLayout = 'board' | 'table' | 'roadmap' + +/** + * A saved view (§4). Keys name the built-in fields or a custom field as `f`: + * - `group` (columns of the board layout, sections of the table): `status` (the default), + * `assignee`, `label`, `milestone`, `repo` or a `sel` / `iter` field; the board layout takes + * only `status` and `sel` / `iter` fields. + * - `lane` (swimlanes): the same keys but `status`, and never the grouping. + * - `sort`: `rank` (the default), `title`, `number`, `created`, `status`, `repo`, `author`, + * `milestone` or any field, `-` first for descending. + * - `cols`: the fields a card or row shows: `title`, `number`, `repo`, `state`, `author`, + * `assignees`, `labels`, `milestone`, `created`, `status` or any field. + * - `date` (roadmap): one `iter` field, or a start and an end `date` field. + */ +export interface BoardView { + readonly id: number + readonly name: string + readonly layout: ViewLayout + readonly q: string + readonly group?: string + readonly lane?: string + readonly sort?: string + readonly cols?: readonly string[] + readonly date?: readonly number[] +} + +/** A board definition, `v: 1` (§2). `def` / `done` are column ids, 0 for none; `arch` is days, 0 = off. */ +export interface BoardSpec { + readonly v: 1 + readonly desc?: string + readonly columns: readonly BoardColumn[] + readonly def: number + readonly done: number + readonly sources: readonly BoardSource[] + readonly fields: readonly BoardField[] + readonly views: readonly BoardView[] + readonly arch: number +} + +/** + * Why a spec was refused: not JSON or not an object (`json`), not `v: 1` (`version`), over 4096 + * bytes (`size`), or the part that is malformed. A list over its limit names the list + * (`columns`, `fields`, `sources`, `views`); a malformed or repeated entry (an id, or a name in + * any letter case) names the entry (`column`, `field`, `options` for a field's options, `source`, + * `view`); `def`, `done`, `arch`, `desc` name themselves. + */ +export type SpecError = + | 'json' + | 'version' + | 'size' + | 'desc' + | 'columns' + | 'column' + | 'def' + | 'done' + | 'sources' + | 'source' + | 'fields' + | 'field' + | 'options' + | 'views' + | 'view' + | 'arch' + +export type SpecResult = { readonly spec: BoardSpec } | { readonly error: SpecError } + +/** + * Names a field may not have, in any letter case: the query's own keys and the built-in fields + * (§2.2, §4.4), so `:` is never ambiguous. + */ +const RESERVED_FIELD_NAMES: ReadonlySet = new Set([ + 'is', 'state', 'label', 'labels', 'assignee', 'assignees', 'author', 'milestone', 'no', 'status', 'repo', 'repository', 'title', 'number', 'created', +]) + +const FIELD_TYPES: readonly FieldType[] = ['sel', 'num', 'date', 'iter', 'text'] +const LAYOUTS: readonly ViewLayout[] = ['board', 'table', 'roadmap'] +const GROUP_BUILTINS = ['status', 'assignee', 'label', 'milestone', 'repo'] +const SORT_BUILTINS = ['rank', 'title', 'number', 'created', 'status', 'repo', 'author', 'milestone'] +const COL_BUILTINS = ['title', 'number', 'repo', 'state', 'author', 'assignees', 'labels', 'milestone', 'created', 'status'] + +/** The field id a `f` key names (1-255, no leading zero), or null. */ +export function fieldKeyId(key: string): number | null { + const m = /^f([1-9]\d{0,2})$/.exec(key) + if (!m) return null + const id = Number(m[1]) + return id <= 255 ? id : null +} + +/** A spec's field by id. */ +export function fieldById(spec: BoardSpec, id: number): BoardField | undefined { + return spec.fields.find((f) => f.id === id) +} + +function fieldOfKey(fields: readonly BoardField[], key: string): BoardField | undefined { + const id = fieldKeyId(key) + return id === null ? undefined : fields.find((f) => f.id === id) +} + +function groupKeyOk(fields: readonly BoardField[], key: string, boardLayout: boolean): boolean { + if (key === 'status') return true + if (GROUP_BUILTINS.includes(key)) return !boardLayout + const f = fieldOfKey(fields, key) + return f !== undefined && (f.type === 'sel' || f.type === 'iter') +} + +function sortKeyOk(fields: readonly BoardField[], key: string): boolean { + const k = key.startsWith('-') ? key.slice(1) : key + return SORT_BUILTINS.includes(k) || fieldOfKey(fields, k) !== undefined +} + +function colKeyOk(fields: readonly BoardField[], key: string): boolean { + return COL_BUILTINS.includes(key) || fieldOfKey(fields, key) !== undefined +} + +/** Whether `names` (compared in lower case) and `ids` repeat. */ +function repeats(entries: readonly { readonly id: number; readonly name: string }[]): boolean { + const ids = new Set(entries.map((e) => e.id)) + const names = new Set(entries.map((e) => e.name.toLowerCase())) + return ids.size !== entries.length || names.size !== entries.length +} + +class SpecRefused extends Error { + constructor(readonly code: SpecError) { + super(code) + } +} + +function refuse(code: SpecError): never { + throw new SpecRefused(code) +} + +/** An optional `#rrggbb`. */ +function colorOf(v: unknown, code: SpecError): string | undefined { + if (v === undefined) return undefined + return typeof v === 'string' && COLOR.test(v) ? v : refuse(code) +} + +function parseColumns(v: unknown): BoardColumn[] { + if (!Array.isArray(v) || v.length < 1 || v.length > MAX_COLUMNS) refuse('columns') + const out = v.map((c): BoardColumn => { + if (!isObject(c) || !isInt(c.id, 1, 255) || !nameOk(c.name)) refuse('column') + const color = colorOf(c.color, 'column') + if (c.wip !== undefined && !isInt(c.wip, 1, WIP_MAX)) refuse('column') + return { id: c.id, name: c.name, ...(color !== undefined ? { color } : {}), ...(c.wip !== undefined ? { wip: c.wip as number } : {}) } + }) + if (repeats(out)) refuse('column') + return out +} + +function parseColumnRef(v: unknown, columns: readonly BoardColumn[], code: 'def' | 'done'): number { + if (v === undefined) return 0 + if (!isInt(v, 0, 255) || (v !== 0 && !columns.some((c) => c.id === v))) refuse(code) + return v +} + +function parseSources(v: unknown): BoardSource[] { + if (v === undefined) return [] + if (!Array.isArray(v) || v.length > MAX_SOURCES) refuse('sources') + return v.map((s): BoardSource => { + if (!isObject(s)) refuse('source') + if (s.r !== undefined && !(typeof s.r === 'string' && IDENTIFIER.test(s.r))) refuse('source') + if (s.k !== 'i' && s.k !== 'p' && s.k !== 'a') refuse('source') + if (s.q !== undefined && !textOk(s.q, QUERY_MAX)) refuse('source') + return { ...(s.r !== undefined ? { r: s.r as string } : {}), k: s.k, q: (s.q as string | undefined) ?? '' } + }) +} + +function parseOptions(v: unknown): FieldOption[] { + if (!Array.isArray(v) || v.length > MAX_OPTIONS) refuse('options') + const out = v.map((o): FieldOption => { + if (!isObject(o) || !isInt(o.id, 1, 255) || !nameOk(o.name)) refuse('options') + const color = colorOf(o.color, 'options') + return { id: o.id, name: o.name, ...(color !== undefined ? { color } : {}) } + }) + if (repeats(out)) refuse('options') + return out +} + +function fieldNameOk(name: unknown): name is string { + return nameOk(name) && !name.includes(':') && !name.startsWith('-') && !RESERVED_FIELD_NAMES.has(name.toLowerCase()) +} + +function parseFields(v: unknown): BoardField[] { + if (v === undefined) return [] + if (!Array.isArray(v) || v.length > MAX_FIELDS) refuse('fields') + const out = v.map((f): BoardField => { + if (!isObject(f) || !isInt(f.id, 1, 255) || !fieldNameOk(f.name)) refuse('field') + const type = f.type as FieldType + if (!FIELD_TYPES.includes(type)) refuse('field') + if ((f.options !== undefined) !== (type === 'sel')) refuse('field') + if ((f.start !== undefined || f.days !== undefined) && type !== 'iter') refuse('field') + const base = { id: f.id, name: f.name, type } + if (type === 'sel') return { ...base, options: parseOptions(f.options) } + if (type === 'iter') { + if (typeof f.start !== 'string' || dateDays(f.start) === null || !isInt(f.days, 1, ITER_DAYS_MAX)) refuse('field') + return { ...base, start: f.start, days: f.days } + } + return base + }) + if (repeats(out)) refuse('field') + return out +} + +function parseViews(v: unknown, fields: readonly BoardField[]): BoardView[] { + if (v === undefined) return [] + if (!Array.isArray(v) || v.length > MAX_VIEWS) refuse('views') + const out = v.map((w): BoardView => { + if (!isObject(w) || !isInt(w.id, 1, 255) || !nameOk(w.name)) refuse('view') + const layout = w.layout as ViewLayout + if (!LAYOUTS.includes(layout)) refuse('view') + if (w.q !== undefined && !textOk(w.q, QUERY_MAX)) refuse('view') + const str = (x: unknown): x is string | undefined => x === undefined || typeof x === 'string' + const { group, lane, sort, cols, date } = w + if (!str(group) || !str(lane) || !str(sort)) refuse('view') + if (group !== undefined && !groupKeyOk(fields, group, layout === 'board')) refuse('view') + if (lane !== undefined && (lane === 'status' || lane === (group ?? 'status') || !groupKeyOk(fields, lane, false))) refuse('view') + if (sort !== undefined && !sortKeyOk(fields, sort)) refuse('view') + if (cols !== undefined) { + if (!Array.isArray(cols) || cols.length > MAX_VIEW_COLS) refuse('view') + if (cols.some((c) => typeof c !== 'string' || !colKeyOk(fields, c)) || new Set(cols).size !== cols.length) refuse('view') + } + if (date !== undefined) { + if (!Array.isArray(date) || !date.every((d) => isInt(d, 1, 255))) refuse('view') + const types = date.map((d) => fields.find((f) => f.id === d)?.type) + const iter = types.length === 1 && types[0] === 'iter' + const range = types.length === 2 && types[0] === 'date' && types[1] === 'date' && date[0] !== date[1] + if (!iter && !range) refuse('view') + } + return { + id: w.id, + name: w.name, + layout, + q: (w.q as string | undefined) ?? '', + ...(group !== undefined ? { group } : {}), + ...(lane !== undefined ? { lane } : {}), + ...(sort !== undefined ? { sort } : {}), + ...(cols !== undefined ? { cols: cols as string[] } : {}), + ...(date !== undefined ? { date: date as number[] } : {}), + } + }) + if (repeats(out)) refuse('view') + return out +} + +/** + * Read a board definition (`board.spec`, §2): JSON, `v: 1`, at most 4096 UTF-8 bytes, every + * limit of §8, ids 1-255 and unique, names unique in any letter case, every reference (`def`, + * `done`, a view's keys) to something the spec defines. Unknown keys are tolerated (a later + * client's optional additions read here) and dropped by {@link serializeSpec}; a known key of the + * wrong type or shape refuses the whole spec. Checked in the canonical key order, so both + * clients name the same first problem. + */ +export function parseSpec(json: string): SpecResult { + if (utf8Length(json) > SPEC_MAX_BYTES) return { error: 'size' } + const raw = readJson(json) + if (!isObject(raw)) return { error: 'json' } + try { + if (raw.v !== 1) refuse('version') + if (raw.desc !== undefined && !textOk(raw.desc, DESC_MAX)) refuse('desc') + const columns = parseColumns(raw.columns) + const def = parseColumnRef(raw.def, columns, 'def') + const done = parseColumnRef(raw.done, columns, 'done') + const sources = parseSources(raw.sources) + const fields = parseFields(raw.fields) + const views = parseViews(raw.views, fields) + if (raw.arch !== undefined && !isInt(raw.arch, 0, ARCH_MAX)) refuse('arch') + const arch = (raw.arch as number | undefined) ?? 0 + // an empty description is none (written as none) + const desc = raw.desc === '' ? undefined : (raw.desc as string | undefined) + return { spec: { v: 1, ...(desc !== undefined ? { desc } : {}), columns, def, done, sources, fields, views, arch } } + } catch (e) { + if (e instanceof SpecRefused) return { error: e.code } + throw e + } +} + +/** The spec as canonical JSON: keys in the declared order, defaults (0, `""`, `[]`, absent) omitted. */ +function canonicalSpec(spec: BoardSpec): string { + const opt = (key: string, v: T | undefined, omit: (x: T) => boolean = () => false) => (v === undefined || omit(v) ? {} : { [key]: v }) + return JSON.stringify({ + v: 1, + ...opt('desc', spec.desc), + columns: spec.columns.map((c) => ({ id: c.id, name: c.name, ...opt('color', c.color), ...opt('wip', c.wip) })), + ...opt('def', spec.def, (x) => x === 0), + ...opt('done', spec.done, (x) => x === 0), + ...opt('sources', spec.sources.map((s) => ({ ...opt('r', s.r), k: s.k, ...opt('q', s.q, (x) => x === '') })), (x) => x.length === 0), + ...opt( + 'fields', + spec.fields.map((f) => ({ + id: f.id, + name: f.name, + type: f.type, + ...opt('options', f.options?.map((o) => ({ id: o.id, name: o.name, ...opt('color', o.color) }))), + ...opt('start', f.start), + ...opt('days', f.days), + })), + (x) => x.length === 0, + ), + ...opt( + 'views', + spec.views.map((w) => ({ + id: w.id, + name: w.name, + layout: w.layout, + ...opt('q', w.q, (x) => x === ''), + ...opt('group', w.group), + ...opt('lane', w.lane), + ...opt('sort', w.sort), + ...opt('cols', w.cols), + ...opt('date', w.date), + })), + (x) => x.length === 0, + ), + ...opt('arch', spec.arch, (x) => x === 0), + }) +} + +/** + * Write a definition as canonical compact JSON (the declared key order, defaults omitted), so + * equal specs are equal bytes in both clients. Refused when it would not read back + * ({@link parseSpec}'s error) or is over 4096 bytes (`size`): what this returns always parses + * to an equal spec. + */ +export function serializeSpec(spec: BoardSpec): { readonly json: string } | { readonly error: SpecError } { + const json = canonicalSpec(spec) + const back = parseSpec(json) + if ('error' in back) return back + // a spec carrying a value its parse normalizes away (an unknown key) is written as parsed + return { json: canonicalSpec(back.spec) } +} + +/** The Monday (UTC) of the week holding `ms`, as `YYYY-MM-DD`. */ +export function mondayOf(ms: number): string { + const days = Math.floor(ms / DAY_MS) + // 1970-01-01 was a Thursday: (days + 3) mod 7 is days since Monday + return civilFromDays(days - (((days + 3) % 7) + 7) % 7) +} + +/** + * The new-board template: Todo / In progress / Done (Done the done column, Todo the default), + * the home repository's issues and pull requests, Priority (P0-P3), Estimate and a two-week + * Iteration starting the Monday of the week of `nowMs`, a Board, a Table and a Roadmap view, + * and auto-archive after 14 days. + */ +export function defaultSpec(homeRepoId: string, nowMs: number): BoardSpec { + return { + v: 1, + columns: [ + { id: 1, name: 'Todo' }, + { id: 2, name: 'In progress' }, + { id: 3, name: 'Done' }, + ], + def: 1, + done: 3, + sources: [{ r: homeRepoId, k: 'a', q: '' }], + fields: [ + { + id: 1, + name: 'Priority', + type: 'sel', + options: [ + { id: 1, name: 'P0', color: '#d1242f' }, + { id: 2, name: 'P1', color: '#fb8f44' }, + { id: 3, name: 'P2', color: '#d4a72c' }, + { id: 4, name: 'P3', color: '#8c959f' }, + ], + }, + { id: 2, name: 'Estimate', type: 'num' }, + { id: 3, name: 'Iteration', type: 'iter', start: mondayOf(nowMs), days: 14 }, + ], + views: [ + { id: 1, name: 'Board', layout: 'board', q: '' }, + { id: 2, name: 'Table', layout: 'table', q: '', cols: ['title', 'status', 'assignees', 'f1', 'f2', 'f3'] }, + { id: 3, name: 'Roadmap', layout: 'roadmap', q: '', date: [3] }, + ], + arch: 14, + } +} + +// --------------------------------------------------------------------------------------------- +// Card field values (§3.2 `f`) +// --------------------------------------------------------------------------------------------- + +/** A field value: an option id (`sel`), a number (`num`), `YYYY-MM-DD` (`date`), an iteration index (`iter`) or text. */ +export type FieldValue = number | string + +/** A card's field values by field id (decimal, as JSON keys). */ +export type FieldValues = Readonly> + +/** Whether `v` is a valid value of `field`. */ +export function fieldValueOk(field: BoardField, v: unknown): v is FieldValue { + switch (field.type) { + case 'sel': + return isInt(v, 1, 255) && (field.options ?? []).some((o) => o.id === v) + case 'num': + return typeof v === 'number' && Number.isFinite(v) && Math.abs(v) <= NUM_ABS_MAX && (v === 0 || Math.abs(v) >= NUM_ABS_MIN) + case 'date': + return dateDays(v) !== null + case 'iter': + return isInt(v, 0, ITER_INDEX_MAX) + case 'text': + return typeof v === 'string' && v !== '' && textOk(v, TEXT_VALUE_MAX) + } +} + +/** `values` less every entry for a field `spec` does not have, an option it does not have, or of the wrong type; `-0` reads as 0. */ +function validValues(entries: Iterable<[string, unknown]>, spec: BoardSpec): Record { + const out: Record = {} + for (const [key, v] of entries) { + if (!/^[1-9]\d{0,2}$/.test(key)) continue + const field = fieldById(spec, Number(key)) + if (field === undefined || !fieldValueOk(field, v)) continue + out[key] = v === 0 ? 0 : v + } + return out +} + +/** + * A card's field values (`card.f`, `{"": value}`), keeping only those `spec` defines + * with a value of the field's type (a deleted field, a deleted option, a wrong type are dropped: + * the card reads as having no value there). Not JSON or not an object reads as none. + */ +export function parseFieldValues(json: string | null, spec: BoardSpec): FieldValues { + if (json === null || json === '') return {} + const raw = readJson(json) + return isObject(raw) ? validValues(Object.entries(raw), spec) : {} +} + +/** + * Field values as canonical JSON (ids ascending, invalid entries dropped as {@link + * parseFieldValues} drops them), refused over 2048 bytes (`size`). + */ +export function serializeFieldValues(values: FieldValues, spec: BoardSpec): { readonly json: string } | { readonly error: 'size' } { + // integer-like keys iterate in ascending numeric order + const json = JSON.stringify(validValues(Object.entries(values), spec)) + return utf8Length(json) > FIELD_VALUES_MAX_BYTES ? { error: 'size' } : { json } +} + +// --------------------------------------------------------------------------------------------- +// Rank (§2.6) +// --------------------------------------------------------------------------------------------- + +/** The 62 rank digits, in ASCII (byte) order. */ +export const RANK_DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + +/** A rank digit's value 0-61, or -1. */ +function digitOf(c: string): number { + const x = c.charCodeAt(0) + if (x >= 48 && x <= 57) return x - 48 + if (x >= 65 && x <= 90) return x - 55 + if (x >= 97 && x <= 122) return x - 61 + return -1 +} + +/** Whether `r` is a well-formed explicit rank: 1-63 digits, not ending in `0` (the `card.rank` pattern). */ +export function isExplicitRank(r: unknown): r is string { + return typeof r === 'string' && /^[0-9A-Za-z]{0,62}[1-9A-Za-z]$/.test(r) +} + +/** + * Why no rank was made: a bound is not 0-63 rank digits (`invalid`), the lower bound is above the + * upper (`order`), or no rank of at most 63 digits fits between them (`re-rank`: the bounds are + * equal, or `b` is `a` + `0…0`, or the gap is used up; re-rank the column, §2.6). + */ +export type RankError = 'invalid' | 'order' | 're-rank' + +export type RankResult = { readonly rank: string } | { readonly error: RankError } + +/** + * A rank strictly between `a` and `b` in byte order (`null` / `""` is open: below everything / + * above everything), ending in a non-zero digit, at most 63 digits. + * + * Built digit by digit. `lo` / `hi` say whether the digits so far still equal `a`'s / `b`'s. + * At position i the digit x may end the rank when it is above `a[i]` (or anything above 0 once + * `a` is passed or exhausted), and below `b[i]` (or equal to it while `b` goes on: the rank is + * then a proper prefix of `b`, which sorts first). The midpoint of the allowed digits is taken; + * when none is allowed the rank copies `a[i]` (staying just above `a`) or, past `a`, writes `0` + * (forced while `b[i]` is `0`), and goes on. So `a` < rank < `b` always holds, a bound may end in + * `0` (an implicit rank), and a prefix pair (`V` / `V1`) is handled. The pairs with nothing + * between are equal bounds and `b` = `a` + `0…0`; they end in `re-rank`, as does a rank that would + * pass 63 digits. + */ +export function rankBetween(a: string | null, b: string | null): RankResult { + const lo = a ?? '' + const hi = b ?? '' + const ok = (r: string) => r.length <= RANK_MAX && [...r].every((c) => digitOf(c) >= 0) + if (!ok(lo) || !ok(hi)) return { error: 'invalid' } + // two members dropping into one gap at once write one rank: nothing lies between them + if (hi !== '' && compareStrings(lo, hi) >= 0) return { error: lo === hi ? 're-rank' : 'order' } + let out = '' + let loTight = true + let hiTight = hi !== '' + for (let i = 0; ; i++) { + if (i >= RANK_MAX || (hiTight && i >= hi.length)) return { error: 're-rank' } + const inLo: boolean = loTight && i < lo.length + const floor = inLo ? digitOf(lo[i] as string) : 0 + const hd = hiTight ? digitOf(hi[i] as string) : 62 + const ceil = hiTight && i + 1 < hi.length ? hd + 1 : hd + if (ceil - floor >= 2) return { rank: out + RANK_DIGITS[(floor + ceil) >> 1] } + loTight = inLo + hiTight = hiTight && floor === hd + out += RANK_DIGITS[floor] + } +} + +/** `n` in `width` base-62 digits (clamped to 0 … 62^width − 1). */ +function base62(n: number, width: number): string { + let v = Math.max(0, Math.min(Math.floor(n), 62 ** width - 1)) + let out = '' + for (let i = 0; i < width; i++) { + out = RANK_DIGITS[v % 62] + out + v = Math.floor(v / 62) + } + return out +} + +/** + * The rank of an item with no card, or whose newest card has no rank: `V`, its `$createdAt` in + * 8 base-62 digits, the first 3 bytes of its `$id` (big-endian, mod 62⁴) in 4. Sourced items pool + * in creation order, oldest first, none equal. It may end in `0`. + */ +export function implicitRank(createdAtMs: number, itemIdBytes: Uint8Array): string { + const head = ((itemIdBytes[0] ?? 0) << 16) | ((itemIdBytes[1] ?? 0) << 8) | (itemIdBytes[2] ?? 0) + return `V${base62(createdAtMs, 8)}${base62(head % 62 ** 4, 4)}` +} + +/** The bytes of a base58 id; none when it is not base58. */ +function idBytes(id: string): Uint8Array { + try { + return base58Decode(id) + } catch { + return new Uint8Array(0) + } +} + +/** {@link implicitRank} of an item by its base58 `$id`. */ +export function implicitRankOf(createdAtMs: number, itemId: string): string { + return implicitRank(createdAtMs, idBytes(itemId)) +} + +/** The rank that puts a card at the top of a column whose first rank is `first` (null: empty), above the sourced pool. */ +export function topRank(first: string | null): RankResult { + return rankBetween('', first === null || compareStrings(first, 'V') > 0 ? 'V' : first) +} + +/** The rank that puts a card at the bottom of a column whose last rank is `last` (null: empty), below the sourced pool. */ +export function bottomRank(last: string | null): RankResult { + return rankBetween(last === null || compareStrings(last, 'W') < 0 ? 'W' : last, '') +} + +/** + * `n` evenly spaced explicit ranks, ascending, for re-ranking a column (§2.6): rank k is k/(n+1) + * of the way from `0` to `V` (so items sourced later join below them, in the pool), in the fewest + * digits that leave 62 free ranks between neighbours, trailing zeros dropped. `invalid` for n + * outside 0 … 1 000 000. + */ +export function rerank(n: number): { readonly ranks: readonly string[] } | { readonly error: 'invalid' } { + if (!Number.isInteger(n) || n < 0 || n > RERANK_MAX) return { error: 'invalid' } + let width = 1 + while (31 * 62 ** (width - 1) < 62 * (n + 1)) width++ + const space = 31 * 62 ** (width - 1) + const ranks: string[] = [] + for (let k = 1; k <= n; k++) ranks.push(base62(Math.floor((k * space) / (n + 1)), width).replace(/0+$/, '')) + return { ranks } +} + +// --------------------------------------------------------------------------------------------- +// Iterations (§2.2) +// --------------------------------------------------------------------------------------------- + +/** One iteration of an `iter` field: index k, named " k+1", `start` … `end` (the last day, inclusive). */ +export interface IterationRange { + readonly index: number + readonly name: string + readonly start: string + readonly end: string + /** `start`'s midnight UTC, and the next iteration's (exclusive end). */ + readonly startMs: number + readonly endMs: number +} + +/** An `iter` field's first day number and length in days; null when `field` is not a well-formed `iter` field. */ +function iterOf(field: BoardField): { readonly start: number; readonly days: number } | null { + const start = dateDays(field.start) + if (field.type !== 'iter' || start === null || field.days === undefined || field.days < 1) return null + return { start, days: field.days } +} + +/** The index of `field`'s iteration holding `dateMs` (UTC days); null before its first or past index 65535, or not an `iter` field. */ +export function iterationAt(field: BoardField, dateMs: number): number | null { + const iter = iterOf(field) + if (iter === null) return null + const k = Math.floor((Math.floor(dateMs / DAY_MS) - iter.start) / iter.days) + return k >= 0 && k <= ITER_INDEX_MAX ? k : null +} + +/** Iteration `k` of `field`: days `start + k·days` … `start + (k+1)·days − 1`; null when not an `iter` field or k out of range. */ +export function iterationRange(field: BoardField, k: number): IterationRange | null { + const iter = iterOf(field) + if (iter === null || !isInt(k, 0, ITER_INDEX_MAX)) return null + const first = iter.start + k * iter.days + const next = first + iter.days + return { index: k, name: `${field.name} ${k + 1}`, start: civilFromDays(first), end: civilFromDays(next - 1), startMs: first * DAY_MS, endMs: next * DAY_MS } +} + +// --------------------------------------------------------------------------------------------- +// Items, cards and placement (§2.4) +// --------------------------------------------------------------------------------------------- + +export type ItemKind = 'issue' | 'pr' +export type ItemState = 'open' | 'closed' | 'merged' + +/** + * What a board reads of an issue or PR. `closedAt` is the `$createdAt` of its latest transition + * into closed or merged (null when open, or unknown); `repo` is `owner/name` as shown, when known. + * `assignees` / `author` are identity ids. + */ +export interface BoardItem { + readonly id: string + readonly number: number + readonly repoId: string + readonly repo?: string + readonly kind: ItemKind + readonly state: ItemState + readonly createdAt: number + readonly closedAt: number | null + readonly title: string + readonly labels: readonly string[] + readonly assignees: readonly string[] + readonly milestone: string | null + readonly author: string +} + +/** Card `state` (§3.2). */ +export const CARD_ACTIVE = 0 +export const CARD_ARCHIVED = 1 +export const CARD_REMOVED = 2 + +/** A `card` document as read (a private repo's opened): `col` / `rank` / `f` null when absent or unreadable. */ +export interface CardDoc { + readonly id: string + readonly ownerId: string + readonly updatedAt: number + readonly item: string + readonly col: number | null + readonly rank: string | null + readonly f: string | null + readonly state: number +} + +/** Why an item is archived: its newest card says so, or auto-archive (`arch`) caught it. */ +export type ArchivedBy = 'card' | 'auto' + +/** Where one item shows (§2.4). `col` 0 is "No status". */ +export interface Placement { + readonly id: string + /** On the board: a source matches it or it has a card, and that card is not removed. */ + readonly on: boolean + readonly sourced: boolean + readonly removed: boolean + /** The newest card's `$id`, if any. */ + readonly card: string | null + readonly col: number + readonly rank: string + readonly archived: ArchivedBy | null + readonly fields: FieldValues +} + +/** A column's visible items (on the board, not archived), in rank order. */ +export interface ColumnItems { + readonly id: number + readonly items: readonly string[] +} + +export interface BoardFold { + /** One per input item, in input order (repeated ids once). */ + readonly items: readonly Placement[] + /** "No status" (0) first while it holds an item, then every column in order. */ + readonly columns: readonly ColumnItems[] +} + +export interface FoldInput { + readonly spec: BoardSpec + /** The board's home repository id (a source without `r` reads it). */ + readonly home: string + readonly items: readonly BoardItem[] + /** The board's cards (every member's, this board's key and home repo). */ + readonly cards: readonly CardDoc[] + readonly now: number +} + +/** Whether `a` is newer than `b` by (`$updatedAt`, `$id`), the id by code point. */ +function newer(a: { readonly updatedAt: number; readonly id: string }, b: { readonly updatedAt: number; readonly id: string }): boolean { + return a.updatedAt !== b.updatedAt ? a.updatedAt > b.updatedAt : compareStrings(a.id, b.id) > 0 +} + +/** Every item's newest card over every member's, by (`$updatedAt`, `$id`) (§2.4). */ +export function newestCards(cards: readonly CardDoc[]): Map { + const out = new Map() + for (const c of cards) { + const prev = out.get(c.item) + if (prev === undefined || newer(c, prev)) out.set(c.item, c) + } + return out +} + +/** A `board` document as read: `spec` null when absent or unreadable. */ +export interface BoardDoc { + readonly id: string + readonly ownerId: string + readonly updatedAt: number + readonly key: number + readonly state: number + readonly name: string | null + readonly spec: string | null +} + +/** Board `state` (§3.1). */ +export const BOARD_OPEN = 0 +export const BOARD_CLOSED = 1 +export const BOARD_DELETED = 2 + +/** + * A repository's boards: per key the newest revision over every member's by (`$updatedAt`, + * `$id`), ascending by key, less the deleted ones (state 2) unless `withDeleted`. + */ +export function newestBoards(docs: readonly BoardDoc[], withDeleted = false): BoardDoc[] { + const byKey = new Map() + for (const d of docs) { + const prev = byKey.get(d.key) + if (prev === undefined || newer(d, prev)) byKey.set(d.key, d) + } + return [...byKey.values()].filter((d) => withDeleted || d.state !== BOARD_DELETED).sort((a, b) => a.key - b.key) +} + +/** + * Whether `source` includes `item` (§2.3): its repository (absent: `home`) and kind, and the + * qualifiers of its query (`query`, {@link parseSourceQuery} of `source.q`). + */ +export function sourceMatches(source: BoardSource, query: BoardQuery, item: BoardItem, home: string, spec: BoardSpec, now: number): boolean { + if ((source.r ?? home) !== item.repoId) return false + if (source.k === 'i' && item.kind !== 'issue') return false + if (source.k === 'p' && item.kind !== 'pr') return false + return queryHolds(item, null, spec, query, { me: null, now }) +} + +/** + * Where every item shows (§2.4). Per item: its newest card; on the board when a source matches + * it or it has a card, unless that card is removed; its column (closed or merged → Done, unless + * the card holds it in a column at or after Done; else the card's column while the board has it; + * else the default); its rank (the card's, else {@link implicitRank}); archived by its card, or + * by auto-archive once `now ≥ closedAt + arch` days for a closed or merged item whose newest card + * is older than `closedAt` (or which has none); its field values ({@link parseFieldValues}). + */ +export function foldBoard(input: FoldInput): BoardFold { + const { spec, home, now } = input + const cards = newestCards(input.cards) + const sources = spec.sources.map((s) => ({ s, q: parseSourceQuery(s.q, spec) })) + const colIndex = new Map(spec.columns.map((c, i) => [c.id, i])) + const doneIndex = spec.done === 0 ? undefined : colIndex.get(spec.done) + const seen = new Set() + const items: Placement[] = [] + for (const item of input.items) { + if (seen.has(item.id)) continue + seen.add(item.id) + const card = cards.get(item.id) ?? null + const sourced = sources.some(({ s, q }) => sourceMatches(s, q, item, home, spec, now)) + const removed = card?.state === CARD_REMOVED + const cardCol = card !== null && card.col !== null && colIndex.has(card.col) ? card.col : null + const finished = item.state !== 'open' + let col: number + if (finished && doneIndex !== undefined && !(cardCol !== null && (colIndex.get(cardCol) as number) >= doneIndex)) col = spec.done + else col = cardCol ?? spec.def + let archived: ArchivedBy | null = null + if (card?.state === CARD_ARCHIVED) archived = 'card' + else if (spec.arch > 0 && finished && item.closedAt !== null && (card === null || card.updatedAt < item.closedAt) && now >= item.closedAt + spec.arch * DAY_MS) archived = 'auto' + items.push({ + id: item.id, + on: (sourced || card !== null) && !removed, + sourced, + removed, + card: card?.id ?? null, + col, + rank: card !== null && isExplicitRank(card.rank) ? card.rank : implicitRankOf(item.createdAt, item.id), + archived, + fields: card === null ? {} : parseFieldValues(card.f, spec), + }) + } + const visible = items.filter((p) => p.on && p.archived === null).sort(byRank) + const inCol = (id: number) => visible.filter((p) => p.col === id).map((p) => p.id) + const none = inCol(0) + return { items, columns: [...(none.length > 0 ? [{ id: 0, items: none }] : []), ...spec.columns.map((c) => ({ id: c.id, items: inCol(c.id) }))] } +} + +/** Order within a column (§2.6): (rank, item `$id`), both by code point. */ +export function byRank(a: { readonly rank: string; readonly id: string }, b: { readonly rank: string; readonly id: string }): number { + return compareStrings(a.rank, b.rank) || compareStrings(a.id, b.id) +} + +// --------------------------------------------------------------------------------------------- +// Query (§4.4) +// --------------------------------------------------------------------------------------------- + +/** A comparison of a field value: `=`, `>`, `>=`, `<`, `<=`, an inclusive range `a..b`, or text `has`. */ +export type QueryOp = 'eq' | 'gt' | 'ge' | 'lt' | 'le' | 'range' | 'has' + +/** + * One qualifier, every one ANDed, `not` for a leading `-`: + * - `is`: `v` `open`, `closed` (closed or merged), `merged`, `unmerged` (open or closed), `issue`, `pr`, `archived` + * - `label` / `milestone` (names, any case), `assignee` / `author` (an identity id or `me`), `repo` (`owner/name` or an id) + * - `status`: `v` a column id; `no`: `v` `label`, `assignee`, `milestone`, `status` or `f` + * - `field`: field `f`, `op`, `v` (and `v2` for a range: either end may be absent, `*`): an option id + * (`sel`), a number (`num`), `YYYY-MM-DD` or `@today` (`date`), an iteration index or `@current` / + * `@next` / `@previous` (`iter`), lowercased text (`text`, `has`) + */ +export interface QueryPred { + readonly k: 'is' | 'label' | 'milestone' | 'assignee' | 'author' | 'repo' | 'status' | 'no' | 'field' + readonly not: boolean + readonly v?: string | number + readonly f?: number + readonly op?: QueryOp + readonly v2?: string | number +} + +export interface BoardQuery { + readonly preds: readonly QueryPred[] + /** The free text: matched against titles, `#12` / `12` against numbers. */ + readonly text: string + /** The qualifier tokens not applied, as typed (reported under the box, never searched). */ + readonly unresolved: readonly string[] +} + +const IS_VALUES = ['open', 'closed', 'merged', 'unmerged', 'issue', 'pr', 'archived'] +/** The query's own keys: a token with one of them and no value is reported, not text. */ +const QUERY_KEYS = new Set(['is', 'state', 'label', 'milestone', 'assignee', 'author', 'repo', 'status', 'no']) +const LABEL_MAX = 30 +const MILESTONE_MAX = 63 +const ITER_RELATIVE = ['@current', '@next', '@previous'] + +const unquote = (s: string): string => s.replace(/"/g, '') + +/** A person value: an identity id, or `me` (`@me`, any case). */ +function personOf(v: string): string | null { + const t = v.replace(/^@/, '') + if (t.toLowerCase() === 'me') return 'me' + return IDENTIFIER.test(t) ? t : null +} + +const COMPARISON_OPS: Readonly> = { '>=': 'ge', '<=': 'le', '>': 'gt', '<': 'lt' } + +/** A comparison value's op and operand(s), its operands still text. */ +function comparison(v: string): { op: QueryOp; a: string; b?: string } { + const range = /^(.*?)\.\.(.*)$/.exec(v) + if (range) return { op: 'range', a: range[1] as string, b: range[2] as string } + const m = /^(>=|<=|>|<)(.*)$/.exec(v) + if (!m) return { op: 'eq', a: v } + return { op: COMPARISON_OPS[m[1] as string] as QueryOp, a: m[2] as string } +} + +const NUMBER = /^-?\d{1,15}(\.\d{1,15})?$/ + +/** A typed comparison operand: a number, a date, an iteration; null when it does not read as one. */ +function operand(field: BoardField, s: string): string | number | null { + switch (field.type) { + case 'num': + return NUMBER.test(s) ? Number(s) : null + case 'date': + return s.toLowerCase() === '@today' ? '@today' : dateDays(s) !== null ? s : null + case 'iter': { + const low = s.toLowerCase() + if (ITER_RELATIVE.includes(low)) return low + // `3` or `"Iteration 3"`: iteration 3, index 2 + const prefix = `${field.name.toLowerCase()} ` + const n = low.startsWith(prefix) ? low.slice(prefix.length) : low + return /^[1-9]\d{0,4}$/.test(n) && Number(n) - 1 <= ITER_INDEX_MAX ? Number(n) - 1 : null + } + default: + return null + } +} + +/** A custom-field qualifier's predicate, or null when the value does not read for the field. */ +function fieldPred(field: BoardField, value: string, not: boolean): QueryPred | null { + if (value === '') return null + const base = { k: 'field' as const, not, f: field.id } + if (field.type === 'sel') { + const opt = (field.options ?? []).find((o) => o.name.toLowerCase() === value.toLowerCase()) + return opt ? { ...base, op: 'eq', v: opt.id } : null + } + if (field.type === 'text') return charLength(value) <= TEXT_VALUE_MAX ? { ...base, op: 'has', v: value.toLowerCase() } : null + const c = comparison(value) + if (c.op === 'range') { + const a = c.a === '*' ? null : operand(field, c.a) + const b = c.b === '*' ? null : operand(field, c.b as string) + if ((c.a !== '*' && a === null) || (c.b !== '*' && b === null) || (c.a === '*' && c.b === '*')) return null + if (a === null) return { ...base, op: 'le', v: b as string | number } + if (b === null) return { ...base, op: 'ge', v: a } + return { ...base, op: 'range', v: a, v2: b } + } + const a = operand(field, c.a) + return a === null ? null : { ...base, op: c.op, v: a } +} + +/** + * Read a board query (§4.4): the Issues tab's qualifiers (`is:open|closed|merged|unmerged`, + * `is:issue|pr`, `label:`, `assignee:`, `author:`, `milestone:`, `no:label|assignee|milestone`; + * `state:` reads as `is:`), plus `status:`, `no:status`, `repo:owner/name`, + * `is:archived`, and `:` for a custom field by name (`priority:P0`, + * `estimate:>3`, `estimate:1..5`, `target:<2026-11-01`, `iteration:@current`, `no:priority`). + * Any qualifier takes a leading `-` (NOT). Keys and names match in any letter case; quote values + * (and field names) with spaces: `status:"In progress"`, `"story points":>3`. A token whose key + * or value names nothing on this board is reported in `unresolved`, never searched as text; a + * key with nothing after its colon (`note:`) and a URL stay text. Values naming people take an + * identity id or `@me` (resolve DPNS names first, as the Issues tab does). + */ +export function parseBoardQuery(text: string, spec: BoardSpec): BoardQuery { + return parseQuery(text, spec, false) +} + +/** + * A source's query (§2.3): {@link parseBoardQuery} less what depends on the board or the reader + * rather than the item (`status:`, `no:status`, custom fields, `is:archived`, `@me`), which goes + * to `unresolved`: a source includes the same items for every reader, before any card. + */ +export function parseSourceQuery(text: string, spec: BoardSpec): BoardQuery { + return parseQuery(text, spec, true) +} + +/** Whether a predicate reads the board or the reader, not only the item. */ +function boardOnly(p: QueryPred): boolean { + if (p.k === 'status' || p.k === 'field') return true + if (p.k === 'no') return p.v === 'status' || fieldKeyId(String(p.v)) !== null + if (p.k === 'is') return p.v === 'archived' + return (p.k === 'assignee' || p.k === 'author') && p.v === 'me' +} + +function parseQuery(text: string, spec: BoardSpec, forSource: boolean): BoardQuery { + const preds: QueryPred[] = [] + const free: string[] = [] + const unresolved: string[] = [] + const fieldByName = new Map(spec.fields.map((f) => [f.name.toLowerCase(), f])) + for (const tok of searchTokens(text)) { + const at = tok.indexOf(':') + const rawKey = at > 0 ? tok.slice(0, at) : '' + const not = rawKey.startsWith('-') && rawKey.length > 1 + const key = unquote(not ? rawKey.slice(1) : rawKey).toLowerCase() + const rawValue = at > 0 ? tok.slice(at + 1) : '' + const value = unquote(rawValue) + if (key === '' || (value === '' && !QUERY_KEYS.has(key) && !fieldByName.has(key)) || rawValue.startsWith('//')) { + free.push(tok) + continue + } + const pred = qualifier(key, value, not, spec, fieldByName) + if (pred === null || (forSource && boardOnly(pred))) unresolved.push(tok) + else preds.push(pred) + } + return { preds, text: free.join(' '), unresolved } +} + +function qualifier(key: string, value: string, not: boolean, spec: BoardSpec, fieldByName: ReadonlyMap): QueryPred | null { + const low = value.toLowerCase() + switch (key) { + case 'is': + case 'state': + return IS_VALUES.includes(low) && (key === 'is' || ['open', 'closed', 'merged', 'unmerged'].includes(low)) ? { k: 'is', not, v: low } : null + case 'label': + return value !== '' && charLength(value) <= LABEL_MAX ? { k: 'label', not, v: value } : null + case 'milestone': + return value !== '' && charLength(value) <= MILESTONE_MAX ? { k: 'milestone', not, v: value } : null + case 'assignee': + case 'author': { + const who = personOf(value) + return who === null ? null : { k: key, not, v: who } + } + case 'repo': + return value !== '' ? { k: 'repo', not, v: value } : null + case 'status': { + const col = spec.columns.find((c) => c.name.toLowerCase() === low) + return col ? { k: 'status', not, v: col.id } : null + } + case 'no': { + if (['label', 'assignee', 'milestone', 'status'].includes(low)) return { k: 'no', not, v: low } + const f = fieldByName.get(low) + return f ? { k: 'no', not, v: `f${f.id}` } : null + } + default: { + const f = fieldByName.get(key) + return f ? fieldPred(f, value, not) : null + } + } +} + +/** What a query reads besides the item: the viewer (`@me`) and the time (`@today`, `@current`). */ +export interface QueryContext { + readonly me: string | null + readonly now: number +} + +/** A field value's rank for comparison, resolving `@today` and the relative iterations; null: matches nothing. */ +function resolveOperand(field: BoardField, v: string | number, ctx: QueryContext): string | number | null { + if (v === '@today') return dateOf(ctx.now) + if (typeof v === 'string' && ITER_RELATIVE.includes(v)) { + // before the first iteration there is no current one, and the next is the first + const cur = iterationAt(field, ctx.now) + const before = ctx.now < (dateDays(field.start) ?? 0) * DAY_MS + if (v === '@current') return cur + if (v === '@next') return cur !== null ? cur + 1 : before ? 0 : null + return cur !== null && cur > 0 ? cur - 1 : null + } + return v +} + +function compare(x: string | number, y: string | number): number { + if (typeof x === 'number' && typeof y === 'number') return x < y ? -1 : x > y ? 1 : 0 + return compareStrings(String(x), String(y)) +} + +function fieldHolds(p: QueryPred, field: BoardField, value: FieldValue | undefined, ctx: QueryContext): boolean { + if (value === undefined) return false + if (p.op === 'has') return String(value).toLowerCase().includes(String(p.v)) + const a = resolveOperand(field, p.v as string | number, ctx) + if (a === null) return false + const c = compare(value, a) + switch (p.op) { + case 'eq': + return c === 0 + case 'gt': + return c > 0 + case 'ge': + return c >= 0 + case 'lt': + return c < 0 + case 'le': + return c <= 0 + case 'range': { + const b = resolveOperand(field, p.v2 as string | number, ctx) + return b !== null && c >= 0 && compare(value, b) <= 0 + } + default: + return false + } +} + +/** Whether the item's title and number hold every free-text term (the Issues tab's `matchesText`, without a body). */ +function textMatches(text: string, item: BoardItem): boolean { + const title = item.title.toLowerCase() + return searchTerms(text).every((t) => { + const hash = /^#(\d+)$/.exec(t.text) + const holds = hash ? Number(hash[1]) === item.number : (/^\d+$/.test(t.text) && Number(t.text) === item.number) || title.includes(t.text) + return holds !== t.not + }) +} + +/** One predicate on the item and (for board qualifiers) its placement. */ +function predHolds(p: QueryPred, item: BoardItem, placement: Placement | null, spec: BoardSpec, ctx: QueryContext): boolean { + const eqi = (a: string, b: string) => a.toLowerCase() === b.toLowerCase() + switch (p.k) { + case 'is': + switch (p.v) { + case 'open': + return item.state === 'open' + case 'closed': + return item.state !== 'open' + case 'merged': + return item.state === 'merged' + case 'unmerged': + return item.state !== 'merged' + case 'issue': + return item.kind === 'issue' + case 'pr': + return item.kind === 'pr' + default: + return placement !== null && placement.archived !== null + } + case 'label': + return item.labels.some((l) => eqi(l, p.v as string)) + case 'milestone': + return item.milestone !== null && eqi(item.milestone, p.v as string) + case 'assignee': + case 'author': { + const who = p.v === 'me' ? ctx.me : (p.v as string) + if (who === null) return false + return p.k === 'author' ? item.author === who : item.assignees.includes(who) + } + case 'repo': + return item.repoId === p.v || (item.repo !== undefined && eqi(item.repo, p.v as string)) + case 'status': + return placement !== null && placement.col === p.v + case 'no': + switch (p.v) { + case 'label': + return item.labels.length === 0 + case 'assignee': + return item.assignees.length === 0 + case 'milestone': + return item.milestone === null + case 'status': + return placement !== null && placement.col === 0 + default: + return placement !== null && placement.fields[String(fieldKeyId(p.v as string))] === undefined + } + case 'field': { + const field = fieldById(spec, p.f as number) + return field !== undefined && placement !== null && fieldHolds(p, field, placement.fields[String(p.f)], ctx) + } + } +} + +/** Whether an item (with its placement; none for a source) holds every predicate, each negated by `-`, and the free text. */ +function queryHolds(item: BoardItem, placement: Placement | null, spec: BoardSpec, query: BoardQuery, ctx: QueryContext): boolean { + return query.preds.every((p) => predHolds(p, item, placement, spec, ctx) !== p.not) && textMatches(query.text, item) +} + +/** + * Whether an item on the board passes `query` (§4.4): it is on the board, archived exactly when + * the query has `is:archived` (otherwise archived items are hidden), and holds every predicate + * (each negated by `-`) and the free text. A value the item lacks never matches its qualifier + * (so `-priority:P0` matches an item with no priority). + */ +export function matchesBoardQuery(item: BoardItem, placement: Placement, spec: BoardSpec, query: BoardQuery, ctx: QueryContext): boolean { + if (!placement.on) return false + const wantsArchived = query.preds.some((p) => p.k === 'is' && p.v === 'archived') + if (!wantsArchived && placement.archived !== null) return false + return queryHolds(item, placement, spec, query, ctx) +} + +// --------------------------------------------------------------------------------------------- +// Views: grouping, sorting, totals, progress (§4.1-§4.5) +// --------------------------------------------------------------------------------------------- + +/** An item with its placement, as views take them. */ +export interface BoardRow { + readonly item: BoardItem + readonly placement: Placement +} + +/** A group's key: a column id (status), an option id (`sel`), an iteration index, an identity id, a label or milestone name, a repo id; null for "No ". */ +export interface RowGroup { + readonly key: string | number | null + readonly items: readonly string[] +} + +/** + * `rows` grouped by `by` (a view's `group` or `lane` key), each group's items in `rows`' order. + * The empty group (null; "No status" is 0) comes first and only while it holds an item. Then: + * every column in order (`status`), every option in order (`sel`), the iterations items name + * and the current one ascending (`iter`), or the distinct values by code point (`assignee` and + * `label`, an item in each of its own; `milestone`; `repo`, by id). An unknown key is one group. + */ +export function groupRows(rows: readonly BoardRow[], by: string, spec: BoardSpec, now: number): RowGroup[] { + const field = fieldOfKey(spec.fields, by) + const keysOf = (r: BoardRow): (string | number | null)[] => { + if (by === 'status') return [r.placement.col === 0 ? null : r.placement.col] + if (by === 'assignee') return r.item.assignees.length > 0 ? [...new Set(r.item.assignees)] : [null] + if (by === 'label') return r.item.labels.length > 0 ? [...new Set(r.item.labels)] : [null] + if (by === 'milestone') return [r.item.milestone] + if (by === 'repo') return [r.item.repoId] + const v = field === undefined ? undefined : r.placement.fields[String(field.id)] + return [v === undefined ? null : v] + } + let order: (string | number)[] + if (by === 'status') order = spec.columns.map((c) => c.id) + else if (field?.type === 'sel') order = (field.options ?? []).map((o) => o.id) + else if (field?.type === 'iter' || ['assignee', 'label', 'milestone', 'repo'].includes(by)) { + const present = new Set() + for (const r of rows) for (const k of keysOf(r)) if (k !== null) present.add(k) + if (field !== undefined) { + const cur = iterationAt(field, now) + if (cur !== null) present.add(cur) + order = [...present].sort((a, b) => (a as number) - (b as number)) + } else order = [...present].sort((a, b) => compareStrings(String(a), String(b))) + } else return [{ key: null, items: rows.map((r) => r.item.id) }] + const groups = new Map([[null, []], ...order.map((k): [string | number, string[]] => [k, []])]) + for (const r of rows) for (const k of keysOf(r)) groups.get(k)?.push(r.item.id) + const empty = groups.get(null) as string[] + const head: RowGroup[] = empty.length > 0 ? [{ key: by === 'status' ? 0 : null, items: empty }] : [] + return [...head, ...order.map((k) => ({ key: k, items: groups.get(k) as string[] }))] +} + +/** A row's sort value under `key` (no `-`); undefined when it has none (sorted last either way). */ +function sortValue(r: BoardRow, key: string, spec: BoardSpec): string | number | undefined { + switch (key) { + case 'title': + return r.item.title.toLowerCase() + case 'number': + return r.item.number + case 'created': + return r.item.createdAt + case 'status': { + const i = spec.columns.findIndex((c) => c.id === r.placement.col) + return i < 0 ? undefined : i + } + case 'repo': + return (r.item.repo ?? r.item.repoId).toLowerCase() + case 'author': + return r.item.author + case 'milestone': + return r.item.milestone?.toLowerCase() + default: { + const field = fieldOfKey(spec.fields, key) + const v = field === undefined ? undefined : r.placement.fields[String(field.id)] + if (field === undefined || v === undefined) return undefined + if (field.type === 'sel') return (field.options ?? []).findIndex((o) => o.id === v) + return field.type === 'text' ? String(v).toLowerCase() : v + } + } +} + +/** + * `rows` in a view's `sort` (absent or `rank`: the column order, §2.6): by the key, `-` for + * descending; rows without a value last in both directions; ties by (rank, item id). + */ +export function sortRows(rows: readonly BoardRow[], sort: string | undefined, spec: BoardSpec): BoardRow[] { + const desc = sort?.startsWith('-') === true + const key = sort === undefined ? 'rank' : desc ? sort.slice(1) : sort + const tie = (a: BoardRow, b: BoardRow) => byRank(a.placement, b.placement) + if (key === 'rank') return [...rows].sort((a, b) => (desc ? -tie(a, b) : tie(a, b))) + return [...rows].sort((a, b) => { + const x = sortValue(a, key, spec) + const y = sortValue(b, key, spec) + if (x === undefined || y === undefined) return x === y ? tie(a, b) : x === undefined ? 1 : -1 + const c = compare(x, y) + return c !== 0 ? (desc ? -c : c) : tie(a, b) + }) +} + +/** The number field a view sums (§4.5): the first `num` field of its `cols`, or with no `cols` the spec's first; null for none. */ +export function sumFieldOf(spec: BoardSpec, view: BoardView | null): number | null { + const keys = view?.cols ?? spec.fields.map((f) => `f${f.id}`) + for (const k of keys) { + const f = fieldOfKey(spec.fields, k) + if (f?.type === 'num') return f.id + } + return null +} + +/** A group's totals: its item count and the sum of a number field (null with none). */ +export interface Totals { + readonly count: number + readonly sum: number | null +} + +/** `rows`' count and the sum of number field `sumField`'s values (in `rows`' order). */ +export function totals(rows: readonly BoardRow[], sumField: number | null): Totals { + if (sumField === null) return { count: rows.length, sum: null } + let sum = 0 + for (const r of rows) { + const v = r.placement.fields[String(sumField)] + if (typeof v === 'number') sum += v + } + return { count: rows.length, sum } +} + +/** A status column's totals (§4.5) and its WIP limit (null: none); `over` when the count passes it. */ +export interface ColumnTotals extends Totals { + readonly id: number + readonly wip: number | null + readonly over: boolean +} + +/** Every status column's totals for `rows` (as {@link groupRows} by `status` groups them). */ +export function columnTotals(rows: readonly BoardRow[], spec: BoardSpec, sumField: number | null): ColumnTotals[] { + const byId = new Map(rows.map((r) => [r.item.id, r])) + return groupRows(rows, 'status', spec, 0).map((g) => { + const t = totals( + g.items.map((id) => byId.get(id) as BoardRow), + sumField, + ) + const wip = spec.columns.find((c) => c.id === g.key)?.wip ?? null + return { id: g.key as number, ...t, wip, over: wip !== null && t.count > wip } + }) +} + +/** An iteration's progress (§4.5): items and points, all and done. Points are null without a points field. */ +export interface IterationProgress { + readonly total: number + readonly done: number + readonly points: number | null + readonly donePoints: number | null +} + +/** + * Progress of iteration `k` of field `fieldId` over `rows`: the rows whose value is `k`; done is + * in the Done column, or closed or merged. + */ +export function iterationProgress(rows: readonly BoardRow[], spec: BoardSpec, fieldId: number, k: number, pointsField: number | null): IterationProgress { + const inIter = rows.filter((r) => r.placement.fields[String(fieldId)] === k) + const done = inIter.filter((r) => (spec.done !== 0 && r.placement.col === spec.done) || r.item.state !== 'open') + const all = totals(inIter, pointsField) + const fin = totals(done, pointsField) + return { total: all.count, done: fin.count, points: all.sum, donePoints: fin.sum } +} diff --git a/forge-web/lib/rules/conformance.test.ts b/forge-web/lib/rules/conformance.test.ts index f6495296a..5b870f372 100644 --- a/forge-web/lib/rules/conformance.test.ts +++ b/forge-web/lib/rules/conformance.test.ts @@ -1218,7 +1218,9 @@ describe('FORGE_RULES conformance vectors', () => { const isPrivate = (v: Vector) => isMembersGit(v) || ['private_', 'mixed_doc_', 'named_envelope', 'named_artifact', 'converted_repo_', 'seal_off_marker', 'env_snapshot', 'key_letter', 'access_notice', 'branch_key', 'bot_post', 'bot_push'].some((p) => v.case.startsWith(p)) - const v2Vectors = vectors.filter((v) => v.rules === 'v2' && !isPrivate(v)) + // boards (`board_*`, boards.md) run in `./boards.conformance.test.ts` + const isBoard = (v: Vector) => v.case.startsWith('board_') + const v2Vectors = vectors.filter((v) => v.rules === 'v2' && !isPrivate(v) && !isBoard(v)) const privateVectors = vectors.filter(isPrivate) it('loads the full vector corpus', () => { @@ -1226,7 +1228,7 @@ describe('FORGE_RULES conformance vectors', () => { expect(v2Vectors.length).toBeGreaterThanOrEqual(110) expect(privateVectors.length).toBeGreaterThanOrEqual(138) expect(vectors.filter((v) => v.case === 'branch_key').length).toBeGreaterThanOrEqual(59) - expect(base.length + v2Vectors.length + privateVectors.length).toBe(vectors.length) + expect(base.length + v2Vectors.length + privateVectors.length + vectors.filter(isBoard).length).toBe(vectors.length) // every members-git case is present (forge-core `members_git::conformance` runs all five) for (const c of MEMBERS_GIT_CASES) expect(vectors.filter((v) => v.case === c).length, c).toBeGreaterThanOrEqual(5) expect(vectors.filter(isMembersGit).length).toBeGreaterThanOrEqual(98) diff --git a/forge-web/lib/rules/index.ts b/forge-web/lib/rules/index.ts index 397a9672f..8567ba5d1 100644 --- a/forge-web/lib/rules/index.ts +++ b/forge-web/lib/rules/index.ts @@ -46,6 +46,8 @@ export { } from './releaseProvenance' export { refHistory, type Contains, type RefEvent, type RefEventKind } from './refHistory' export { overlayTree } from './overlay' +// Boards (docs/design/boards.md): spec, rank, fold, query, iteration and view rules +export * as boards from './boards' // FORGE_RULES_V2: the forge-v2 membership, event-fold, pack and numbering rules export * as v2 from './v2' export { FORGE_RULES_V2 } from './v2' diff --git a/forge-web/lib/rules/search-terms.ts b/forge-web/lib/rules/search-terms.ts new file mode 100644 index 000000000..f4f4ab8dc --- /dev/null +++ b/forge-web/lib/rules/search-terms.ts @@ -0,0 +1,42 @@ +/** + * The search box's tokenizer and free-text terms, shared by the Issues and Pull requests lists + * (`lib/view/issue-query.ts`, which re-exports both) and the board query (`./boards`, design + * `boards.md` §4.4). Pure, so the rules can use them without the view layer's DPNS reads. + * forge-core `rules::search::{tokens, search_terms}` is the Rust half (vectors `search_*`). + */ + +/** Split `text` into tokens, keeping `"quoted phrases"` (and `label:"two words"`) whole. */ +export function searchTokens(text: string): string[] { + const out: string[] = [] + const re = /(\S*?"[^"]*"\S*|\S+)/g + for (const m of text.matchAll(re)) out.push(m[0]) + return out +} + +/** One free-text search term: a word or a phrase, and whether a row must not hold it. */ +export interface SearchTerm { + readonly text: string + /** `-word` or `-"a phrase"` (QW3-018); a `-` inside quotes (`"-x"`) is literal. */ + readonly not: boolean +} + +/** + * The free text's search terms (QW-021): a `"quoted phrase"` is one term, spaces and all, and + * any other word is one term; lowercased, quotes never part of a term. A leading `-` outside + * quotes negates the term (QW3-018); a lone `-` is a word. + */ +export function searchTerms(text: string): SearchTerm[] { + const out: SearchTerm[] = [] + for (const m of text.toLowerCase().matchAll(/(-?)"([^"]*)"|(\S+)/g)) { + if (m[2] !== undefined) { + const phrase = m[2].trim() + if (phrase !== '') out.push({ text: phrase, not: m[1] === '-' }) + continue + } + const word = (m[3] ?? '').replace(/"/g, '').trim() + if (word === '') continue + const not = word.length > 1 && word.startsWith('-') + out.push({ text: not ? word.slice(1) : word, not }) + } + return out +} diff --git a/forge-web/lib/view/issue-query.ts b/forge-web/lib/view/issue-query.ts index 2233a1795..4753b1233 100644 --- a/forge-web/lib/view/issue-query.ts +++ b/forge-web/lib/view/issue-query.ts @@ -28,6 +28,7 @@ import type { CloseReason } from '../rules/transition' import { displayDpnsName, looksLikeDpnsName } from './dpns' import { plural } from './format' import { isIdentityId } from '../utils' +import { searchTerms, searchTokens, type SearchTerm } from '../rules/search-terms' export type IssueStateFilter = 'open' | 'closed' | 'all' export type IssueSort = 'newest' | 'oldest' | 'comments' @@ -337,18 +338,12 @@ export function pastLastPage(page: number, matching: number | null, pageSize: nu return page > last ? last : null } -/** Split `text` into tokens, keeping `"quoted phrases"` (and `label:"two words"`) whole. */ -function tokens(text: string): string[] { - const out: string[] = [] - const re = /(\S*?"[^"]*"\S*|\S+)/g - for (const m of text.matchAll(re)) out.push(m[0]) - return out -} +const tokens = searchTokens const unquote = (s: string): string => s.replace(/"/g, '') -/** The search box's tokens, as every qualifier parser reads them (quoted phrases whole). */ -export const searchTokens = tokens +/** The search box's tokens, as every qualifier parser reads them (quoted phrases whole); see `../rules/search-terms`. */ +export { searchTokens } /** * The qualifiers this parser applies (the rest of GitHub's are known by name below and @@ -678,30 +673,5 @@ export function searchText(q: IssueListQuery): string { return parts.join(' ') } -/** One free-text search term: a word or a phrase, and whether a row must not hold it. */ -export interface SearchTerm { - readonly text: string - /** `-word` or `-"a phrase"` (QW3-018); a `-` inside quotes (`"-x"`) is literal. */ - readonly not: boolean -} - -/** - * The free text's search terms (QW-021): a `"quoted phrase"` is one term, spaces and all, and - * any other word is one term; lowercased, quotes never part of a term. A leading `-` outside - * quotes negates the term (QW3-018); a lone `-` is a word. - */ -export function searchTerms(text: string): SearchTerm[] { - const out: SearchTerm[] = [] - for (const m of text.toLowerCase().matchAll(/(-?)"([^"]*)"|(\S+)/g)) { - if (m[2] !== undefined) { - const phrase = m[2].trim() - if (phrase !== '') out.push({ text: phrase, not: m[1] === '-' }) - continue - } - const word = (m[3] ?? '').replace(/"/g, '').trim() - if (word === '') continue - const not = word.length > 1 && word.startsWith('-') - out.push({ text: not ? word.slice(1) : word, not }) - } - return out -} +/** The free text's terms (`../rules/search-terms`, shared with the board query). */ +export { searchTerms, type SearchTerm } From fe0f61679168ca2eb1e5b2734752f5e318624824 Mon Sep 17 00:00:00 2001 From: pasta Date: Tue, 27 Oct 2026 21:13:50 +0000 Subject: [PATCH 03/26] feat(web): board data layer (reads, writes, sealing, polling) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The forge-web layer the board pages build on (docs/design/boards.md): - reads (lib/repo/boards.ts): a repo's boards (newest revision per key, deleted dropped), one board with every card (card.recent), the 20 s poll (>= and merged by $id), an item's boards for its sidebar (card.onItem, same-owner homes only) and its placement there - items (lib/repo/board-items.ts): the fold's BoardItem facts from the Issues/PRs list indexes: open items, closed ones from the transition feed newest first (exact resume, ties past a page, auto-archive window or 200 most recent per source repo, loadOlderClosed), card-named items in any repo, placeholders for private items - writes (lib/repo/board-writes.ts): create/save/close/delete boards, card writes over a fresh read of the definition and the item's newest card, own document found among raw rows; move (rank before an item, re-rank refusal), re-rank, add/archive/remove, next iteration, quick add; role-gated (board r=1, card r 1-2 in rules/roles.ts) - private repos: board/card sealed into enc v0x01 (lib/private/board.ts, TLV tags 32-36, private-repos.md §4.6) with 49 sealed_board vectors from an independent Python reference (tools/private-repos-vectors/boards.py); the Rust rules harness skips the case until forge-core reads it - costs: estimated board/card entries and priceBoardWrites - hooks/use-board.ts: useBoards, useBoard (polling while visible, definition re-read on focus, optimistic cards with rollback), useItemBoards Co-Authored-By: Claude Opus 5.5 --- crates/forge-core/src/rules.rs | 3 + docs/design/boards.md | 10 +- docs/security/private-repos.md | 26 +- .../vectors/sealed_board__open_board.json | 37 + .../sealed_board__open_board_epoch1.json | 42 ++ ..._board__open_board_moved_to_other_key.json | 34 + .../vectors/sealed_board__open_card.json | 39 ++ .../sealed_board__open_card_empty.json | 35 + .../sealed_board__open_card_enc_as_board.json | 34 + ...board__open_card_moved_to_other_board.json | 35 + ..._board__open_card_moved_to_other_item.json | 35 + .../vectors/sealed_board__open_no_epoch.json | 34 + .../vectors/sealed_board__open_no_key.json | 38 + .../sealed_board__open_other_owner.json | 34 + ...aled_board__open_plaintext_beside_enc.json | 33 + ...ealed_board__open_private_without_enc.json | 32 + .../vectors/sealed_board__open_short_enc.json | 33 + ...rd__open_superseded_epoch_still_opens.json | 42 ++ ...led_board__open_tlv_board_tag_in_card.json | 34 + ...ed_board__open_tlv_board_without_spec.json | 33 + .../sealed_board__open_tlv_col_two_bytes.json | 34 + ..._board__open_tlv_content_tag_in_board.json | 33 + ...led_board__open_tlv_empty_rank_absent.json | 37 + ...led_board__open_tlv_extension_skipped.json | 37 + .../sealed_board__open_tlv_out_of_order.json | 34 + ...ed_board__open_tlv_rank_trailing_zero.json | 34 + .../sealed_board__open_tlv_repeated.json | 34 + .../sealed_board__open_tlv_truncated.json | 33 + ...rd__open_under_burned_epoch_by_member.json | 49 ++ ..._under_burned_epoch_by_removed_member.json | 43 ++ .../vectors/sealed_board__open_version_3.json | 34 + .../vectors/sealed_board__seal_board.json | 27 + .../sealed_board__seal_board_epoch1.json | 27 + .../sealed_board__seal_board_key_max.json | 27 + .../sealed_board__seal_board_key_zero.json | 25 + ...ealed_board__seal_board_name_63_chars.json | 27 + ...ealed_board__seal_board_name_64_chars.json | 25 + .../sealed_board__seal_board_name_blank.json | 25 + ...sealed_board__seal_board_name_control.json | 25 + ...led_board__seal_board_spec_4096_bytes.json | 27 + ...led_board__seal_board_spec_4097_bytes.json | 25 + .../sealed_board__seal_board_spec_empty.json | 25 + ...sealed_board__seal_board_unicode_name.json | 27 + .../vectors/sealed_board__seal_card.json | 29 + .../sealed_board__seal_card_col_256.json | 25 + .../sealed_board__seal_card_col_zero.json | 27 + .../sealed_board__seal_card_empty.json | 25 + ...ed_board__seal_card_fields_2048_bytes.json | 27 + ...ed_board__seal_card_fields_2049_bytes.json | 25 + .../sealed_board__seal_card_rank_63.json | 27 + .../sealed_board__seal_card_rank_64.json | 25 + ...d_board__seal_card_rank_trailing_zero.json | 25 + forge-web/hooks/use-board.test.tsx | 148 ++++ forge-web/hooks/use-board.ts | 561 +++++++++++++++ .../lib/private/board.conformance.test.ts | 122 ++++ forge-web/lib/private/board.ts | 323 +++++++++ forge-web/lib/private/index.ts | 20 +- forge-web/lib/private/testing.ts | 12 + forge-web/lib/repo/board-items.test.ts | 216 ++++++ forge-web/lib/repo/board-items.ts | 512 ++++++++++++++ forge-web/lib/repo/board-writes.ts | 657 ++++++++++++++++++ forge-web/lib/repo/boards.test.ts | 468 +++++++++++++ forge-web/lib/repo/boards.ts | 418 +++++++++++ forge-web/lib/repo/index.ts | 78 +++ forge-web/lib/repo/issue-index.ts | 13 + forge-web/lib/repo/pull-index.ts | 15 + forge-web/lib/rules/conformance.test.ts | 5 +- forge-web/lib/rules/roles.test.ts | 9 + forge-web/lib/rules/roles.ts | 26 +- forge-web/lib/sdk/cost.test.ts | 23 + forge-web/lib/sdk/cost.ts | 49 +- forge-web/lib/sdk/index.ts | 1 + tools/private-repos-vectors/boards.py | 243 +++++++ 73 files changed, 5499 insertions(+), 12 deletions(-) create mode 100644 forge-contracts/vectors/sealed_board__open_board.json create mode 100644 forge-contracts/vectors/sealed_board__open_board_epoch1.json create mode 100644 forge-contracts/vectors/sealed_board__open_board_moved_to_other_key.json create mode 100644 forge-contracts/vectors/sealed_board__open_card.json create mode 100644 forge-contracts/vectors/sealed_board__open_card_empty.json create mode 100644 forge-contracts/vectors/sealed_board__open_card_enc_as_board.json create mode 100644 forge-contracts/vectors/sealed_board__open_card_moved_to_other_board.json create mode 100644 forge-contracts/vectors/sealed_board__open_card_moved_to_other_item.json create mode 100644 forge-contracts/vectors/sealed_board__open_no_epoch.json create mode 100644 forge-contracts/vectors/sealed_board__open_no_key.json create mode 100644 forge-contracts/vectors/sealed_board__open_other_owner.json create mode 100644 forge-contracts/vectors/sealed_board__open_plaintext_beside_enc.json create mode 100644 forge-contracts/vectors/sealed_board__open_private_without_enc.json create mode 100644 forge-contracts/vectors/sealed_board__open_short_enc.json create mode 100644 forge-contracts/vectors/sealed_board__open_superseded_epoch_still_opens.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_board_tag_in_card.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_board_without_spec.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_col_two_bytes.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_content_tag_in_board.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_empty_rank_absent.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_extension_skipped.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_out_of_order.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_rank_trailing_zero.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_repeated.json create mode 100644 forge-contracts/vectors/sealed_board__open_tlv_truncated.json create mode 100644 forge-contracts/vectors/sealed_board__open_under_burned_epoch_by_member.json create mode 100644 forge-contracts/vectors/sealed_board__open_under_burned_epoch_by_removed_member.json create mode 100644 forge-contracts/vectors/sealed_board__open_version_3.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_epoch1.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_key_max.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_key_zero.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_name_63_chars.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_name_64_chars.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_name_blank.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_name_control.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_spec_4096_bytes.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_spec_4097_bytes.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_spec_empty.json create mode 100644 forge-contracts/vectors/sealed_board__seal_board_unicode_name.json create mode 100644 forge-contracts/vectors/sealed_board__seal_card.json create mode 100644 forge-contracts/vectors/sealed_board__seal_card_col_256.json create mode 100644 forge-contracts/vectors/sealed_board__seal_card_col_zero.json create mode 100644 forge-contracts/vectors/sealed_board__seal_card_empty.json create mode 100644 forge-contracts/vectors/sealed_board__seal_card_fields_2048_bytes.json create mode 100644 forge-contracts/vectors/sealed_board__seal_card_fields_2049_bytes.json create mode 100644 forge-contracts/vectors/sealed_board__seal_card_rank_63.json create mode 100644 forge-contracts/vectors/sealed_board__seal_card_rank_64.json create mode 100644 forge-contracts/vectors/sealed_board__seal_card_rank_trailing_zero.json create mode 100644 forge-web/hooks/use-board.test.tsx create mode 100644 forge-web/hooks/use-board.ts create mode 100644 forge-web/lib/private/board.conformance.test.ts create mode 100644 forge-web/lib/private/board.ts create mode 100644 forge-web/lib/repo/board-items.test.ts create mode 100644 forge-web/lib/repo/board-items.ts create mode 100644 forge-web/lib/repo/board-writes.ts create mode 100644 forge-web/lib/repo/boards.test.ts create mode 100644 forge-web/lib/repo/boards.ts create mode 100644 tools/private-repos-vectors/boards.py diff --git a/crates/forge-core/src/rules.rs b/crates/forge-core/src/rules.rs index 0c16a7a86..afee38dc8 100644 --- a/crates/forge-core/src/rules.rs +++ b/crates/forge-core/src/rules.rs @@ -3887,6 +3887,9 @@ mod tests { || v.case == crate::private::branch_key::conformance::CASE || v.case == crate::private::members_check::CASE || v.case == "seal_off_marker" + // a private repository's sealed boards and cards: forge-web + // `lib/private/board.conformance.test.ts` runs them; no Rust reader yet + || v.case == "sealed_board" { continue; } diff --git a/docs/design/boards.md b/docs/design/boards.md index 1ca055157..5642711f1 100644 --- a/docs/design/boards.md +++ b/docs/design/boards.md @@ -76,6 +76,8 @@ Its column: An open item may sit in Done (a team that marks work done before closing). A board without a Done column applies rule 2 and 3 only. +**Which closed items a reader reads.** A source's open items are read whole; its closed and merged ones from the repository's state changes newest first, until the auto-archive window ends (older ones are archived unless a card keeps them, and the items cards name are read by id anyway), or, with `arch` 0, until the 200 most recently closed of that source **repository** (all its sources together) are found; "Show older" (and a view asking for `is:archived`) reads on. + **Auto-archive** (`arch`, days, 0 = off): let `closedAt` be the `$createdAt` of the item's latest transition into closed or merged (the transition that made its `sum mod 16` closed or merged). A closed or merged item whose newest card is older than `closedAt` (or which has none) is archived once `now ≥ closedAt + arch` days. `now` is an explicit input of the fold (the vectors pin it). Reopening never clears a card's archived state (as on GitHub). **Archived** items (auto or by a card's state) are hidden unless the view asks for them (`is:archived`). A **removed** item is off the board even if a source matches it; adding it again writes an active card. **Order within a column** is by rank (§2.6), ascending; a view may sort by a field instead (§4). @@ -158,7 +160,9 @@ Indexes: unique `onItem (item, repoId, board, $ownerId)` (one card per member pe A private repository's boards and cards are sealed with the repository key under the current epoch, with the private-repos per-document framing (`docs/security/private-repos.md` §4.4): new `docType`s `board` and `card`, bound to `u32(key)` and `u32(board) ‖ item (32 B)` respectively, so a sealed payload cannot be moved to another board or item. Readers of a private repo see nothing; the keys, `state` and the item ids are all that is plaintext. -**What a private board still shows.** `item` is plaintext, immutable and indexed, so a card in a private planning repository that names a *public* repository's issue publishes "private repository R tracks owner/name#12" (and which member wrote it). Clients confirm before writing such a cross-repository card from a private home repo. A public repository's members-only boards (the members key, `enc` v0x03) are possible with this schema and left to a later client. +The payload encoding (TLV tags 32–36, padding, the read order) is `private-repos.md` §4.6, pinned by the `sealed_board__*` vectors. A version other than `0x01` reads as unreadable, not malformed, so a later client's members-only boards stay listed. + +**What a private board still shows.** `item` is plaintext, immutable and indexed, so a card in a private planning repository that names a *public* repository's issue publishes "private repository R tracks owner/name#12" (and which member wrote it). Clients confirm before writing such a cross-repository card from a private home repo (the web refuses the write until the caller passes the confirmation: `crossRepoCardNeedsConfirm`, `BoardWriteError` `cross-repo`). A public repository's members-only boards (the members key, `enc` v0x03) are possible with this schema and left to a later client. --- @@ -225,7 +229,7 @@ Clicking a card opens a side panel: title, state, body (markdown), labels, assig ### 5.6 On an issue or pull request -The sidebar's "Boards" section lists the boards it is on whose home is the item's repository or another repository of the same owner (`card.onItem` with `item ==` the item, filtered by home repo; a stranger's board naming the issue never shows), with its status and fields (editable), and "Add to board" for that repository's other boards. +The sidebar's "Boards" section lists the boards it is on whose home is the item's repository or another repository of the same owner (`card.onItem` with `item ==` the item, filtered by home repo; a stranger's board naming the issue never shows), with its status and fields (editable), and "Add to board" for that repository's other boards. Another repository of the owner that is private is left out: its boards are sealed with a key the item's page does not hold. ### 5.7 Liveness @@ -241,7 +245,7 @@ An open board polls `card.recent` for cards with `$updatedAt >=` its last read ( ## 7. Costs -From the measured model (`forge-web/lib/sdk/cost.ts`): a board definition ≈ 0.0015 DASH to create, ≈ 0.0002 to edit; a member's first card for an item ≈ 0.0005, every later move or field change of it ≈ 0.00003. Sources, Done, auto-archive and views cost nothing. +From the measured model (`forge-web/lib/sdk/cost.ts`): a board definition ≈ 0.0015 DASH to create, ≈ 0.0002 to edit; a member's first card for an item ≈ 0.0005, every later move or field change of it ≈ 0.00003. Sources, Done, auto-archive and views cost nothing. Until a network carries the types these are **estimates** (`board` and `card` in `BASE_CREDITS` and `REPLACE_BASE_BY_TYPE`, scaled from the passkey vault's measured create and replace); `priceBoardWrites(creates, replaces)` prices a multi-write action (a re-rank, "move to the next iteration", a bulk archive) before it is signed. ## 8. Limits diff --git a/docs/security/private-repos.md b/docs/security/private-repos.md index b51c54cdf..a1fa5bea5 100644 --- a/docs/security/private-repos.md +++ b/docs/security/private-repos.md @@ -230,14 +230,15 @@ The plaintext is a sequence of records `tag(u8) ‖ len(u16) ‖ value`. No JSON | 25 | a letter's recipient identity id, **repeatable**, consecutive, in slot order | bytes | `enc` v0x04 only (§4.1) | exactly 32 B each | | 27 | the salt of the document's OID blinds | bytes | `enc` **v0x03** only, beside 22, 23 or 24 and present exactly when one of them is (§19.1); reserved everywhere else | exactly 32 B | | 29 | a letter's role group: `0x01` Maintainers, `0x02` Writers and maintainers; at most once, after the tag-25 records | one byte | `enc` v0x04 only (§17.7) | exactly 1 B, value 1 or 2 | -| 64 | padding | zero bytes | members-only and specific-people documents (§4.1) | skipped | +| 32–36 | a board's `name` (32) and `spec` (33); a card's `col` (34), `rank` (35) and `f` (36) | see §4.6 | `board` and `card` only (UPDATE-3) | §4.6 | +| 64 | padding | zero bytes | members-only and specific-people documents (§4.1); sealed releases, boards and cards (§16.2, §4.6) | skipped | | 65 | seal-off marker | bytes | interpreted in `config` only; skipped in other kinds | 30 B fresh, 34 B start-over; §18.5 | **Strictness** (any violation is `Malformed`): - Records are in strictly ascending tag order, except that consecutive tag-7 records repeat, and so do consecutive tag-25 records in a letter; any other repeated tag is malformed (two padding records included, `mixed_doc_open__pad_twice_refused`). - A record whose declared `len` runs past the end of the plaintext, or fewer than 3 trailing bytes after the last complete record, is malformed. There are no padding bytes outside records: padding is the tag-64 record of §4.1, which, as an extension record, comes after every other record. -- Tags 22–63 are **reserved**: a record with one is malformed. Three exceptions are defined: **tags 25 and 29** are fields of `enc` v0x04 only (in v0x01 and v0x03 they are still reserved, `mixed_doc_open__recipient_tag_refused`, `mixed_doc_open__group_tag_refused`; in a letter tag 29 is one byte, 1 or 2, at most once, after the recipients, `named_envelope_open__group_*`), and tags **22–24 and 27** are fields of `enc` v0x03 members-only ref updates, PRs and head updates (§19): in v0x01, v0x04 and every other kind they stay reserved (`sealed_ref__open_v01_blind_tags_reserved`, `mixed_doc_open__blind_tags_reserved`), and a client from before §19 refuses such a document as malformed instead of folding its blinds as commits (DESIGN S5 V5). An event carries a value (15), a head (24), or both. Tags 64–255 are **extension** tags: a reader skips them (forward compatibility), except tag 65 in a `config`, the seal-off marker (§18.5). Tag 64 is the padding record. Unknown tag-65 values in configs are retained so their epoch still supplies a boundary. (Tags 16–21 were reserved before §16; they are release-only, so in every other kind they are still malformed, as "not listed for the kind" below.) +- Tags 22–63 are **reserved**: a record with one is malformed. Three exceptions are defined: **tags 25 and 29** are fields of `enc` v0x04 only (in v0x01 and v0x03 they are still reserved, `mixed_doc_open__recipient_tag_refused`, `mixed_doc_open__group_tag_refused`; in a letter tag 29 is one byte, 1 or 2, at most once, after the recipients, `named_envelope_open__group_*`), and tags **22–24 and 27** are fields of `enc` v0x03 members-only ref updates, PRs and head updates (§19): in v0x01, v0x04 and every other kind they stay reserved (`sealed_ref__open_v01_blind_tags_reserved`, `mixed_doc_open__blind_tags_reserved`), and a client from before §19 refuses such a document as malformed instead of folding its blinds as commits (DESIGN S5 V5). An event carries a value (15), a head (24), or both. Tags 64–255 are **extension** tags: a reader skips them (forward compatibility), except tag 65 in a `config`, the seal-off marker (§18.5). Tag 64 is the padding record. Unknown tag-65 values in configs are retained so their epoch still supplies a boundary. (Tags 16–21 were reserved before §16; they are release-only, so in every other kind they are still malformed, as "not listed for the kind" below.) Likewise tags 32–36 are the board's and the card's (§4.6) and malformed in every other kind. - A tag not listed for the document's kind (tag 3 in an issue, say) is malformed. Tags 11 and 12 are allowed only in a config with `e ≥ 1` (never epoch 0); tag 11's only value is the one byte `0x01`. A **burned** config (tag 11) carries `prevEpoch` but neither `prevEpochKey` nor `skipEpochKey`: its key may sit with someone who never held the key below it. - Every UTF-8 value must be valid UTF-8, within the cap above, and non-empty unless the cap says otherwise; a zero-length record for a field with `minLength 1` counts as absent. Fixed-size tags must be exactly their size. - Required fields by kind: issue/patch `title`; comment `body`; event `eventValue` (an event without a value is not sealed, see §7), or in `enc` v0x03 a head (24) instead (a members-only PR's head update, §19.4); refUpdate/protectedRefUpdate `refName`; every config with `e ≥ 1`, anchor or not, `prevEpoch`, and unless burned `prevEpochKey` (neither is allowed when `e = 0`): any config of an epoch can become its anchor when an earlier one's author stops being a maintainer (§5.3), and it must then still chain to the previous epoch, so a writer copies the anchor's whole chain link (`prevEpoch`, `prevEpochKey`, `skipEpochKey`, the burned flag) into every later config of the epoch; review and epoch-0 config have none. An empty plaintext is therefore valid only for a review or an epoch-0 non-anchor config. @@ -264,6 +265,25 @@ AD = "dash-forge/v2/doc" ‖ 0x00 ‖ enc[0] ‖ repoId(32) ‖ $ownerId(32) ‖ `oidf(x) = u8(len(x)) ‖ x`. Binding `repoId`, `$ownerId`, `epoch` and the type means a ciphertext lifted from one document cannot be replayed as another: not by an outsider into a new comment in the same repo (different `$ownerId`), not into another repo, not under another type or epoch. `$ownerId` is safe to bind because none of these types is transferable; making one transferable would be a breaking change to this design. The ref-update binding ties the hidden name to the visible tip, so a stored `enc` cannot be re-used to name a different ref for the same OID. A board's or a card's binding is its immutable keys, so a sealed payload cannot be moved to another board or item; both are mutable, and a member's edit re-seals the whole payload under the repository's current epoch (a card is one document per member, item and board, so a replace is its only way to change). The document's `$id`, `$createdAt` and `$createdAtBlockHeight` are not bound (unknown at encryption time). +### 4.6 Boards and cards (UPDATE-3) + +A private repository's `board` and `card` documents ([boards.md](../design/boards.md) §3.3) seal their content into `enc` **v0x01** under the repository's current write epoch, with the AD of §4.4 (`docType` `board`, `bind = u32(key)`; `docType` `card`, `bind = u32(board) ‖ item (32)`). Both types are mutable, one document per member, and every save re-seals the whole payload under the epoch current then (a replace sets `enc`, `epoch` and the plaintext `state` and `r`). `enc` caps: 5120 bytes for a board, 2560 for a card (forge-meta `board.enc` / `card.enc` `maxItems`), so 5091 and 2531 bytes of TLV. + +| tag | field | type | in | cap (the plaintext schema's) | +|---|---|---|---|---| +| 32 | `name` | UTF-8 | board, **required** | 1–63 chars, ≤ 252 B, no control character, at least one character that is not white space | +| 33 | `spec` | UTF-8 (the definition's JSON, boards.md §2.7) | board, **required** | 1–4096 B | +| 34 | `col` | one byte, 0–255 | card | exactly 1 B | +| 35 | `rank` | ASCII | card | 1–63 B, `^[0-9A-Za-z]*[1-9A-Za-z]$` | +| 36 | `f` | UTF-8 (the field values' JSON) | card | 1–2048 B | +| 64 | padding | zero bytes | both | the writer pads the TLV to a multiple of 32 bytes within the cap, as a release does (§16.2); readers skip it | + +The rules of §4.3 apply as written: records strictly ascending and none repeated; a tag 1–63 not listed for the kind (a card's tag in a board, tag 2 anywhere here) is malformed; 64–255 are skipped; a zero-length record of a text field counts as absent (so a board missing tag 32 or 33 is malformed); every value within its cap and valid UTF-8. A card may carry no record at all but the padding (an item archived or removed before it was ever placed). The TLV does not judge the JSON of `spec` and `f`: the board rules do, exactly as for a public board (a definition they refuse reads as a board with no definition; field values they drop read as none). + +**Reading** (in order): a document with `enc` that also carries a plaintext `name` / `spec` (board) or `col` / `rank` / `f` (card), with no `enc`, with no u32 `epoch`, or with an `enc` shorter than 29 bytes is `Malformed` (skipped, as every malformed document is); an `enc[0]` other than `0x01` is `Unreadable(UnknownVersion)` (a later client's, such as a public repository's members-only board in `enc` v0x03, boards.md §3.3: listed, never malformed); then `NoEpoch`, `NoKey`, AES-GCM (`BadTag`: the AD binds the repository, the signer, the epoch, the type and the board's key or the card's board and item, so a payload copied to another board, item, member or type fails), the TLV (`Malformed`), and the burned clause of §8.2 (`Late` for a document under a burned epoch whose signer is not a current member). The height part of the late-content rule does not apply: both types are member-gated at consensus on every create and replace, as a member `event` is. A board that does not open reads with no name or definition; a card that does not open keeps its plaintext `state` with no column, rank or fields (unknown, not empty: a writer applies its change to the newest card it can open). In a repository made public (§18) a sealed board or card is opened with the published keys; any other public repository's sealed one (a later client's members-only board) reads as unreadable. Neither is dropped, so newest-wins never brings an older revision back; and a writer finds its own document among the raw rows, so one it skips as malformed is still the one it replaces. + +Vectors `sealed_board__seal_*` and `sealed_board__open_*` (`tools/private-repos-vectors/boards.py`, an independent Python reference over this section; forge-web `lib/private/board.conformance.test.ts`; forge-core has no reader yet and its rules harness skips the case). + ### 4.5 Ref-name hashing, and the hash check on read Private: `refNameHash = HMAC-SHA256(K_ref,e, refName)` with `e` the epoch the update is written under; `patch.baseRefNameHash` and `sourceRefNameHash` likewise under the patch's epoch. Public: `sha256(refName)` (unchanged). @@ -513,6 +533,8 @@ New vector cases in `forge-contracts/vectors/` with `"rules": "v2"`, one file pe **`private_release_seal__*` / `private_release_open__*`**: sealed releases, listed in §16.7. +**`sealed_board__seal_*` / `sealed_board__open_*`**: a private repository's boards and cards, §4.6 (seal: the padded TLV, the AD and `enc` under the fixed inputs, or the writer's refusal; open: what a reader makes of a stored document, every failure of §4.6's order). + **`mixed_doc_seal__*` / `mixed_doc_open__*`** (members-only, `enc` v0x03; the fixed inputs above, `vis: "public"`): a comment on `targetId = 0x33×32` with body `members-only: the fix is in sec/cve-1` under `K_0` and the fixed nonce gives `K_obj = 4faf51f6930dfb44ded0de72f22d0bd0233a50c420b375ece2ce3edc56fb6958`, `COMMIT_obj = f9a7fa2b8dc201ec7c98681cdcfcfdd62d0c8514308e08b3254c75e528853e9f`, the padded TLV `0200256d656d626572732d6f6e6c793a207468652066697820697320696e207365632f6376652d31400015` followed by 21 zero bytes (64 B), and `enc` (125 B) `03000102030405060708090a0bf9a7fa2b8dc201ec7c98681cdcfcfdd62d0c8514308e08b3254c75e528853e9f68c2c84f9892eab0fdb7a611874cf68f179a64d1f255e203d2fcd039a43f1e5e4427ffea6920a5296635807834ce89db33640789703539675c630fe4e0e9e440fa0941eba61eeb6f2957e4f93ebbccfe`. The seal cases cover an issue, a review, an inline comment, a body at the v0x03 room (no padding record fits), an empty review (one bucket), an unpadded event, and the writer's refusals (a private header, a config, a body one byte over, a field not of the kind). The open cases: `member`, `outsider_placeholder` (no key: `NoKey`), `no_lane` (`NoEpoch`), `commit_mismatch`, `body_tampered` (`BadTag`), `forged_after_reveal_refused`, `moved_to_other_target`, `v01_relabelled_refused`, `v01_byte_relabelled_as_v03` (`CommitMismatch`), `v03_in_private_member` (readable, D38), `v03_too_short`, `pad_roundtrip`, `pad_mid_bucket`, `pad_twice_refused`, `pad_before_content_refused`, `recipient_tag_refused`, `blind_tags_reserved` (tag 22), `reserved_tag_23`, `reserved_tag_24`, `reserved_tag_27`, `late`, `v04_public` and `v04_private` (`Unreadable(Letter)`), `config_anchor_public`. **`oid_blind__*`, `sealed_ref__*`, `sealed_patch__*`** (members-only branches and pull requests, §19; `tools/private-repos-vectors/members_git.py`): the blind and its check; S5's PR scenarios in blind space (rule C across a rotation, a mismatched head update, a re-blinded commit that counts for no one); sealing and opening members-only ref updates (create, update, force, delete, protected, SHA-256 width, epoch 1) with every malformed shape and the blind alerts; the member fold's input over public and members-only updates of one name (S5 V1, V1b, V1c); members-only PRs from members-only and public sources, head updates, and their refusals. **`members_pack_plan__*`, `publish_guard__*`** are the git helper's (Rust only, §19.5, §19.6). diff --git a/forge-contracts/vectors/sealed_board__open_board.json b/forge-contracts/vectors/sealed_board__open_board.json new file mode 100644 index 000000000..8b0928c1d --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_board.json @@ -0,0 +1,37 @@ +{ + "name": "open_board", + "description": "a sealed board opens under K_0 to its name and definition.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df789b274eea479160eb2cfbec2fbba79e8a330954a9e8700f356020378f2350e347a9d8bd0f55aac03fe2ae2265e98dfa589874658be2f70d3a8102d8736fdb4c99f93726ec567354e3eb4cf7685f5b3950e9c00e6a81460d91e36cde8ada3ad90c548e031d6e78adaa21612b6862e4008ef93596fbe90429874f25150568ec0e65" + } + }, + "expected": { + "status": "readable", + "fields": { + "name": "Roadmap", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + } +} diff --git a/forge-contracts/vectors/sealed_board__open_board_epoch1.json b/forge-contracts/vectors/sealed_board__open_board_epoch1.json new file mode 100644 index 000000000..6f6a12087 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_board_epoch1.json @@ -0,0 +1,42 @@ +{ + "name": "open_board_epoch1", + "description": "a board sealed under epoch 1 opens with K_1.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "1": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + }, + "1": { + "id": "723e4415b140d11aae49ab4d7cbf0e3f418bb90092a5ab040d47602af4ba5a86", + "height": 1000 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 1, + "plaintext": false, + "enc": "01000102030405060708090a0bf6b9c40c7ba5b252a436a4cb9e96caa8704c39c480f0b41453c060256b136e03f7b379e6e39a1009d28adb1b426b75caef9efb7b0a350effcc3b561ea101230a9bd159c631199f28bdccde8822b545fc1cb5cdf13893f701c0a0271eb85ab07cf9c1c7ee3cd57420ec2330ba92c188a7d2d77afd8712107516ce80db327fa3bade35dd1731e53a6240182aaa50563d11" + } + }, + "expected": { + "status": "readable", + "fields": { + "name": "Roadmap", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + } +} diff --git a/forge-contracts/vectors/sealed_board__open_board_moved_to_other_key.json b/forge-contracts/vectors/sealed_board__open_board_moved_to_other_key.json new file mode 100644 index 000000000..aa8d5a4eb --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_board_moved_to_other_key.json @@ -0,0 +1,34 @@ +{ + "name": "open_board_moved_to_other_key", + "description": "a board's enc copied under another key fails the tag.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 8, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df789b274eea479160eb2cfbec2fbba79e8a330954a9e8700f356020378f2350e347a9d8bd0f55aac03fe2ae2265e98dfa589874658be2f70d3a8102d8736fdb4c99f93726ec567354e3eb4cf7685f5b3950e9c00e6a81460d91e36cde8ada3ad90c548e031d6e78adaa21612b6862e4008ef93596fbe90429874f25150568ec0e65" + } + }, + "expected": { + "status": "unreadable", + "reason": "badTag" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_card.json b/forge-contracts/vectors/sealed_board__open_card.json new file mode 100644 index 000000000..79d893d0e --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_card.json @@ -0,0 +1,39 @@ +{ + "name": "open_card", + "description": "a sealed card opens to its column, rank and field values.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3c702ef0e032ed2f7b7c13c8e21adf348a603fc66ef20f875996825c999dc5f110d66cf89f88d3cc7f0518ed1c5e3f18" + } + }, + "expected": { + "status": "readable", + "fields": { + "col": 2, + "rank": "V", + "f": "{\"1\":3}" + } + } +} diff --git a/forge-contracts/vectors/sealed_board__open_card_empty.json b/forge-contracts/vectors/sealed_board__open_card_empty.json new file mode 100644 index 000000000..44ead2f3c --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_card_empty.json @@ -0,0 +1,35 @@ +{ + "name": "open_card_empty", + "description": "a card sealed with no fields opens to none.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b5e7032f2c332ec795f7c14b3c02bfd0eb91d7fc665f20f875996825c999dc5f1eb65592e9a7b12b6a67c5d40a1fb72bd" + } + }, + "expected": { + "status": "readable", + "fields": {} + } +} diff --git a/forge-contracts/vectors/sealed_board__open_card_enc_as_board.json b/forge-contracts/vectors/sealed_board__open_card_enc_as_board.json new file mode 100644 index 000000000..7a2c980f7 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_card_enc_as_board.json @@ -0,0 +1,34 @@ +{ + "name": "open_card_enc_as_board", + "description": "the AD binds the type: a card's enc stored as a board (key 7, the card's board) fails the tag.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3c702ef0e032ed2f7b7c13c8e21adf348a603fc66ef20f875996825c999dc5f110d66cf89f88d3cc7f0518ed1c5e3f18" + } + }, + "expected": { + "status": "unreadable", + "reason": "badTag" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_card_moved_to_other_board.json b/forge-contracts/vectors/sealed_board__open_card_moved_to_other_board.json new file mode 100644 index 000000000..f9e0dbbd5 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_card_moved_to_other_board.json @@ -0,0 +1,35 @@ +{ + "name": "open_card_moved_to_other_board", + "description": "the AD binds the board key: the enc copied to another board fails the tag.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 8, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3c702ef0e032ed2f7b7c13c8e21adf348a603fc66ef20f875996825c999dc5f110d66cf89f88d3cc7f0518ed1c5e3f18" + } + }, + "expected": { + "status": "unreadable", + "reason": "badTag" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_card_moved_to_other_item.json b/forge-contracts/vectors/sealed_board__open_card_moved_to_other_item.json new file mode 100644 index 000000000..4cd49fa8b --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_card_moved_to_other_item.json @@ -0,0 +1,35 @@ +{ + "name": "open_card_moved_to_other_item", + "description": "the AD binds the item: a card's enc copied onto a card for another item fails the tag.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4545454545454545454545454545454545454545454545454545454545454545", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3c702ef0e032ed2f7b7c13c8e21adf348a603fc66ef20f875996825c999dc5f110d66cf89f88d3cc7f0518ed1c5e3f18" + } + }, + "expected": { + "status": "unreadable", + "reason": "badTag" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_no_epoch.json b/forge-contracts/vectors/sealed_board__open_no_epoch.json new file mode 100644 index 000000000..1658a4f34 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_no_epoch.json @@ -0,0 +1,34 @@ +{ + "name": "open_no_epoch", + "description": "an epoch without an anchor does not exist: Unreadable(NoEpoch).", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "1": { + "id": "723e4415b140d11aae49ab4d7cbf0e3f418bb90092a5ab040d47602af4ba5a86", + "height": 1000 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df789b274eea479160eb2cfbec2fbba79e8a330954a9e8700f356020378f2350e347a9d8bd0f55aac03fe2ae2265e98dfa589874658be2f70d3a8102d8736fdb4c99f93726ec567354e3eb4cf7685f5b3950e9c00e6a81460d91e36cde8ada3ad90c548e031d6e78adaa21612b6862e4008ef93596fbe90429874f25150568ec0e65" + } + }, + "expected": { + "status": "unreadable", + "reason": "noEpoch" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_no_key.json b/forge-contracts/vectors/sealed_board__open_no_key.json new file mode 100644 index 000000000..0b5cec1d5 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_no_key.json @@ -0,0 +1,38 @@ +{ + "name": "open_no_key", + "description": "epoch 0 exists but the reader holds only K_1: Unreadable(NoKey).", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "1": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + }, + "1": { + "id": "723e4415b140d11aae49ab4d7cbf0e3f418bb90092a5ab040d47602af4ba5a86", + "height": 1000 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df789b274eea479160eb2cfbec2fbba79e8a330954a9e8700f356020378f2350e347a9d8bd0f55aac03fe2ae2265e98dfa589874658be2f70d3a8102d8736fdb4c99f93726ec567354e3eb4cf7685f5b3950e9c00e6a81460d91e36cde8ada3ad90c548e031d6e78adaa21612b6862e4008ef93596fbe90429874f25150568ec0e65" + } + }, + "expected": { + "status": "unreadable", + "reason": "noKey" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_other_owner.json b/forge-contracts/vectors/sealed_board__open_other_owner.json new file mode 100644 index 000000000..254a9600c --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_other_owner.json @@ -0,0 +1,34 @@ +{ + "name": "open_other_owner", + "description": "the AD binds $ownerId: another member cannot re-post this enc as theirs.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2323232323232323232323232323232323232323232323232323232323232323", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df789b274eea479160eb2cfbec2fbba79e8a330954a9e8700f356020378f2350e347a9d8bd0f55aac03fe2ae2265e98dfa589874658be2f70d3a8102d8736fdb4c99f93726ec567354e3eb4cf7685f5b3950e9c00e6a81460d91e36cde8ada3ad90c548e031d6e78adaa21612b6862e4008ef93596fbe90429874f25150568ec0e65" + } + }, + "expected": { + "status": "unreadable", + "reason": "badTag" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_plaintext_beside_enc.json b/forge-contracts/vectors/sealed_board__open_plaintext_beside_enc.json new file mode 100644 index 000000000..089a0a49b --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_plaintext_beside_enc.json @@ -0,0 +1,33 @@ +{ + "name": "open_plaintext_beside_enc", + "description": "a sealed board that also carries a plaintext name or spec is malformed (the contract's noPlain refuses it; a reader does too).", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": true, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df789b274eea479160eb2cfbec2fbba79e8a330954a9e8700f356020378f2350e347a9d8bd0f55aac03fe2ae2265e98dfa589874658be2f70d3a8102d8736fdb4c99f93726ec567354e3eb4cf7685f5b3950e9c00e6a81460d91e36cde8ada3ad90c548e031d6e78adaa21612b6862e4008ef93596fbe90429874f25150568ec0e65" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_private_without_enc.json b/forge-contracts/vectors/sealed_board__open_private_without_enc.json new file mode 100644 index 000000000..20c4e5b7d --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_private_without_enc.json @@ -0,0 +1,32 @@ +{ + "name": "open_private_without_enc", + "description": "a private repository's board without enc is malformed: its readers read only sealed boards.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_short_enc.json b/forge-contracts/vectors/sealed_board__open_short_enc.json new file mode 100644 index 000000000..0b8f6f99b --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_short_enc.json @@ -0,0 +1,33 @@ +{ + "name": "open_short_enc", + "description": "an enc shorter than 29 bytes is malformed before any key is used.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_superseded_epoch_still_opens.json b/forge-contracts/vectors/sealed_board__open_superseded_epoch_still_opens.json new file mode 100644 index 000000000..95a55f6ba --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_superseded_epoch_still_opens.json @@ -0,0 +1,42 @@ +{ + "name": "open_superseded_epoch_still_opens", + "description": "a board under superseded epoch 0 by a member removed since still opens: both types are member-gated at consensus on every write, so the height part of the late rule (§8.2) does not apply.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "1": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + }, + "1": { + "id": "723e4415b140d11aae49ab4d7cbf0e3f418bb90092a5ab040d47602af4ba5a86", + "height": 1000 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df789b274eea479160eb2cfbec2fbba79e8a330954a9e8700f356020378f2350e347a9d8bd0f55aac03fe2ae2265e98dfa589874658be2f70d3a8102d8736fdb4c99f93726ec567354e3eb4cf7685f5b3950e9c00e6a81460d91e36cde8ada3ad90c548e031d6e78adaa21612b6862e4008ef93596fbe90429874f25150568ec0e65" + } + }, + "expected": { + "status": "readable", + "fields": { + "name": "Roadmap", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_board_tag_in_card.json b/forge-contracts/vectors/sealed_board__open_tlv_board_tag_in_card.json new file mode 100644 index 000000000..721a56dae --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_board_tag_in_card.json @@ -0,0 +1,34 @@ +{ + "name": "open_tlv_board_tag_in_card", + "description": "a board's tag (33) in a card is malformed.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3f702d89be7e5e98ea29e6753e65d450bcfb37696e" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_board_without_spec.json b/forge-contracts/vectors/sealed_board__open_tlv_board_without_spec.json new file mode 100644 index 000000000..c8b954947 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_board_without_spec.json @@ -0,0 +1,33 @@ +{ + "name": "open_tlv_board_without_spec", + "description": "a board needs its definition.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c6d0e111c646bfbea8f0001fc34e70d9a" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_col_two_bytes.json b/forge-contracts/vectors/sealed_board__open_tlv_col_two_bytes.json new file mode 100644 index 000000000..3d3719f9a --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_col_two_bytes.json @@ -0,0 +1,34 @@ +{ + "name": "open_tlv_col_two_bytes", + "description": "a column is exactly one byte.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3c702df2c2d049d7d8a00cc02cff3001588c0bae5a" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_content_tag_in_board.json b/forge-contracts/vectors/sealed_board__open_tlv_content_tag_in_board.json new file mode 100644 index 000000000..25bf0cfd0 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_content_tag_in_board.json @@ -0,0 +1,33 @@ +{ + "name": "open_tlv_content_tag_in_board", + "description": "another kind's tag (2, a body) in a board is malformed.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b1c702e8ae332eb2b301d70dea15bdc0ec9665db047c83eab7bf5ed30ecf0ab82335a6bf0f0284735347076c86f0bac76e486f07947e2d43ff6e67b7db2c5fa0ccb3522c7b9b821769b50e37228d95b85ed673eb35e7340abb254ad205f0f6b11ae8c5525a00b59d6857eedc3da23e14654d057576e26f3e866277e357a863abd577bfdd067ea604e8b54bb3d810534a994" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_empty_rank_absent.json b/forge-contracts/vectors/sealed_board__open_tlv_empty_rank_absent.json new file mode 100644 index 000000000..d231cc4e7 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_empty_rank_absent.json @@ -0,0 +1,37 @@ +{ + "name": "open_tlv_empty_rank_absent", + "description": "a zero-length record of a field with minLength 1 counts as absent.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3c702ef3e032ecc89844c25f0db9e7c7dc54fba36c1b7d" + } + }, + "expected": { + "status": "readable", + "fields": { + "col": 1 + } + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_extension_skipped.json b/forge-contracts/vectors/sealed_board__open_tlv_extension_skipped.json new file mode 100644 index 000000000..027e7e410 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_extension_skipped.json @@ -0,0 +1,37 @@ +{ + "name": "open_tlv_extension_skipped", + "description": "tags 64-255 are extensions: skipped.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3c702ef38532e9153e0871c12c6981e59ce12f6bff6372fa76f91d46" + } + }, + "expected": { + "status": "readable", + "fields": { + "col": 1 + } + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_out_of_order.json b/forge-contracts/vectors/sealed_board__open_tlv_out_of_order.json new file mode 100644 index 000000000..17e023542 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_out_of_order.json @@ -0,0 +1,34 @@ +{ + "name": "open_tlv_out_of_order", + "description": "records out of order (rank before column) are malformed.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3d702ea4e132ed7b64759ab231e7476ee3c341ce6aee97a7" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_rank_trailing_zero.json b/forge-contracts/vectors/sealed_board__open_tlv_rank_trailing_zero.json new file mode 100644 index 000000000..1ec20a496 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_rank_trailing_zero.json @@ -0,0 +1,34 @@ +{ + "name": "open_tlv_rank_trailing_zero", + "description": "a sealed rank ending in 0 is malformed, as the plaintext pattern refuses it.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3d702da4f3e1405201c7d6dfcd41afa1c599137d50" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_repeated.json b/forge-contracts/vectors/sealed_board__open_tlv_repeated.json new file mode 100644 index 000000000..764f00654 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_repeated.json @@ -0,0 +1,34 @@ +{ + "name": "open_tlv_repeated", + "description": "a repeated record is malformed.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3c702ef0e132ed7a8689b616e00dc8cd9c80685cd8592f96" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_tlv_truncated.json b/forge-contracts/vectors/sealed_board__open_tlv_truncated.json new file mode 100644 index 000000000..44ad26ec8 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_tlv_truncated.json @@ -0,0 +1,33 @@ +{ + "name": "open_tlv_truncated", + "description": "a record running past the end is malformed.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3c95080ca7df70d3e0b8a52196338fe006d8126" + } + }, + "expected": { + "status": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_under_burned_epoch_by_member.json b/forge-contracts/vectors/sealed_board__open_under_burned_epoch_by_member.json new file mode 100644 index 000000000..d336f9392 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_under_burned_epoch_by_member.json @@ -0,0 +1,49 @@ +{ + "name": "open_under_burned_epoch_by_member", + "description": "the same card by a current member opens.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "1": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + }, + "1": { + "id": "723e4415b140d11aae49ab4d7cbf0e3f418bb90092a5ab040d47602af4ba5a86", + "height": 1000 + } + }, + "members": [ + "2222222222222222222222222222222222222222222222222222222222222222" + ], + "burned": [ + 1 + ] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 1, + "plaintext": false, + "enc": "01000102030405060708090a0bf4b9c25c37c4d769e14682b0ccdccae4610b48e8a993db7826ad0e56492935789535360f7d5587ddad23a7725e27e1bb" + } + }, + "expected": { + "status": "readable", + "fields": { + "col": 2, + "rank": "V", + "f": "{\"1\":3}" + } + } +} diff --git a/forge-contracts/vectors/sealed_board__open_under_burned_epoch_by_removed_member.json b/forge-contracts/vectors/sealed_board__open_under_burned_epoch_by_removed_member.json new file mode 100644 index 000000000..4282d7936 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_under_burned_epoch_by_removed_member.json @@ -0,0 +1,43 @@ +{ + "name": "open_under_burned_epoch_by_removed_member", + "description": "the burned clause of §8.2 still applies: a card under burned epoch 1 by someone who is no longer a member is Unreadable(Late).", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "1": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + }, + "1": { + "id": "723e4415b140d11aae49ab4d7cbf0e3f418bb90092a5ab040d47602af4ba5a86", + "height": 1000 + } + }, + "members": [], + "burned": [ + 1 + ] + }, + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444", + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 1, + "plaintext": false, + "enc": "01000102030405060708090a0bf4b9c25c37c4d769e14682b0ccdccae4610b48e8a993db7826ad0e56492935789535360f7d5587ddad23a7725e27e1bb" + } + }, + "expected": { + "status": "unreadable", + "reason": "late" + } +} diff --git a/forge-contracts/vectors/sealed_board__open_version_3.json b/forge-contracts/vectors/sealed_board__open_version_3.json new file mode 100644 index 000000000..f3ea173c7 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__open_version_3.json @@ -0,0 +1,34 @@ +{ + "name": "open_version_3", + "description": "a version other than 0x01 is a later client's (a public repository's members-only board): Unreadable(UnknownVersion), listed, never malformed.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "open", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "context": { + "keys": { + "0": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + }, + "anchors": { + "0": { + "id": "d8789e13d97af4e288d46cadf47488315539d063487e8855778ef2c990068926", + "height": 10 + } + }, + "members": [] + }, + "doc": { + "type": "board", + "key": 7, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "epoch": 0, + "plaintext": false, + "enc": "03000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df789b274eea479160eb2cfbec2fbba79e8a330954a9e8700f356020378f2350e347a9d8bd0f55aac03fe2ae2265e98dfa589874658be2f70d3a8102d8736fdb4c99f93726ec567354e3eb4cf7685f5b3950e9c00e6a81460d91e36cde8ada3ad90c548e031d6e78adaa21612b6862e4008ef93596fbe90429874f25150568ec0e65" + } + }, + "expected": { + "status": "unreadable", + "reason": "unknownVersion" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board.json b/forge-contracts/vectors/sealed_board__seal_board.json new file mode 100644 index 000000000..07d2d1132 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board.json @@ -0,0 +1,27 @@ +{ + "name": "seal_board", + "description": "a board under epoch 0: its name (TLV 32) and definition (33), padded to 32 bytes; the AD binds u32(key).", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": "Roadmap", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f6300011111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222200000000626f6172640000000007", + "tlv": "200007526f61646d61702100707b2276223a312c22636f6c756d6e73223a5b7b226964223a312c226e616d65223a22546f646f227d2c7b226964223a322c226e616d65223a22496e2070726f6772657373227d2c7b226964223a332c226e616d65223a22446f6e65227d5d2c22646566223a312c22646f6e65223a337d400000", + "enc": "01000102030405060708090a0b3e7028a0ac5388143e0c35b3b050df789b274eea479160eb2cfbec2fbba79e8a330954a9e8700f356020378f2350e347a9d8bd0f55aac03fe2ae2265e98dfa589874658be2f70d3a8102d8736fdb4c99f93726ec567354e3eb4cf7685f5b3950e9c00e6a81460d91e36cde8ada3ad90c548e031d6e78adaa21612b6862e4008ef93596fbe90429874f25150568ec0e65" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_epoch1.json b/forge-contracts/vectors/sealed_board__seal_board_epoch1.json new file mode 100644 index 000000000..856c60615 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_epoch1.json @@ -0,0 +1,27 @@ +{ + "name": "seal_board_epoch1", + "description": "the same board under epoch 1: another key, another epoch in the AD.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", + "epoch": 1, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": "Roadmap", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f6300011111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222200000001626f6172640000000007", + "tlv": "200007526f61646d61702100707b2276223a312c22636f6c756d6e73223a5b7b226964223a312c226e616d65223a22546f646f227d2c7b226964223a322c226e616d65223a22496e2070726f6772657373227d2c7b226964223a332c226e616d65223a22446f6e65227d5d2c22646566223a312c22646f6e65223a337d400000", + "enc": "01000102030405060708090a0bf6b9c40c7ba5b252a436a4cb9e96caa8704c39c480f0b41453c060256b136e03f7b379e6e39a1009d28adb1b426b75caef9efb7b0a350effcc3b561ea101230a9bd159c631199f28bdccde8822b545fc1cb5cdf13893f701c0a0271eb85ab07cf9c1c7ee3cd57420ec2330ba92c188a7d2d77afd8712107516ce80db327fa3bade35dd1731e53a6240182aaa50563d11" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_key_max.json b/forge-contracts/vectors/sealed_board__seal_board_key_max.json new file mode 100644 index 000000000..6b6d169e8 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_key_max.json @@ -0,0 +1,27 @@ +{ + "name": "seal_board_key_max", + "description": "the largest key, 4294967295.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 4294967295 + }, + "fields": { + "name": "Ops", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"}]}" + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f6300011111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222200000000626f61726400ffffffff", + "tlv": "2000034f707321002a7b2276223a312c22636f6c756d6e73223a5b7b226964223a312c226e616d65223a22546f646f227d5d7d40000a00000000000000000000", + "enc": "01000102030405060708090a0b3e702cbdb341cd79750736c5e211cc229b7e10aa109f61f47bacd927bbf4a1d32b511ca9bc204e722c7b78be6e0eae31bbe1af6d288cbb1d8bca005fdba1d836f54b660aca5699ac713627493305f0e8" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_key_zero.json b/forge-contracts/vectors/sealed_board__seal_board_key_zero.json new file mode 100644 index 000000000..d30b446b7 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_key_zero.json @@ -0,0 +1,25 @@ +{ + "name": "seal_board_key_zero", + "description": "key 0 is not a board key.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 0 + }, + "fields": { + "name": "Zero", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_name_63_chars.json b/forge-contracts/vectors/sealed_board__seal_board_name_63_chars.json new file mode 100644 index 000000000..3c70c9de0 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_name_63_chars.json @@ -0,0 +1,27 @@ +{ + "name": "seal_board_name_63_chars", + "description": "a name at its 63-character cap.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f6300011111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222200000000626f6172640000000007", + "tlv": "20003f6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e2100707b2276223a312c22636f6c756d6e73223a5b7b226964223a312c226e616d65223a22546f646f227d2c7b226964223a322c226e616d65223a22496e2070726f6772657373227d2c7b226964223a332c226e616d65223a22446f6e65227d5d2c22646566223a312c22646f6e65223a337d4000080000000000000000", + "enc": "01000102030405060708090a0b3e70109cad5c821731127addae459360d77311a80b9c61e937f8ec32f7f3ab9f7f0e5ee5bc2f4d79602f34846f04af7da8d2bc4346e8d573e5a46e31b5cfb658977721a9a8ae662283489b302aca4686ff7835b30f6b66fceb1fa0664704741fe283592de71341a0ae75ec848572c7481fd0100b7e30e0aa252e7479258649e00a67b63cbfdf48ade0cec965921838ac2f45a1d2485c767e00befa6ee6a67ed175ec6e8270aec9e03450bddf03fc9ce66c4d5e7db3d503d560c4e46d30559f32af7d62903e130943fc567d3d7746e1be" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_name_64_chars.json b/forge-contracts/vectors/sealed_board__seal_board_name_64_chars.json new file mode 100644 index 000000000..36d9fe00c --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_name_64_chars.json @@ -0,0 +1,25 @@ +{ + "name": "seal_board_name_64_chars", + "description": "a name over 63 characters is refused before sealing.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_name_blank.json b/forge-contracts/vectors/sealed_board__seal_board_name_blank.json new file mode 100644 index 000000000..97e2f167f --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_name_blank.json @@ -0,0 +1,25 @@ +{ + "name": "seal_board_name_blank", + "description": "a name of only white space is refused (the schema pattern needs a visible character).", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": " ", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_name_control.json b/forge-contracts/vectors/sealed_board__seal_board_name_control.json new file mode 100644 index 000000000..63e2253b3 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_name_control.json @@ -0,0 +1,25 @@ +{ + "name": "seal_board_name_control", + "description": "a name with a control character is refused.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": "a\tb", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_spec_4096_bytes.json b/forge-contracts/vectors/sealed_board__seal_board_spec_4096_bytes.json new file mode 100644 index 000000000..5f9bd7b3b --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_spec_4096_bytes.json @@ -0,0 +1,27 @@ +{ + "name": "seal_board_spec_4096_bytes", + "description": "a definition at its 4096-byte cap (the TLV does not judge its JSON: the board rules do).", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": "Big", + "spec": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f6300011111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222200000000626f6172640000000007", + "tlv": "200003426967211000787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878784000140000000000000000000000000000000000000000", + "enc": "01000102030405060708090a0b3e702cb0aa55cd695f046ccbb8538576c16507be1d8a77ff21eefa24e1e5bd89691848f3aa395b6f763922927912b96bbec4aa5550fec365f3b27827a3d9a04e816178d1a0ad3c2cd90ad26470d15192f26d23b8552945ffb10ebc3c054d2045f49a4c30bd511b8cb969fbde8026c4120ecc4a493464babc3c3b692367dc78f6526fbc2ba0d555a6eb94cc31914229b07507ea86124a6f6b1de4b834dab168cc2fe94bd62ab2d4fe6e12f48b59e08bf071171c36b6ed7ba518bc9c15482de74a6558453af589dbac67849bf671b613c58228dbf1828694a295b3d3f98b0ada7652c67205384291ab25c69ae87677a695ef32a579d40ae32ca1384431979a254a7705796be2f87bbaa8cba0f1bd96a7edcda9678f26df894267a4fc360f88d7572b843f5f649117c3d2ec33909979217d058add006370839afe0e61cf6ac55c1415db5bd22b97942fe569060f551bdc200b06f0c6c3da0c4317548c2c417449d29a18440caf0f600ac4141edb59496f81a54c98a60746b380b704e1a367941e1cfd31c0d04d3c4d5f76c805970464d81776212149ab122c7e42383c01d2c262f8fe4151ac495f67811f7f7a9d471d8f0d0e03d207f0781fea8f96d47f8c0f1ff41254989a08c1b42a43232fa840feaa434f124c2c4464f47960c98ae454efd86020d2417006cab626e68b5c17be872d4f3b5c401b64f5eb8f260c6327086f3566c17e0d4aa6d0be8d7c2d2fa27236e606df8b2c8ae85286927ea9a9c63c0750de1845bff3aec8c664fc6b2a7710d50c251e25a23852b3c2cfc725906e2853f22727ccc74dc091d370f083dd8aa82fef888930721048aec6ae5988e5089aec21887d8e562be838690c0bd5d93cbb42edebf99d41a0c56c1e3cc4a7ff0eacf99e2b5de52ce5687eb924ce781639c8967461ea6d2b3bce667289be355fd91e037175bcbfe7c71b06b466b3d19ffe7ee879a9e4f0c993d1ab5c19b43e07383c360e525b370bfd0bac884519329bda63c723c15d1c8611bbff6c102d1ecf009f244c92b7e12eb2d2ab2de6711d5d8419594d7e3223676df27866d4f5b17c53b8c2d18918fc861827f2502bc6425ed22d4f08c442a331adf1a23b1e3e901ca8e3eb312faec851e5a53a394d978dbb5791f4972da9bc7d800b4ecbeb0a8bd67f1a0e25ca503fc257271f77f07c6a38aca145bcaef49e6a39c028b8dda67dba79e39a73c494b6613ad5febbfc6ad8d5002b466f89ec2d20fb2a72d2c0771fc9f625895c071ba2a993135817596f9ef9e167ff1a8dc19eab1eacb072000d9c478bb54522da09b87368e90ccb926fb6769225e94e95ec8d40eaaa29e39801b2e0f3fc4a5ecb89bb0a5750e0a234ed95d6e5170dcd736b6894822a05a18a21d46a5e358c61ed2f47f8d15674a96befcceea342598ce918c41b2e04e229db0c421e269d173810f6d621f3881a05f081e9a8119378ce7e04aba48bde12eff397b82963e9b5a81fbd72cb5dd5d56b756e0d5be995aeedbc6c480f3ab63c85e80f1ea7b96a1c60f07178f5fd4f8764aa1166cb2742de0c49015cae1c1938bd8d2230c347e150456e68a872c7b81e5ed4cc607eb3adefb0c9f12edbf498ee77b50d33e3e9e6afa370cf9d9b1b3450bfc31214a15daeda5707eb7e1d38df89af671f29123e0446838e08c6479ce5cf6e0f447081e9a40b5f2aaffef45416ab6161605bda4b4087b4fca29d48e884388412db8c6135d3cf8319f85920e2c8cd08e0888a07c22a0167e61ad51938731c5a06f96ccab164e4cebf40d6a939e274bdb8b1a42c73f30678e7988425102c5a0eb7fe06cd9b921b271a77c97741783f6ddc9344b9335316e70df89897587d442410a57d05f464d9033db711d71d5d22c2379772843900992732e5b0e972dcf86c28662d3ba93b32716e5f8bf2378a1f0c7f29a653bc0194e0a08e8321a037de8bd1942ea6b6a06ae23969a255be92c5a99680cf42b8c07ae1c77bd74566d3a16ade67249a00e30844da98835b972cf62bda82e5f92962ccf796caa3b07195e3d493c3cf6a0ee0fc873eaaab7ab5c765024da886a1a1fe99d9e0799edac7544292cdc4bd5fcf082d7c0db2844431d20f6f06676fe5682b897b7a05b0d5e9353af171ccae07a0dec463998b596d317b6d20b27997c2569db42ef325e60f1a232c3466943a0e22b81a685a0af9684be39af8b43639007c8d894f7af22388429b17ba986cf6f07f6979f2a4eaeeb6367739b56c69b8abb1be8c92358a14057fff5deecd203b14c582b4e668dfa02853ec521e9fc6498dfdfac16d3c4be19508fad32ed7dbec23276cb7d52e3a34658d298fe9b5450d4fa5e4b38ca520428ba8c605e381d63e32e6c6ea12318ac0916a81223f9d28fd5ef5d7a55165fd55fb0f59adf4dbf02de85904cf1d3c6737b97b1228ff81e17de12e39d5e0354585efc9915f6d8a2dbfd77ed38a6d006eb98f6c889e12930e2d800cad94f0daa759bda0a61ccc9460fdd6a6d87da41484b359d2a8c0b7bdd22a5b0ba2b418d6ceea955bfb8e7d7a782e5fdf12aafaffe4c8a83e93f21232f085d23cd5294e065bbea7114fa6bd665876e6b3cedd406be8bab50c8ce0c6a5b0acd657ac47b08efd182610bd07c8ff74126dc360944151d015f629309cfba7adce894a7ee722ad12c9ca82e98a5df477b75d570811d1db5ddb58e4fc16b87ab00b6b74c2a5c56748c1a4759e607259de4109276ed95a7db08597282fcd390d860c0b47e4b611ca6ed8b894ca4940e8a0e9d7765e417a2ee3c6ba64d90783d8c851ad95c0ea2720a0dfce4a0fdeddb867b3f661878b42a50ca46663ad75234f710c75e6ebd150a13f54ca809a30dc9a032f577c26c24372910b83f8c7aa5042461c08a3f733d40eba001bc0b36dd48f87b24c0223d36e09c63d234c6b2d6ef6a7f34ef4167cf0287e76a37e1495f0e319b15692d3f38c6b2928640228f840ee391c59c8821f773509fc2b8f663864fe2e5f98c8a56c67c49775e4b268d655a0a273c75339bec841dd0427460bf00931da626369f7fed8feddbd0f9d25d9268733bfcb5915f6862958220de690090a2b7021c9d76323434152e3820d5a84bd7f208779642ac9f2e1bfb2ab00585970ee7b6fbaee3b8a21db864a8ee56cdd121248fe27b6f29a34947353c38b873fbda2994134f16cdf440ecfd01943bf3941b03ca45cd7d96db0217028eba720fe8bb37ec0067cf3988a2042d714cc10022858441f183d2abbc4bbb0df42399b8cfcb5a0cab05f1b937796917c686af48e3e5c3a63a637f7f440052d9d0e8b095a92f61a4ccb141d7d33d43923abfbc28ca80179494c12e2e2c00e3f6679ccaffca440e78ac740ca984d5909ef0078638c900e6a905911a59a4439f3a46dc41a348181f2f7657411ee761c53ad77218b67beef4dd72f8a53c4b28838872f2816dbf2c464d3422710581b0554728fa672ca2a74982b97fcc808ba8221ccb7a2b3e2691c7b8cfdf15c5a002762edeba9a5ca8dff2fd406458ade9f05ad54867f3b354f0c79001d05568bac25b30bc4b06c3ac12d5fd917d11e045cdeecbb0d36a702f933e57a9ff3c128696cb351bdd1aac5751c5ba0d10477f63f90ac4e1bb553a1f37a09904e49b1f0337be7ce315d74aa2f353eab8e5aa1823000ae3f6647ef9532c82173d104a7440e5eb76afbaf2d1bc594a0a1ea79917b0bef09532f0096c0a757f9a7656abc62c8b6175e0664a27fcb426ad494382609ca37b86f0f742a8be05905542b47470eeb427ae89d5d3af4c00262018f057ff2b984d66bafcfa43cc8abee4e15ec7a9f70894fb4553574d7963b9dae9fc13e126091d4fc1a98c85fe6c051d7ad1cd6fe0f604aab18cad2e85d71464733c9efdc7f4104931dd51f936bf422aaac19bae56b324e9453edbf45015a59454c5ff738bc3ba78b8a4f5f6af4743a501dc759c2623a7cc389b7defa29c9d67f103cc38660f0739aff954e566bee85a82e1afbc9159331a4956abd92b8f87c4203b91c7ed1fe4ee49d1b2e7d409abda8bf61defec98ff21d00b0f3c0fced3ef9f8535078d50b34083500ae7d57f4ca61a598f7075ca95a545560c39b1d905e921589d1ee7e7f8a240ee853ce001ba20b926c0a68b4a6ac79e177669bf3b078247bd575c6b3e641f74339d90cfec7a772b0c4210b73e48f712e088d59a62c490de2564b328b86566f21c8b099375c2eaa6afa914d0bbd0ce10383b5af3e34560c8413fe2e8b9e4bb00760be643a13874fe13952e73f8112246925e304dc7fdba0e11696b73fc5115463446cbaafc0289292468544014cb4d51c2efb37b631fd0bd6613ba86063680e82cccff91934c30cd65015cecc1e7583fd998f5a221738585c7d264a00e20f2f07914f5594bafba77d94de7e8b6fb68a2645373c1c1814b23b507eb56402a1a4cc849d3e88e2a92bb7aa217b82f1baa63423615b4060203777fadb829649171b6635399ebea8f786db358ffcd903f02cd2e38bbb907ada8e4b798d07e34c0f8030df6d8b8be53551e8d1863e7f74123eae66e1f598617418142e4b44751cd50bcc1fef9f47f0fa8099615439cd4cddc580fdd23419459f6f95cfaee98227e57332ad6a4a4e92b43f442a5087f19ba315db5e263b50cc592981293a7976ec6428cf2d48bf6770ad1f16a700fbd63fa42600f8f79cf0cfe99eeb11598770490b1b1bdf33b269dfe4c0ebb689e2be8694f90ef1b5a15b4559bab0081e7ddea63fa476a21932ff355a06964cde6ea135a005d5f85d6f396f05198e3496b7a5b37b79f634ecf08416fcce9575575b61fed1af00dbed2f119cb9e164582e738b9131c3d59d2af2f6a76c905f9e880b15892161dda3d7cd92a24e80264a3ed54c1f73c95c81b7143256d4c084bae8f5edfdeb8d1f83f4a42182c29338083e1679aec346597097c31b3198b989bd09dc9018bf10c1128cc033e1026e6f206c18972c1e81581ef6300977f2145f83095e2b9c931a348158106dd06667ab90cb57e791eca5a8c73bc7c4ddbda92e1364ce3ece58a6fc2444fd36a87d359b16a24c46b0715cc18f990b3752b83b82bf03471a1b16ab3a4065f35db3337613ea1dabc818ebf72d520d7738d2586dbdf704f27804c8fbcc84ba8e5771c328975bb6d23d7ddb8ce7c039d57a4e9d03d57516dcddef333aeef22d50e5eff63152e497540a97ac0f8b34e89a054a74bc94203909db67f3de81635e8b8b675e371c52065d2a62e60a799cbf40ce6a99d5db9aae2492142abbe9799497243c250539cc690aa0081712bc1ea7dbd9ab9f1d9dcedb1b86cf139736f7907b1d4f8ca5341770de1f2649bb904f812b437e0f7cc801de8ccbaaa9b88710b3b7c3d5857276cefb3af4ed17b9e817c0d4fc5bc0a2b540bc3496d4342abbc7e7ca799b9926459e8aceae395eadbeda4d29567ac8cb3ab4374c9a02529d15876d72167cad0e4d580fb318d6bee8eecef1bf402ae80b79835b8d86c48ae67ef30a77b359226501334b7347d44560b7f7bae34fb860d01fcb6bd53c34d6a007230675cb8acc7ce3139a76253e0a8e993ce920a6c4890ae5bfb8073d6cfdc47028950b593db02d2b675d68b013e33d66e27b59a488c0a0d17977164471bfc38e9bed592f2242ee2445e423631d2915be620b6560589bbfc85343e4d0421de6d439ba2554e9df906749ef5c9b0781e215609b854925e3a5c3df07b4a2b3563492eb43527cdd735c585ecb0278fd454a9e1489e5a5befa14b61b5964dedda2be1ebccf3b2ebf2b1f9f5745160aa8c4f9c299ef9cb52edf36db1ef2aaf205d723dd39662359243b4b0d781e014b84fa1851b527b0b7226731cf65fde28d94" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_spec_4097_bytes.json b/forge-contracts/vectors/sealed_board__seal_board_spec_4097_bytes.json new file mode 100644 index 000000000..d9a709a42 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_spec_4097_bytes.json @@ -0,0 +1,25 @@ +{ + "name": "seal_board_spec_4097_bytes", + "description": "a definition over 4096 bytes is refused.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": "Big", + "spec": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_spec_empty.json b/forge-contracts/vectors/sealed_board__seal_board_spec_empty.json new file mode 100644 index 000000000..922d2d6f4 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_spec_empty.json @@ -0,0 +1,25 @@ +{ + "name": "seal_board_spec_empty", + "description": "a board needs a definition.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": "Empty", + "spec": "" + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_board_unicode_name.json b/forge-contracts/vectors/sealed_board__seal_board_unicode_name.json new file mode 100644 index 000000000..edc16e54d --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_board_unicode_name.json @@ -0,0 +1,27 @@ +{ + "name": "seal_board_unicode_name", + "description": "a name of 11 characters and 13 bytes.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "board", + "key": 7 + }, + "fields": { + "name": "Sprint ✨ 12", + "spec": "{\"v\":1,\"columns\":[{\"id\":1,\"name\":\"Todo\"},{\"id\":2,\"name\":\"In progress\"},{\"id\":3,\"name\":\"Done\"}],\"def\":1,\"done\":3}" + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f6300011111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222200000000626f6172640000000007", + "tlv": "20000d537072696e7420e29ca82031322100707b2276223a312c22636f6c756d6e73223a5b7b226964223a312c226e616d65223a22546f646f227d2c7b226964223a322c226e616d65223a22496e2070726f6772657373227d2c7b226964223a332c226e616d65223a22446f6e65227d5d2c22646566223a312c22646f6e65223a337d40001a0000000000000000000000000000000000000000000000000000", + "enc": "01000102030405060708090a0b3e7022a1b34085172b5cf62f680bcc3c981d0fbd47842dbd68baa03ff6f1b09c7f1312b1893a017e6a6360db2d48af72abd9f0170ad2d479e4e87d73a083b152db233285fabb2539c450903e41c7099af87a3cb248224ea5b45abf6614517a07bfce1626a44406d6fb33c7c9963b9e172b981055297ae0fe756f333f70ca65ac1024b913d8b72dde93ecb449e93a51c80d7f92fe6a321713659cc04ca2c910b49d323483bd5499895b6fc40a8698d765" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_card.json b/forge-contracts/vectors/sealed_board__seal_card.json new file mode 100644 index 000000000..2d12bc398 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_card.json @@ -0,0 +1,29 @@ +{ + "name": "seal_card", + "description": "a card: column (TLV 34, one byte), rank (35) and field values (36); the AD binds u32(board) and the item id.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444" + }, + "fields": { + "col": 2, + "rank": "V", + "f": "{\"1\":3,\"2\":5}" + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f63000111111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222000000006361726400000000074444444444444444444444444444444444444444444444444444444444444444", + "tlv": "220001022300015624000d7b2231223a332c2232223a357d4000050000000000", + "enc": "01000102030405060708090a0b3c702ef0e032ed2f7b7c19c8e21adf348a315df447c83afa1996875c999dc5f1d8d144af701b281092db7a53cfc55ab7" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_card_col_256.json b/forge-contracts/vectors/sealed_board__seal_card_col_256.json new file mode 100644 index 000000000..414d2eb7d --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_card_col_256.json @@ -0,0 +1,25 @@ +{ + "name": "seal_card_col_256", + "description": "a column is 0-255.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444" + }, + "fields": { + "col": 256 + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_card_col_zero.json b/forge-contracts/vectors/sealed_board__seal_card_col_zero.json new file mode 100644 index 000000000..c30c61382 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_card_col_zero.json @@ -0,0 +1,27 @@ +{ + "name": "seal_card_col_zero", + "description": "column 0 (\"No status\") is written: one byte 0x00.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444" + }, + "fields": { + "col": 0 + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f63000111111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222000000006361726400000000074444444444444444444444444444444444444444444444444444444444444444", + "tlv": "2200010040001900000000000000000000000000000000000000000000000000", + "enc": "01000102030405060708090a0b3c702ef28332f5795f7c14b3c02bfd0eb91d7fc665f20f875996825c999dc5f1cdc6fbe870bd416e63c03804b7b16e3b" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_card_empty.json b/forge-contracts/vectors/sealed_board__seal_card_empty.json new file mode 100644 index 000000000..b62e129c5 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_card_empty.json @@ -0,0 +1,25 @@ +{ + "name": "seal_card_empty", + "description": "a card with nothing but its state (an archive or removal of an item never placed): only the padding record.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444" + }, + "fields": {} + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f63000111111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222000000006361726400000000074444444444444444444444444444444444444444444444444444444444444444", + "tlv": "40001d0000000000000000000000000000000000000000000000000000000000", + "enc": "01000102030405060708090a0b5e7032f2c332ec795f7c14b3c02bfd0eb91d7fc665f20f875996825c999dc5f1eb65592e9a7b12b6a67c5d40a1fb72bd" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_card_fields_2048_bytes.json b/forge-contracts/vectors/sealed_board__seal_card_fields_2048_bytes.json new file mode 100644 index 000000000..5b9bf3b7a --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_card_fields_2048_bytes.json @@ -0,0 +1,27 @@ +{ + "name": "seal_card_fields_2048_bytes", + "description": "field values at their 2048-byte cap.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444" + }, + "fields": { + "f": "{\"5\":\"tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt\"}" + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f63000111111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222000000006361726400000000074444444444444444444444444444444444444444444444444444444444444444", + "tlv": "2408007b2235223a22747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474747474227d40001a0000000000000000000000000000000000000000000000000000", + "enc": "01000102030405060708090a0b3a782f89e107ce437d0860c7b45f897acd690bb211867bf32de2f628ede9b185651444ffa63557637a352e9e751eb567b2c8a6595cf2cf69ffbe742bafd5ac428d6d74ddaca13020d506de687cdd5d9efe612fb4592549f3bd02b03009412c49f896403cb15d1780b565f7d28c2ac81e02c046453868b6b03037652f6bd074fa5e63b027acd959aae798c03d9d4e25bc790be68a1e46636711e8b438d6bd64c023e547da26bed8f2621ef88755ec87fc7d1b103abae177a914b090194421eb4669544936f985d7a06b8897fa7dba1fc98e24d7fd8e8a98ae99bfdff58706d67a5eca7e09344e9da729ca96e47a7baa99e33ea975d806ef20ad34483d9b9629467b097567eef477b6a4c7acfdb19aabe1c1a56b832ad3854e6ba8f03a0384db5b27883353689d1bcfdee03f9c95752d710986d10c6f7c8f96f2026dc366c9501819d757de279b9823e9650a035917d02c070afccacfd6004f1b5880204d7845de96144800a3036c06c81812d75545638da94094aa0b4abf8cbb08edaf6b981210f13dccdc413041537ac4099b0868d41b7a2d2d45a71e20724e34300ddece6ef4f24d5da045536b8d137376914b118301020fde0bfc7413e6839ad873800313f81e58949604cdb8264f2f23a44cf2a64f431e40204868f8756cc586e858e3d46c2cde4d7c0ac6ba2aea87501bb28b214337504c1768f9e7832a006f2b0463396acd720146aadcb281702123ae7e3aea0ad3872086e45e8a9e72a5a5ca300b5cd21449b3ffa2c4ca68f067267b1cd900291229ae345ebfcec3cb299c62245ffe2b2bc0cb41cc9ddf7cfc8fd186a423e384853c7e1c44a2caa25584e90496e02d8471825a27e434650007d9d530b74ee1e7f5914dacc9601230c8abf302a0f5922751e920e96472b528c2741a35c49a786de6612737c26a7e85b23953d5120f7d79b0b3ebcb170ab86abfdd93f272e475a5e8fcc59fdda75015b8320b34303a025e573b07f107a08449153e97d66fcb2fcd51108a1db7f3601c2112c30c9328409ebbed22bedea721ea7d115188155541723e2f6b61fe746ad8f9bd705fb4cedd8514f08a142bfe5c27ca4e52de214304c84eaf3da1fdae3712329c10a4efe73d23a2c45de9a93635419b81b75b9df89b21a5b0718c0742c7e70687da73160229c65c33ce5b2b137bfc706634a0ad49b0a2f8926635cc24b4d1aa71b675ef967fc898ba6d36d9f2b7f066d4d90c274a6385e0212cf7267edecc7b13c5fa2985500b17aea59f1f541b556392f5ed6bf31681cd92a712a0bc7e0c01904b87b9492ed605b47f64e500c79e63ba7a9e29e54299e0814ce6a625ef940dbeecfff04652c785b7065b5cecae38e199dae91b01c17f6764988e2609ad862dd8665239806de1234bf4dd5a78a567e3c0e2af4e5580e514c8172208ee25d7004e122a911b341cfada2dff841609fc8de5a41d9f74c27208a7a887d21ee3ff9bb4256fe5b9a413b17ec751d9d96779620157e599a2e1b060440336ba3089e40312abb566106cfc7d74f9f1438b68a61d6ac72b4ed200450d50a2101534b1812e3ccf4bed5c496264a47ecbb41252d8c06c72bfa1e3bcc5fd22d7f894e27bb9013fefe5eaa3af7cc3919717385cb3cf1e18ad51a2d65b0be7721134d385a36b13251e32084a8f8204ca4b90e9c36203487c8de5a8075326a3f2f8581aa76d6d6c57d6474c8bb8f0ae9144e48834881ed7806d39dfc38f15f4552ceec4c104ec84860bce260d6bea16d915347f10560af560c6bd68e8c2b34cdaa535ee78b1b4bda8207fff0a74eb9488291c205602bbf20ac1979e172b167bc57b4d743361d09f48b53f5f1aeb01f4949b547148281ca97109f868d50f31bb1ddb11512ece3b9b7e88350c952b3ee9bce57ed0f460246a2137a5373e7d625387fe3b8613007325aa5fb00d98ecac828f2dac3bd287dd9822aabaac66ee3565ae59b29ec9a59a8cc34eb4cc76edcb77db496adfad66d26b28960cef0448d6948f579b20fa27d68ee9f5256ec0fb9ac6afbc7d99efd89fcfc36602ecf08b32a6a776b9cb690e41a48aadadf295d5ec7592d6cb584e9ec1c8b153c304217001be88483dde03630a6b63e9642785777609bcd9e53936fd7dc0a20bacd2c86f958755613d77612cbe759bce5a91b822ff29ea03162f20386a9836022eb416645606f56447ef96f4b83a350c7081854376fe2f844e971bb69460fafc736575fea8e6e2ba3a7b35b96065b4a7bdb2809e3986180973f351e2c12c3718c98eb8ea64d3ac245fe05e1293ca4581f1f6cd613047ed9904f6df22dbd7e02f2b60bbd922363869812583e5b9490143a9e8bf80a92c4e87a4ca09ef8dda323eeacae61e3d86cc9d668d2e339124f152f9dba95d69f159f70355a1f8d7fc21e45508c311306b3bb5771e24f38ded71ed2235d9ec394989e3c59d53618621b3db72df86610c62b5836084921e9f02218c00a198fcd6ab55b1acaa10c0986cf1daaad471a81888bf55dea4ccbbb1de265707aeb814dac2e69957f7827176742253d31ea6f6f3e8c4a4329ffe1e3efc89de30d925420a57b2ab1d43aab16a547aeabfc2d14c67e4b6b90080eccaa9bca0da5ba04bbc82f1142a1cb10bc4f3781e61cf6c984d5ddc19fa253c90f7aba1c2854672eb2ea11ec5c68ee58651f87bbb515b041dddd751d754e8f01ab476bc076778cea9c96b44cda879926c7e55d24d052b62d55671bc899b2423c135018a00074be8ba1dc662d4b498c6454ce4ace5db7a524d7622efcab668d50b8fd4c45da199cce62b2cacd3c24603d2d1b46bbffa6d8b874ea900a86a6fa1792f437d0079eae7dd5cad3358c68c963cd0960f235b702ace4f7e9d078ff4cba65c4e4a1004affb3fd802b65a1ef8cb0facf7ffca347a5bab1671be455b341355168edf8b368c6e048850a51e36d209392fdb82804f75f971798d" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_card_fields_2049_bytes.json b/forge-contracts/vectors/sealed_board__seal_card_fields_2049_bytes.json new file mode 100644 index 000000000..6e2c6237f --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_card_fields_2049_bytes.json @@ -0,0 +1,25 @@ +{ + "name": "seal_card_fields_2049_bytes", + "description": "field values over 2048 bytes are refused.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444" + }, + "fields": { + "f": "{\"5\":\"ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt\"}" + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_card_rank_63.json b/forge-contracts/vectors/sealed_board__seal_card_rank_63.json new file mode 100644 index 000000000..537851da7 --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_card_rank_63.json @@ -0,0 +1,27 @@ +{ + "name": "seal_card_rank_63", + "description": "a rank at its 63-digit cap.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444" + }, + "fields": { + "rank": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + } + }, + "expected": { + "ad": "646173682d666f7267652f76322f646f63000111111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222000000006361726400000000074444444444444444444444444444444444444444444444444444444444444444", + "tlv": "23003f7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a40001b000000000000000000000000000000000000000000000000000000", + "enc": "01000102030405060708090a0b3d701088b948960325066ec9ba518774c36705bc1f8875fd23ecf826e3e7bf8b6b1a4af1a83b596d743b20907b10bb69bcc6a85752fcc167f1b07a25a1dba24c836340a9c3d54454a172aa1c08a929ea8a155bc02d513d87c976c4447d35583db194bc09639cfbe7d4790a3efce80415" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_card_rank_64.json b/forge-contracts/vectors/sealed_board__seal_card_rank_64.json new file mode 100644 index 000000000..6b3c0ddfe --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_card_rank_64.json @@ -0,0 +1,25 @@ +{ + "name": "seal_card_rank_64", + "description": "a rank over 63 digits is refused.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444" + }, + "fields": { + "rank": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-contracts/vectors/sealed_board__seal_card_rank_trailing_zero.json b/forge-contracts/vectors/sealed_board__seal_card_rank_trailing_zero.json new file mode 100644 index 000000000..b59d6fa3f --- /dev/null +++ b/forge-contracts/vectors/sealed_board__seal_card_rank_trailing_zero.json @@ -0,0 +1,25 @@ +{ + "name": "seal_card_rank_trailing_zero", + "description": "an explicit rank never ends in 0.", + "case": "sealed_board", + "rules": "v2", + "input": { + "op": "seal", + "repoId": "1111111111111111111111111111111111111111111111111111111111111111", + "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "epoch": 0, + "ownerId": "2222222222222222222222222222222222222222222222222222222222222222", + "nonce": "000102030405060708090a0b", + "doc": { + "type": "card", + "board": 7, + "item": "4444444444444444444444444444444444444444444444444444444444444444" + }, + "fields": { + "rank": "V0" + } + }, + "expected": { + "error": "malformed" + } +} diff --git a/forge-web/hooks/use-board.test.tsx b/forge-web/hooks/use-board.test.tsx new file mode 100644 index 000000000..f0645cd36 --- /dev/null +++ b/forge-web/hooks/use-board.test.tsx @@ -0,0 +1,148 @@ +// @vitest-environment jsdom +/** + * `useBoard` (`docs/design/boards.md` §5.2, §5.7): a move shows at once and is taken back with + * the reason when refused; a landed move is re-read by a poll at once, merged by `$id`; the + * 20 s poll reads only while the tab is visible. + */ +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { defaultSpec, type BoardItem, type CardDoc } from '@/lib/rules/boards' +import type { BoardItemSet, BoardRead, RepoRef } from '@/lib/repo' + +const HOME = 'H'.repeat(44) +const NOW = Date.UTC(2026, 9, 27) +const SPEC = defaultSpec(HOME, NOW) +const ITEM: BoardItem = { id: 'I'.repeat(44), number: 1, repoId: HOME, kind: 'issue', state: 'open', createdAt: NOW - 1000, closedAt: null, title: 'One', labels: [], assignees: [], milestone: null, author: 'me' } +const CARD: CardDoc = { id: 'c1', ownerId: 'me', updatedAt: 100, item: ITEM.id, col: 1, rank: null, f: null, state: 0 } + +const state = vi.hoisted(() => ({ + move: null as null | { resolve: (v: unknown) => void; reject: (e: unknown) => void }, + since: vi.fn(), + read: null as unknown, + // the SDK and the signer are stable across renders, as the app's are + sdk: {}, + signer: { identityId: 'me', network: 'devnet', getSigningKeyWif: () => 'W' }, +})) +vi.mock('./use-sdk', () => ({ useSdk: () => ({ sdk: state.sdk, ready: true, network: 'devnet' }) })) +vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ signer: state.signer }) })) +vi.mock('./use-repo-chrome', () => ({ useViewerRole: () => ({ role: 'triage', known: true, failed: false, retry: () => undefined }) })) +vi.mock('@/lib/repo', async (load) => ({ + ...(await load()), + readBoard: async () => state.read, + boardItemReader: () => ({}), + loadBoardItems: async (): Promise => ({ items: [ITEM], hidden: new Set(), missing: new Set(), partial: false, hasOlderClosed: false, walks: new Map() }), + addCardItems: async (_r: unknown, _i: unknown, set: BoardItemSet) => set, + readCardsSince: state.since, + moveCard: () => + new Promise((resolve, reject) => { + state.move = { resolve, reject } + }), +})) + +import { BOARD_POLL_MS, useBoard } from './use-board' +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const repo: RepoRef = { forge: { core: 'C', collab: 'L', community: 'M', meta: 'T', group: 'G' }, repoId: HOME, ownerId: 'me', name: 'repo', visibility: 'public' } +let host: HTMLDivElement +let root: Root +let view: ReturnType +function Probe() { + view = useBoard(repo, 7) + return null +} +const colOf = (): number | undefined => view.fold?.items.find((p) => p.id === ITEM.id)?.col + +beforeEach(async () => { + state.move = null + state.since.mockReset().mockResolvedValue([]) + const read: BoardRead = { + board: { key: 7, repoId: HOME, state: 'open', name: 'B', spec: SPEC, specError: null, sealed: false, newest: { id: 'b', ownerId: 'me', updatedAt: 1 }, revisions: [{ id: 'b', ownerId: 'me', updatedAt: 1 }] }, + cards: [CARD], + since: 100, + } + state.read = read + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + await act(async () => root.render()) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() + vi.useRealTimers() +}) + +describe('useBoard', () => { + it('loads, folds, and says what a triage member may do', () => { + expect(colOf()).toBe(1) + expect(view.can).toEqual({ place: true, edit: false }) + }) + + it('shows a move at once and takes it back with the reason when refused', async () => { + let done!: Promise + await act(async () => { + done = view.move({ id: ITEM.id, repoId: HOME }, { col: 2 }, [], null).catch((e: unknown) => e) + }) + expect(colOf()).toBe(2) + expect(view.pending.has(ITEM.id)).toBe(true) + await act(async () => { + state.move?.reject(new Error('refused by consensus')) + await done + }) + expect(colOf()).toBe(1) + expect(view.pending.size).toBe(0) + expect(view.refusal).toMatchObject({ items: [ITEM.id], message: expect.stringContaining('refused by consensus') }) + }) + + it('a landed move polls at once and keeps the landed card, merged by $id', async () => { + state.since.mockResolvedValue([{ ...CARD, updatedAt: 200, col: 2, rank: 'F' }, { ...CARD, updatedAt: 200, col: 2, rank: 'F' }]) + let done!: Promise + await act(async () => { + done = view.move({ id: ITEM.id, repoId: HOME }, { col: 2 }, [], null) + }) + await act(async () => { + state.move?.resolve({ card: CARD, created: false, result: {} }) + await done + }) + expect(state.since).toHaveBeenCalledWith(expect.anything(), repo, 7, 100) + expect(view.cards.filter((c) => c.id === 'c1')).toHaveLength(1) + expect(colOf()).toBe(2) + expect(view.pending.size).toBe(0) + }) + + it("keeps a landed move's card until a poll reads it", async () => { + let done!: Promise + await act(async () => { + done = view.move({ id: ITEM.id, repoId: HOME }, { col: 2 }, [], null) + }) + // the replica does not show it yet: the poll after the write reads nothing new + await act(async () => { + state.move?.resolve({ card: { ...CARD, col: 2, rank: 'F' }, created: false, result: {} }) + await done + }) + expect(colOf()).toBe(2) + expect(view.pending.size).toBe(0) + }) + + it('polls every 20 s while visible, and not while hidden', async () => { + vi.useFakeTimers() + await act(async () => root.render(null)) + await act(async () => root.render()) + await act(async () => { + await vi.runOnlyPendingTimersAsync() + }) + state.since.mockClear() + await act(async () => { + await vi.advanceTimersByTimeAsync(BOARD_POLL_MS) + }) + expect(state.since).toHaveBeenCalledTimes(1) + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' }) + await act(async () => { + await vi.advanceTimersByTimeAsync(BOARD_POLL_MS) + }) + expect(state.since).toHaveBeenCalledTimes(1) + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' }) + }) +}) diff --git a/forge-web/hooks/use-board.ts b/forge-web/hooks/use-board.ts new file mode 100644 index 000000000..5542682a7 --- /dev/null +++ b/forge-web/hooks/use-board.ts @@ -0,0 +1,561 @@ +'use client' + +/** + * Boards in React (`docs/design/boards.md`), on the data layer of `lib/repo/boards.ts`, + * `board-items.ts` and `board-writes.ts`: + * + * - {@link useBoards}: a repository's boards (open and closed), re-read after any board write + * this session made, with the viewer's {@link BoardCan} and `create`. + * - {@link useBoard}: one board: its definition, every card, its items and the fold (§2.4) at + * `now`. While the tab is visible it polls the cards changed since its last read every + * {@link BOARD_POLL_MS} (§5.7; `>=` and deduplicated by `$id`), reads the items new cards name, + * and re-reads the definition when the tab is shown or focused; `refresh` re-reads everything. + * Its writes apply at once (an optimistic card over the fold, §5.2), and are taken back with the + * reason ({@link BoardHookState.refusal}) when the write is refused; a landed write is re-read + * by the next poll, run at once. + * - {@link useItemBoards}: the boards an issue or PR is on, for its sidebar (§5.6), with its + * placement on each and the writes that change it there. + * + * Every write needs a signed-in viewer (`signer`) and the role the contract admits: + * {@link BoardCan.place} (maintainers, writers, triage) for cards, {@link BoardCan.edit} + * (maintainers, writers) for boards; a closed board is read-only. The UI offers only what these + * allow; the writes refuse the rest before signing (`BoardWriteError`, `RoleRefusedError`). + */ + +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' + +import { useAuth } from '@/contexts/auth-context' +import { useAsync, type AsyncState } from '@/hooks/use-async' +import { useViewerRole } from '@/hooks/use-repo-chrome' +import { useSdk } from '@/hooks/use-sdk' +import { + addCardItems, + addItems, + archiveItems, + assembleBoard, + boardItemReader, + boardWriteGeneration, + canEditBoards, + canPlaceCards, + cardsSince, + createBoard, + itemPlacement, + loadBoardItems, + loadOlderClosed, + mergeCards, + moveCard, + moveOpenToNextIteration, + nextIterationPlan, + patchedCard, + quickAddIssue, + rankBefore, + readBoard, + readBoardDefinition, + readBoards, + readCardsSince, + readItemCards, + removeItems, + repoContractIds, + repoKey, + rerankColumn, + saveBoard, + setBoardState, + subscribeBoardWrites, + unarchiveItems, + withItem, + writeCard, + type BoardCard, + type BoardChange, + type BoardItemSet, + type BoardState, + type BoardView, + type BoardWritten, + type BulkWritten, + type CardItem, + type CardPatch, + type CardWriteOptions, + type CardWritten, + type ItemBoard, + type MoveTarget, + type QuickAdded, + type RankedCard, + type RepoRef, +} from '@/lib/repo' +import { newestCards, type BoardFold, type BoardItem, type BoardSpec, type Placement } from '@/lib/rules/boards' +import type { Role } from '@/lib/rules/v2' +import type { WriteAuth } from '@/lib/sdk' +import { errorMessage } from '@/lib/utils' + +/** How often a visible board reads the cards changed since its last read (§5.7). */ +export const BOARD_POLL_MS = 20_000 +/** Showing or focusing the tab re-reads, but not sooner than this after the last read. */ +export const BOARD_FOCUS_THROTTLE_MS = 5_000 + +/** What the viewer may do here (§5.1). */ +export interface BoardCan { + /** Move, rank, set fields, add, archive, remove items (maintainers, writers, triage; signed in; the board open). */ + readonly place: boolean + /** Create, edit, close, delete boards and save views (maintainers, writers; signed in). */ + readonly edit: boolean +} + +function canOf(role: Role | null, signedIn: boolean, board: BoardView | null): BoardCan { + const open = board === null || board.state === 'open' + return { place: signedIn && open && canPlaceCards(role), edit: signedIn && canEditBoards(role) } +} + +/** + * `a` with the items, hidden and missing ids of `b` it lacks (its walks and flags kept): two reads + * of one board's items that may have crossed. + */ +function unionItems(a: BoardItemSet | null, b: BoardItemSet | null): BoardItemSet | null { + if (a === null || b === null) return a ?? b + const have = new Set(a.items.map((i) => i.id)) + return { + ...a, + items: [...a.items, ...b.items.filter((i) => !have.has(i.id))], + hidden: new Set([...a.hidden, ...b.hidden]), + missing: new Set([...a.missing, ...b.missing]), + } +} + +/** Re-render on every board write this session made to `repo` (none given: to any repository). */ +function useBoardWriteGeneration(repo?: RepoRef): number { + return useSyncExternalStore(subscribeBoardWrites, () => boardWriteGeneration(repo), () => 0) +} + +/** The signer and SDK a write needs, or the refusal a signed-out (or not yet connected) viewer gets. */ +function needWriter(sdk: ReturnType['sdk'], signer: WriteAuth | null): { sdk: NonNullable; signer: WriteAuth } { + // copy-lint-ignore: the action's own button is hidden for a signed-out viewer; this is the guard + if (sdk === null || signer === null) throw new Error('Sign in to change this board.') + return { sdk, signer } +} + +/** A repository's boards (open and closed; deleted left out), and what the viewer may do. */ +export function useBoards(repo: RepoRef): AsyncState & { + readonly role: Role | null + readonly can: BoardCan + /** Create a board (§2.1); its key is in the result. */ + readonly create: (input: { readonly name: string; readonly spec: BoardSpec; readonly intent?: string }) => Promise +} { + const { sdk, ready, network } = useSdk(repoContractIds(repo)) + const { signer } = useAuth() + const { role } = useViewerRole(repo) + const generation = useBoardWriteGeneration(repo) + const state = useAsync(() => readBoards(sdk!, repo), [ready, repoKey(repo), network, generation], { enabled: ready && sdk !== null }) + const create = useCallback( + (input: { readonly name: string; readonly spec: BoardSpec; readonly intent?: string }) => { + const w = needWriter(sdk, signer) + return createBoard(w.sdk, w.signer, repo, input) + }, + [sdk, signer, repo], + ) + return { ...state, role, can: canOf(role, signer !== null, null), create } +} + +/** A refused write, taken back (§5.2: the card goes back with the reason). */ +export interface BoardRefusalNote { + /** The items it was for. */ + readonly items: readonly string[] + readonly message: string + readonly error: unknown +} + +/** + * What {@link useBoard} returns. Its functions are made afresh each render (like `useAsync`'s + * data): call them from handlers, never list them in an effect's dependencies. + */ +export interface BoardHookState { + /** The board's definition (null until read, or when it has none: {@link notFound}). */ + readonly board: BoardView | null + /** Every card, every member's, with the pending writes' optimistic cards over them. */ + readonly cards: readonly BoardCard[] + readonly items: BoardItemSet | null + /** Where every item shows (§2.4), folded at {@link now}; null until read or when the definition did not open. */ + readonly fold: BoardFold | null + /** The fold's clock (moved on by every poll). */ + readonly now: number + readonly loading: boolean + readonly error: string | null + /** The board has no revision (a wrong key, or not visible yet). */ + readonly notFound: boolean + readonly role: Role | null + readonly can: BoardCan + /** Items with a write in flight (shown with their optimistic placement). */ + readonly pending: ReadonlySet + /** The last refused write, taken back; cleared by the next write or {@link dismissRefusal}. */ + readonly refusal: BoardRefusalNote | null + dismissRefusal(): void + /** Re-read the definition, every card and the items. */ + refresh(): void + /** Read the older closed items too (`is:archived`, "Show older"), when {@link BoardItemSet.hasOlderClosed}. */ + loadOlderClosed(): Promise + /** One card write (a column, a rank, field values, a state), over a fresh read of the item's newest card (§3.2). */ + write(item: CardItem, patch: CardPatch, opts?: CardWriteOptions): Promise + /** + * Drop `item` in `target` just before item `before` of `column` (the target column's cards in + * rank order, the moving card may be among them; null: at the bottom) (§5.2); refused with + * `re-rank` when no rank fits. + */ + move(item: CardItem, target: MoveTarget, column: readonly RankedCard[], before: string | null, opts?: CardWriteOptions): Promise + add(items: readonly CardItem[], col?: number, opts?: CardWriteOptions): Promise + archive(items: readonly CardItem[], opts?: CardWriteOptions): Promise + unarchive(items: readonly CardItem[], opts?: CardWriteOptions): Promise + remove(items: readonly CardItem[], opts?: CardWriteOptions): Promise + /** Re-rank a column (its cards in shown order): price it first with `planCardWrites` and `priceBoardWrites`. */ + rerank(items: readonly CardItem[], opts?: CardWriteOptions): Promise + /** Carry the current iteration's unfinished items of iteration field `fieldId` into the next (§5.4). */ + moveOpenToNextIteration(fieldId: number, opts?: CardWriteOptions): Promise + /** Quick add (§5.3): a new issue in the home repository (or `target`), placed in `col`. */ + quickAdd(input: { readonly title: string; readonly col: number; readonly column?: readonly RankedCard[]; readonly target?: RepoRef; readonly intent?: string; readonly confirmCrossRepo?: boolean }): Promise + /** Save the board's name or definition (views included). */ + save(change: BoardChange, opts?: { readonly intent?: string }): Promise + /** Open, close or delete the board. */ + setState(state: BoardState, opts?: { readonly intent?: string }): Promise +} + +interface Held { + readonly key: string + readonly board: BoardView | null + readonly cards: readonly BoardCard[] + readonly items: BoardItemSet | null + readonly since: number + readonly notFound: boolean +} + +/** An optimistic card's `$updatedAt`: newer than any read, so the fold takes it as the item's newest. */ +const PENDING_AT = Number.MAX_SAFE_INTEGER +/** A landed write's optimistic card is shown until a poll reads the card, or this long at most. */ +const LANDED_HOLD_MS = 60_000 + +/** An item's optimistic card: while its write is in flight, then until a poll reads what landed. */ +interface Pending { + readonly card: BoardCard + /** Which write set it (a later write on the item replaces it; an earlier one's end leaves it alone). */ + readonly token: number + /** The landed card document, and when it landed; null while the write is in flight. */ + readonly landed: { readonly id: string; readonly at: number } | null +} + +let tokens = 0 + +/** The card document each item's write landed in, from a write's outcome. */ +function landedOf(out: unknown): Map { + const done = new Map() + const one = (w: unknown): void => { + const card = (w as Partial | null)?.card + if (card != null) done.set(card.item, card.id) + } + one(out) + for (const w of (out as Partial | null)?.written ?? []) one(w) + return done +} + +/** Whether `held` already shows what `p` landed (the same document with the same content). */ +function caughtUp(p: Pending, held: readonly BoardCard[]): boolean { + if (p.landed === null) return false + if (Date.now() - p.landed.at > LANDED_HOLD_MS) return true + const id = p.landed.id + return held.some((c) => c.id === id && c.col === p.card.col && c.rank === p.card.rank && c.f === p.card.f && c.state === p.card.state) +} + +/** + * Board `key` of `repo` (see the module header). `options.label` names a repository on its + * items (`owner/name`, default its name); `options.repos` are the repositories the page already + * holds, with their sessions (a private source or card repository the viewer is a member of). + */ +export function useBoard(repo: RepoRef, key: number, options: { readonly label?: (repo: RepoRef) => string; readonly repos?: ReadonlyMap } = {}): BoardHookState { + const { sdk, ready, network } = useSdk(repoContractIds(repo)) + const { signer } = useAuth() + const { role } = useViewerRole(repo) + const holdKey = `${network}:${repoKey(repo)}:${key}` + // A page may rebuild its RepoRef every render: the reads key on `holdKey`, and take the latest one. + const repoRef = useRef(repo) + repoRef.current = repo + const forgeKey = Object.values(repo.forge).join(',') + const [held, setHeld] = useState(null) + const heldRef = useRef(held) + heldRef.current = held + const [error, setError] = useState(null) + const [loading, setLoading] = useState(true) + const [nonce, setNonce] = useState(0) + const [now, setNow] = useState(() => Date.now()) + const [overlay, setOverlay] = useState>(new Map()) + const [refusal, setRefusal] = useState(null) + const optionsRef = useRef(options) + optionsRef.current = options + const reader = useMemo( + () => (sdk === null ? null : boardItemReader(sdk, repoRef.current.forge, network, (r) => (optionsRef.current.label ?? ((x: RepoRef) => x.name))(r))), + // `forgeKey` names the deployment the reader reads + // eslint-disable-next-line react-hooks/exhaustive-deps + [sdk, forgeKey, network], + ) + const inputOf = useCallback( + (board: BoardView, cards: readonly BoardCard[]) => ({ home: repoRef.current, spec: board.spec as BoardSpec, cards, now: Date.now(), ...(optionsRef.current.repos ? { repos: optionsRef.current.repos } : {}), ...(optionsRef.current.label ? { label: optionsRef.current.label } : {}) }), + [], + ) + + // The full read: the definition, every card, the items. + useEffect(() => { + if (!ready || sdk === null || reader === null) return + let cancelled = false + setLoading(true) + setError(null) + void (async () => { + try { + const read = await readBoard(sdk, repoRef.current, key) + if (cancelled) return + if (read === null) { + setHeld({ key: holdKey, board: null, cards: [], items: null, since: 0, notFound: true }) + return + } + const items = read.board.spec === null ? null : await loadBoardItems(reader, inputOf(read.board, read.cards)) + if (cancelled) return + setHeld({ key: holdKey, board: read.board, cards: read.cards, items, since: read.since, notFound: false }) + setNow(Date.now()) + } catch (e) { + if (!cancelled) setError(errorMessage(e)) + } finally { + if (!cancelled) setLoading(false) + } + })() + return () => { + cancelled = true + } + // `holdKey` names the repo (its sessions), the board and the network + }, [ready, sdk, reader, holdKey, nonce, inputOf, key]) + + /** Read the cards changed since the last read, and the items new ones name. */ + const poll = useCallback(async (): Promise => { + const h = heldRef.current + if (sdk === null || reader === null || h === null || h.key !== holdKey || h.board === null) return + const fresh = await readCardsSince(sdk, repoRef.current, key, h.since) + const cards = mergeCards(h.cards, fresh) + const read = h.items === null || h.board.spec === null ? null : await addCardItems(reader, inputOf(h.board, cards), h.items) + // merged into what is held now: an older-closed read or a quick add that landed meanwhile stays + setHeld((cur) => (cur === null || cur.key !== holdKey ? cur : { ...cur, cards: mergeCards(cur.cards, fresh), items: unionItems(cur.items, read), since: Math.max(cur.since, cardsSince(fresh)) })) + setNow(Date.now()) + }, [sdk, reader, key, holdKey, inputOf]) + + /** Re-read the definition (a member saved it, or closed the board). */ + const rereadDefinition = useCallback(async (): Promise => { + if (sdk === null) return + const board = await readBoardDefinition(sdk, repoRef.current, key) + setHeld((cur) => (cur === null || cur.key !== holdKey ? cur : { ...cur, board, notFound: board === null })) + }, [sdk, key, holdKey]) + + // §5.7: poll every 20 s while visible; on show or focus re-read the definition and poll. + useEffect(() => { + if (!ready || sdk === null) return + let cancelled = false + let last = Date.now() + let inFlight = false + const tick = async (definition: boolean): Promise => { + if (cancelled || inFlight || document.visibilityState !== 'visible') return + inFlight = true + last = Date.now() + try { + if (definition) await rereadDefinition() + await poll() + } catch { + // a failed poll is no news: the next one asks again + } finally { + inFlight = false + } + } + const timer = setInterval(() => void tick(false), BOARD_POLL_MS) + const onShown = (): void => { + if (document.visibilityState === 'visible' && Date.now() - last >= BOARD_FOCUS_THROTTLE_MS) void tick(true) + } + document.addEventListener('visibilitychange', onShown) + window.addEventListener('focus', onShown) + return () => { + cancelled = true + clearInterval(timer) + document.removeEventListener('visibilitychange', onShown) + window.removeEventListener('focus', onShown) + } + }, [ready, sdk, poll, rereadDefinition]) + + const current = held !== null && held.key === holdKey ? held : null + const board = current?.board ?? null + // A landed write's optimistic card goes once a poll shows it. + useEffect(() => { + const heldCards = current?.cards ?? [] + if ([...overlay.values()].some((p) => caughtUp(p, heldCards))) { + setOverlay((cur) => new Map([...cur].filter(([, p]) => !caughtUp(p, heldCards)))) + } + }, [current, overlay]) + const cards = useMemo(() => (overlay.size === 0 ? (current?.cards ?? []) : [...(current?.cards ?? []), ...[...overlay.values()].map((p) => p.card)]), [current, overlay]) + const fold = useMemo(() => (board === null || current?.items == null ? null : assembleBoard(board, current.items, cards, now)), [board, current, cards, now]) + const can = canOf(role, signer !== null, board) + + /** + * Run a write for `items`: show `patchOf(item)` over the item's newest card at once, sign, then + * poll (the landed card replaces the optimistic one); on a refusal take it back with the reason. + */ + const run = useCallback( + async (items: readonly CardItem[], patchOf: ((item: CardItem) => CardPatch) | null, write: (w: { sdk: NonNullable; signer: WriteAuth; board: BoardView }) => Promise): Promise => { + const w = needWriter(sdk, signer) + const h = heldRef.current + if (h === null || h.board === null) throw new Error('This board has not loaded yet.') + const b = h.board + setRefusal(null) + const token = ++tokens + if (patchOf !== null && b.spec !== null) { + const spec = b.spec + const newest = newestCards(h.cards) + setOverlay((cur) => { + const next = new Map(cur) + for (const item of items) { + try { + const c = patchedCard(spec, newest.get(item.id) ?? null, patchOf(item)) + next.set(item.id, { card: { id: `pending:${item.id}`, ownerId: w.signer.identityId, updatedAt: PENDING_AT, item: item.id, ...c }, token, landed: null }) + } catch { + // a patch the board refuses is refused again by the write, with its reason + } + } + return next + }) + } + /** Settle this write's optimistic cards: keep a landed one until a poll shows it, take the rest back. */ + const settle = (landed: ReadonlyMap): void => + setOverlay((cur) => { + const next = new Map(cur) + for (const item of items) { + const p = next.get(item.id) + if (p === undefined || p.token !== token) continue + const id = landed.get(item.id) + if (id === undefined) next.delete(item.id) + else next.set(item.id, { ...p, landed: { id, at: Date.now() } }) + } + return next + }) + try { + const out = await write({ ...w, board: b }) + settle(landedOf(out)) + await poll().catch(() => undefined) + const failed = (out as Partial)?.failed + if (failed != null) setRefusal({ items: [failed.item], message: errorMessage(failed.error), error: failed.error }) + return out + } catch (e) { + settle(new Map()) + setRefusal({ items: items.map((i) => i.id), message: errorMessage(e), error: e }) + throw e + } + }, + [sdk, signer, poll], + ) + + return { + board, + cards, + items: current?.items ?? null, + fold, + now, + loading: loading && current === null, + error, + notFound: current?.notFound ?? false, + role, + can, + pending: new Set([...overlay].filter(([, p]) => p.landed === null).map(([id]) => id)), + refusal, + dismissRefusal: () => setRefusal(null), + refresh: () => setNonce((n) => n + 1), + async loadOlderClosed() { + const h = heldRef.current + if (reader === null || h === null || h.board === null || h.items === null || !h.items.hasOlderClosed) return + const older = await loadOlderClosed(reader, inputOf(h.board, h.cards), h.items) + // the walks are the older read's; any item a poll added meanwhile stays + setHeld((cur) => (cur === null || cur.key !== h.key ? cur : { ...cur, items: unionItems(older, cur.items) })) + }, + write: (item, patch, opts) => run([item], () => patch, (w) => writeCard(w.sdk, w.signer, repo, w.board, item, patch, opts)), + move: (item, target, column, before, opts) => { + // the rank shown at once is the one the write computes; a refusal (re-rank) takes it back + const r = rankBefore(column, item.id, before) + const rank = 'rank' in r ? { rank: r.rank } : {} + const optimistic = (): CardPatch => ('col' in target ? { col: target.col, ...rank } : { fields: { [target.field]: target.value }, ...rank }) + return run([item], optimistic, (w) => moveCard(w.sdk, w.signer, repo, w.board, item, target, column, before, opts)) + }, + add: (items, col, opts) => run(items, () => ({ state: 0, ...(col !== undefined ? { col } : {}) }), (w) => addItems(w.sdk, w.signer, repo, w.board, items, col, opts)), + archive: (items, opts) => run(items, () => ({ state: 1 }), (w) => archiveItems(w.sdk, w.signer, repo, w.board, items, opts)), + unarchive: (items, opts) => run(items, () => ({ state: 0 }), (w) => unarchiveItems(w.sdk, w.signer, repo, w.board, items, opts)), + remove: (items, opts) => run(items, () => ({ state: 2 }), (w) => removeItems(w.sdk, w.signer, repo, w.board, items, opts)), + rerank: (items, opts) => run(items, null, (w) => rerankColumn(w.sdk, w.signer, repo, w.board, items, opts)), + moveOpenToNextIteration: (fieldId, opts) => { + const h = heldRef.current + if (h === null || h.board?.spec == null || h.items === null || fold === null) return Promise.reject(new Error('This board has not loaded yet.')) + const t = Date.now() + const plan = nextIterationPlan(h.board.spec, fieldId, h.items.items, fold.items, t) + const items = h.items.items + const placements = fold.items + return run(plan?.items ?? [], plan === null ? null : () => ({ fields: { [fieldId]: plan.next } }), (w) => moveOpenToNextIteration(w.sdk, w.signer, repo, w.board, fieldId, items, placements, t, opts)) + }, + quickAdd: async (input) => { + const out = await run([], null, (w) => quickAddIssue(w.sdk, w.signer, repo, w.board, input)) + // the new issue is on the board at once, whatever the lists have read yet + setHeld((cur) => (cur === null || cur.items === null ? cur : { ...cur, items: withItem(cur.items, out.item) })) + return out + }, + save: async (change, opts) => { + const w = needWriter(sdk, signer) + const out = await saveBoard(w.sdk, w.signer, repo, key, change, opts) + await rereadDefinition().catch(() => undefined) + return out + }, + setState: async (state, opts) => { + const w = needWriter(sdk, signer) + const out = await setBoardState(w.sdk, w.signer, repo, key, state, opts) + await rereadDefinition().catch(() => undefined) + return out + }, + } +} + +/** One board an issue or PR is on, with where it shows there (null: the definition did not open). */ +export interface ItemBoardPlacement extends ItemBoard { + readonly placement: Placement | null +} + +/** + * The boards `item` of `repo` is on (§5.6: home is `repo` or another repository of its owner), + * with its placement on each, and the writes that change its status and fields there (each the + * home repository's members only, as on the board). + */ +export function useItemBoards(repo: RepoRef, item: BoardItem | null): AsyncState & { + /** Write `patch` to the item's card on `entry`'s board. */ + readonly write: (entry: ItemBoard, patch: CardPatch, opts?: CardWriteOptions) => Promise + /** Put the item on `board` of `repo` (an active card, in `col` when given). */ + readonly addTo: (board: BoardView, col?: number, opts?: CardWriteOptions) => Promise +} { + const { sdk, ready, network } = useSdk(repoContractIds(repo)) + const { signer } = useAuth() + // a board of another of the owner's repositories counts too + const generation = useBoardWriteGeneration() + const state = useAsync( + async () => { + const entries = await readItemCards(sdk!, repo, item!.id) + const now = Date.now() + return entries.map((e) => ({ ...e, placement: itemPlacement(e, item!, now) })) + }, + [ready, repoKey(repo), network, item?.id ?? '', item?.state ?? '', generation], + { enabled: ready && sdk !== null && item !== null }, + ) + const write = useCallback( + (entry: ItemBoard, patch: CardPatch, opts?: CardWriteOptions) => { + const w = needWriter(sdk, signer) + if (item === null) return Promise.reject(new Error('No item.')) + return writeCard(w.sdk, w.signer, entry.home, entry.board, { id: item.id, repoId: item.repoId }, patch, opts) + }, + [sdk, signer, item], + ) + const addTo = useCallback( + (board: BoardView, col?: number, opts?: CardWriteOptions) => { + const w = needWriter(sdk, signer) + if (item === null) return Promise.reject(new Error('No item.')) + return writeCard(w.sdk, w.signer, repo, board, { id: item.id, repoId: item.repoId }, { state: 0, ...(col !== undefined ? { col } : {}) }, opts) + }, + [sdk, signer, item, repo], + ) + return { ...state, write, addTo } +} diff --git a/forge-web/lib/private/board.conformance.test.ts b/forge-web/lib/private/board.conformance.test.ts new file mode 100644 index 000000000..e8d8a3605 --- /dev/null +++ b/forge-web/lib/private/board.conformance.test.ts @@ -0,0 +1,122 @@ +/** + * THE PARITY PROOF for sealed boards and cards (`docs/security/private-repos.md` §4.6): every + * `sealed_board__*` vector in `forge-contracts/vectors/` (generated by + * `tools/private-repos-vectors/boards.py`, an independent reference), run against `./board`. + * forge-core has no reader yet; `dg board` implements the same against these files. + */ + +import { readFileSync, readdirSync } from 'node:fs' +import { resolve } from 'node:path' +import { describe, expect, it } from 'vitest' + +import { openBoardDoc, parseBoardTlv, sealBoardDoc, type BoardBind, type BoardFields, type BoardOpenResult, type CardFields } from './board' +import { bytesToHex, hexToBytes } from './bytes' +import type { OpenContext } from './doc' +import { IdSet, privateId } from './ids' +import { EpochKeys, type EpochKeyring } from './keys' +import { sealBoardDocWithNonce } from './testing' +import { MalformedError } from './tlv' + +type Json = null | boolean | number | string | Json[] | { [k: string]: Json } +type Obj = { readonly [k: string]: Json } + +interface Vector { + readonly name: string + readonly case: string + readonly input: Obj + readonly expected: Json +} + +const VECTORS_DIR = resolve(process.cwd(), '..', 'forge-contracts', 'vectors') +const FILES = readdirSync(VECTORS_DIR) + .filter((f) => f.startsWith('sealed_board__') && f.endsWith('.json')) + .sort() + +const obj = (j: Json | undefined): Obj => j as Obj +const hex = (j: Json | undefined): Uint8Array => hexToBytes(j as string) + +function bindOf(d: Obj): BoardBind { + return d['type'] === 'board' ? { type: 'board', key: d['key'] as number } : { type: 'card', board: d['board'] as number, item: hex(d['item']) } +} + +async function contextOf(repoId: Uint8Array, c: Obj): Promise { + const keys = new Map() + for (const [e, k] of Object.entries(obj(c['keys']))) keys.set(Number(e), await EpochKeys.import(repoId, Number(e), hex(k))) + const members = (c['members'] ?? []) as string[] + const burned = (c['burned'] ?? []) as number[] + return { + keys: keys as EpochKeyring, + anchors: new Map(Object.entries(obj(c['anchors'])).map(([e, a]) => [Number(e), { id: privateId(obj(a)['id'] as string), height: obj(a)['height'] as number, statedHeight: obj(a)['height'] as number }])), + members: new IdSet(members.map((m) => privateId(m))), + burned: new Set(burned), + } +} + +function openJson(r: BoardOpenResult): Json { + if (r.status === 'readable') return { status: 'readable', fields: { ...r.fields } as Obj } + return r.status === 'unreadable' ? { status: 'unreadable', reason: r.reason } : { status: 'malformed' } +} + +async function run(v: Vector): Promise { + const inp = v.input + const repoId = hex(inp['repoId']) + if (inp['op'] === 'seal') { + const keys = await EpochKeys.import(repoId, inp['epoch'] as number, hex(inp['key'])) + const bind = bindOf(obj(inp['doc'])) + const fields = obj(inp['fields']) as unknown as BoardFields | CardFields + try { + const sealed = await sealBoardDocWithNonce(keys, hex(inp['ownerId']), bind, fields, hex(inp['nonce'])) + // what the writer seals is what a reader accepts + expect(parseBoardTlv(bind.type, sealed.tlv)).toEqual(fields) + return { ad: bytesToHex(sealed.ad), tlv: bytesToHex(sealed.tlv), enc: bytesToHex(sealed.enc) } + } catch (e) { + if (e instanceof MalformedError) return { error: 'malformed' } + throw e + } + } + const d = obj(inp['doc']) + const ctx = await contextOf(repoId, obj(inp['context'])) + return openJson( + await openBoardDoc(ctx, { + bind: bindOf(d), + ownerId: hex(d['ownerId']), + epoch: d['epoch'] as number, + ...(d['enc'] !== undefined ? { enc: hex(d['enc']) } : {}), + hasPlaintextContent: d['plaintext'] === true, + }), + ) +} + +describe('sealed_board vectors (private-repos.md §4.6)', () => { + it('loads both ops', () => { + const ops = FILES.map((f) => (JSON.parse(readFileSync(resolve(VECTORS_DIR, f), 'utf8')) as Vector).input['op']) + expect(ops.filter((o) => o === 'seal').length).toBeGreaterThanOrEqual(15) + expect(ops.filter((o) => o === 'open').length).toBeGreaterThanOrEqual(20) + }) + + for (const file of FILES) { + const v = JSON.parse(readFileSync(resolve(VECTORS_DIR, file), 'utf8')) as Vector + it(v.name, async () => { + expect(v.case).toBe('sealed_board') + expect(await run(v)).toEqual(v.expected) + }) + } +}) + +describe('sealBoardDoc (hedged nonce)', () => { + it('round-trips a board and a card, and never seals the same bytes twice', async () => { + const repoId = new Uint8Array(32).fill(0x11) + const owner = new Uint8Array(32).fill(0x22) + const keys = await EpochKeys.import(repoId, 3, new Uint8Array(32).fill(5)) + const ctx: OpenContext = { keys: new Map([[3, keys]]), anchors: new Map([[3, { id: new Uint8Array(32), height: 1, statedHeight: 1 }]]), members: new IdSet([]) } + const board = { name: 'Roadmap', spec: '{"v":1,"columns":[{"id":1,"name":"Todo"}]}' } + const a = await sealBoardDoc(keys, owner, { type: 'board', key: 9 }, board) + const b = await sealBoardDoc(keys, owner, { type: 'board', key: 9 }, board) + expect(bytesToHex(a)).not.toBe(bytesToHex(b)) + expect(await openBoardDoc(ctx, { bind: { type: 'board', key: 9 }, ownerId: owner, epoch: 3, enc: a, hasPlaintextContent: false })).toEqual({ status: 'readable', fields: board }) + const item = new Uint8Array(32).fill(0x44) + const card = { col: 1, rank: 'Vx', f: '{"1":2}' } + const c = await sealBoardDoc(keys, owner, { type: 'card', board: 9, item }, card) + expect(await openBoardDoc(ctx, { bind: { type: 'card', board: 9, item }, ownerId: owner, epoch: 3, enc: c, hasPlaintextContent: false })).toEqual({ status: 'readable', fields: card }) + }) +}) diff --git a/forge-web/lib/private/board.ts b/forge-web/lib/private/board.ts new file mode 100644 index 000000000..18ab138ec --- /dev/null +++ b/forge-web/lib/private/board.ts @@ -0,0 +1,323 @@ +/** + * Sealed boards and cards on a private repository (`docs/security/private-repos.md` §4.6, + * `docs/design/boards.md` §3.3): a `board`'s `name` and `spec`, and a `card`'s `col`, `rank` and + * `f`, sealed together into `enc` (v0x01) under the repository's current epoch, with the §4.4 + * framing (`docType` `board` bound to `u32(key)`, `card` bound to `u32(board) ‖ item`), so a + * sealed payload cannot be moved to another board or item. The TLV, its padding and the open are + * this module's; the `sealed_board__*` vectors (`tools/private-repos-vectors/boards.py`) pin them + * byte for byte. forge-core has no reader yet: `dg board` implements the same against the vectors. + */ + +import { bytes, concat, isU32, randomBytes, sha256, u16, u32, utf8, type Bytes } from './bytes' +import { TooLargeError, type OpenContext, type UnreadableReason } from './doc' +import { hedgeNonce, type EpochKeys } from './keys' +import { MalformedError } from './tlv' + +/** The two sealed kinds (§4.4 `docType`). */ +export type BoardDocType = 'board' | 'card' + +const V1 = 0x01 +const NONCE_LEN = 12 +const MIN_ENC = 1 + NONCE_LEN + 16 + +/** The `enc` caps of the two types (forge-meta `board.enc` / `card.enc` `maxItems`). */ +export const BOARD_MAX_ENC = 5120 +export const CARD_MAX_ENC = 2560 +/** The largest TLV each type seals: its `enc` cap less the v0x01 framing (29 bytes). */ +export const BOARD_MAX_PLAINTEXT = BOARD_MAX_ENC - MIN_ENC +export const CARD_MAX_PLAINTEXT = CARD_MAX_ENC - MIN_ENC + +/** The TLV tags of a board and a card (§4.6). Tags 32-36 are these types' only; 64 pads. */ +export const BOARD_TAG = { + name: 32, + spec: 33, + col: 34, + rank: 35, + fields: 36, + padding: 64, +} as const + +/** A sealed TLV is padded to a multiple of this many bytes (a release's bucket, §16.2). */ +const PAD_BUCKET = 32 + +/** The tags each kind carries. */ +const TAGS_OF: Readonly> = { + board: [BOARD_TAG.name, BOARD_TAG.spec], + card: [BOARD_TAG.col, BOARD_TAG.rank, BOARD_TAG.fields], +} + +/** A board's sealed fields: its name and its definition (the spec JSON, judged by the board rules, not here). */ +export interface BoardFields { + readonly name: string + readonly spec: string +} + +/** A card's sealed fields, each absent when the card has none. */ +export interface CardFields { + readonly col?: number + readonly rank?: string + /** The field values' JSON (`card.f`). */ + readonly f?: string +} + +/** The plaintext identity a sealed board or card is bound to (§4.4 `bind`). */ +export type BoardBind = { readonly type: 'board'; readonly key: number } | { readonly type: 'card'; readonly board: number; readonly item: Uint8Array } + +const NAME_MAX_CHARS = 63 +const NAME_MAX_BYTES = 252 +const SPEC_MAX_BYTES = 4096 +const FIELDS_MAX_BYTES = 2048 +const RANK = /^[0-9A-Za-z]{0,62}[1-9A-Za-z]$/ +/** The `board.name` schema pattern: no control character, and at least one that is not white space. */ +const NAME = /^[^\x00-\x1f\x7f]*[^\s\x00-\x1f\x7f][^\x00-\x1f\x7f]*$/u + +const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) + +/** Thrown inside the parser only. */ +class Refused extends Error {} + +function record(tag: number, value: Uint8Array): Bytes { + return concat(new Uint8Array([tag]), u16(value.length), value) +} + +function maxPlaintext(type: BoardDocType): number { + return type === 'board' ? BOARD_MAX_PLAINTEXT : CARD_MAX_PLAINTEXT +} + +/** Why `f` may not be sealed as a board (a reader would refuse it), or null. */ +function boardProblem(f: BoardFields): string | null { + const name = utf8(f.name) + if (f.name === '' || [...f.name].length > NAME_MAX_CHARS || name.length > NAME_MAX_BYTES || !NAME.test(f.name)) return 'a board name is 1-63 characters with no control character' + const spec = utf8(f.spec) + if (spec.length < 1 || spec.length > SPEC_MAX_BYTES) return 'a board definition is 1-4096 bytes' + return null +} + +/** Why `f` may not be sealed as a card, or null. */ +function cardProblem(f: CardFields): string | null { + if (f.col !== undefined && (!Number.isInteger(f.col) || f.col < 0 || f.col > 255)) return 'a card column is 0-255' + if (f.rank !== undefined && !RANK.test(f.rank)) return 'a card rank is 1-63 rank digits, not ending in 0' + if (f.f !== undefined) { + const n = utf8(f.f).length + if (n < 1 || n > FIELDS_MAX_BYTES) return 'card field values are 1-2048 bytes' + } + return null +} + +/** The TLV records of `f`, ascending, without padding (§4.6). */ +export function encodeBoardTlv(f: BoardFields): Bytes { + return concat(record(BOARD_TAG.name, utf8(f.name)), record(BOARD_TAG.spec, utf8(f.spec))) +} + +/** The TLV records of `f`, ascending, without padding; an empty card is no records. */ +export function encodeCardTlv(f: CardFields): Bytes { + const out: Uint8Array[] = [] + if (f.col !== undefined) out.push(record(BOARD_TAG.col, new Uint8Array([f.col]))) + if (f.rank !== undefined) out.push(record(BOARD_TAG.rank, utf8(f.rank))) + if (f.f !== undefined) out.push(record(BOARD_TAG.fields, utf8(f.f))) + return concat(...out) +} + +/** + * The tag-64 record that pads `n` bytes of TLV to a multiple of 32 within the type's cap (a + * release's rule, §16.2); nothing when not even an empty record fits. + */ +function padding(n: number, cap: number): Bytes { + if (n + 3 > cap) return new Uint8Array(0) + const r = Math.min((PAD_BUCKET - ((n + 3) % PAD_BUCKET)) % PAD_BUCKET, cap - 3 - n) + return record(BOARD_TAG.padding, new Uint8Array(r)) +} + +/** The padded TLV a writer seals, refused ({@link MalformedError}) where a reader would refuse it. */ +function buildTlv(type: BoardDocType, f: BoardFields | CardFields): Bytes { + const problem = type === 'board' ? boardProblem(f as BoardFields) : cardProblem(f as CardFields) + if (problem !== null) throw new MalformedError(problem) + const body = type === 'board' ? encodeBoardTlv(f as BoardFields) : encodeCardTlv(f as CardFields) + const cap = maxPlaintext(type) + // never above the cap: every field is bounded well below it (§4.6) + if (body.length > cap) throw new TooLargeError(cap) + return concat(body, padding(body.length, cap)) +} + +function text(value: Uint8Array): string { + try { + return decoder.decode(value) + } catch { + throw new Refused('invalid UTF-8') + } +} + +/** + * Parse a board's or a card's TLV (§4.6): records strictly ascending, none repeated; tags 1-63 + * other than the kind's own are malformed, 64-255 skipped (64 pads); every value valid and + * within its cap; a zero-length text record counts as absent; a board needs its name and spec. + * Null when malformed. + */ +export function parseBoardTlv(type: 'board', pt: Uint8Array): BoardFields | null +export function parseBoardTlv(type: 'card', pt: Uint8Array): CardFields | null +export function parseBoardTlv(type: BoardDocType, pt: Uint8Array): BoardFields | CardFields | null +export function parseBoardTlv(type: BoardDocType, pt: Uint8Array): BoardFields | CardFields | null { + const allowed = TAGS_OF[type] + const out: { name?: string; spec?: string; col?: number; rank?: string; f?: string } = {} + try { + let i = 0 + let last = 0 + while (i < pt.length) { + if (pt.length - i < 3) throw new Refused('truncated record') + const tag = pt[i] as number + const len = ((pt[i + 1] as number) << 8) | (pt[i + 2] as number) + if (i + 3 + len > pt.length) throw new Refused('record runs past the end') + const value = pt.subarray(i + 3, i + 3 + len) + i += 3 + len + if (tag <= last) throw new Refused('records out of order or repeated') + last = tag + if (tag >= BOARD_TAG.padding) continue + if (!allowed.includes(tag)) throw new Refused(`tag ${tag} in a ${type}`) + switch (tag) { + case BOARD_TAG.name: + if (len > 0) out.name = text(value) + break + case BOARD_TAG.spec: + if (len > 0) out.spec = text(value) + break + case BOARD_TAG.col: + if (len !== 1) throw new Refused('a column is one byte') + out.col = value[0] as number + break + case BOARD_TAG.rank: + if (len > 0) out.rank = text(value) + break + case BOARD_TAG.fields: + if (len > 0) out.f = text(value) + break + } + } + } catch (e) { + if (e instanceof Refused) return null + throw e + } + if (type === 'board') { + if (out.name === undefined || out.spec === undefined) return null + const f: BoardFields = { name: out.name, spec: out.spec } + return boardProblem(f) === null ? f : null + } + const f: CardFields = { ...(out.col !== undefined ? { col: out.col } : {}), ...(out.rank !== undefined ? { rank: out.rank } : {}), ...(out.f !== undefined ? { f: out.f } : {}) } + return cardProblem(f) === null ? f : null +} + +/** `bind` (§4.4): `u32(key)` for a board, `u32(board) ‖ item` for a card. */ +function bindOf(b: BoardBind): Bytes { + if (b.type === 'board') { + if (!isU32(b.key) || b.key === 0) throw new MalformedError('a board key is 1-4294967295') + return u32(b.key) + } + if (!isU32(b.board) || b.board === 0) throw new MalformedError('a board key is 1-4294967295') + if (b.item.length !== 32) throw new MalformedError('an item id is 32 bytes') + return concat(u32(b.board), b.item) +} + +/** The §4.4 AD of a board or card: `docType` its type, `bind` its immutable keys. */ +export function boardAd(keys: EpochKeys, ownerId: Uint8Array, b: BoardBind): Bytes { + if (ownerId.length !== 32) throw new MalformedError('ownerId must be 32 bytes') + return concat(utf8('dash-forge/v2/doc'), new Uint8Array([0, V1]), keys.repoId, ownerId, u32(keys.epoch), utf8(b.type), new Uint8Array([0]), bindOf(b)) +} + +/** A sealed board or card with the intermediate values the vectors pin. */ +interface SealedBoard { + readonly ad: Bytes + readonly tlv: Bytes + readonly enc: Bytes +} + +type NonceOf = (ad: Bytes, tlv: Bytes) => Promise + +async function sealWith(keys: EpochKeys, ownerId: Uint8Array, b: BoardBind, f: BoardFields | CardFields, nonceOf: NonceOf): Promise { + const tlv = buildTlv(b.type, f) + const ad = boardAd(keys, ownerId, b) + const nonce = await nonceOf(ad, tlv) + if (nonce.length !== NONCE_LEN) throw new RangeError('a nonce is 12 bytes') + const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, additionalData: ad }, keys.docKey, tlv) + return { ad, tlv, enc: concat(new Uint8Array([V1]), nonce, new Uint8Array(ct)) } +} + +/** + * Seal a board's or a card's fields as `ownerId`'s document under `keys` (the repository's + * current write epoch), with a hedged random nonce (§3.6). The document is then + * `{repoId, key | (board, item), state, epoch: keys.epoch, enc, r}`, with no plaintext name, + * spec, col, rank or f. Throws {@link MalformedError} for fields a reader would refuse. + */ +export async function sealBoardDoc(keys: EpochKeys, ownerId: Uint8Array, b: { readonly type: 'board'; readonly key: number }, f: BoardFields): Promise +export async function sealBoardDoc(keys: EpochKeys, ownerId: Uint8Array, b: { readonly type: 'card'; readonly board: number; readonly item: Uint8Array }, f: CardFields): Promise +export async function sealBoardDoc(keys: EpochKeys, ownerId: Uint8Array, b: BoardBind, f: BoardFields | CardFields): Promise { + const hedged: NonceOf = async (ad, tlv) => hedgeNonce(keys, randomBytes(32), ad, await sha256(tlv)) + const sealed = await sealWith(keys, ownerId, b, f, hedged) + sealed.tlv.fill(0) + return sealed.enc +} + +/** + * INTERNAL, TEST-ONLY: {@link sealBoardDoc} with a caller-chosen nonce, for the `sealed_board` + * vectors. Only `lib/private/testing.ts` may import it; it is not re-exported from `index.ts`. + */ +export function __unsafeSealBoardDocWithNonce(keys: EpochKeys, ownerId: Uint8Array, b: BoardBind, f: BoardFields | CardFields, nonce: Uint8Array): Promise { + return sealWith(keys, ownerId, b, f, async () => new Uint8Array(nonce)) +} + +/** A stored board or card, as the open sees it. */ +export interface StoredBoardDoc { + readonly bind: BoardBind + /** `$ownerId`, 32 bytes. */ + readonly ownerId: Uint8Array + readonly epoch?: number + readonly enc?: Uint8Array + /** Whether it also carries a plaintext content field (a board's `name` / `spec`; a card's `col` / `rank` / `f`): malformed. */ + readonly hasPlaintextContent: boolean +} + +export type BoardOpenResult = + | { readonly status: 'readable'; readonly fields: BoardFields | CardFields } + | { readonly status: 'unreadable'; readonly reason: UnreadableReason } + | { readonly status: 'malformed' } + +const MALFORMED: BoardOpenResult = { status: 'malformed' } +const unreadable = (reason: UnreadableReason): BoardOpenResult => ({ status: 'unreadable', reason }) + +/** + * Open a sealed board or card (§4.6, in order): the key-independent checks (an `enc`, a u32 + * `epoch`, no plaintext content), the framing (a version other than 0x01, a later client's + * members-only board, is `unknownVersion`, never malformed), the epoch and key, AES-GCM, the + * TLV, then the burned clause of the late-content rule. Both types are member-gated at + * consensus on every replace (boards.md §3), so the height part of §8.2 does not apply, as for + * a member `event`. + */ +export async function openBoardDoc(ctx: OpenContext, d: StoredBoardDoc): Promise { + const { enc, epoch } = d + if (d.ownerId.length !== 32 || enc === undefined || epoch === undefined || !isU32(epoch) || d.hasPlaintextContent) return MALFORMED + if (enc.length < MIN_ENC) return MALFORMED + if (enc[0] !== V1) return unreadable('unknownVersion') + if (!ctx.anchors.has(epoch)) return unreadable('noEpoch') + const keys = ctx.keys.get(epoch) + if (keys === undefined) return unreadable('noKey') + let ad: Bytes + try { + ad = boardAd(keys, d.ownerId, d.bind) + } catch (e) { + if (e instanceof MalformedError) return MALFORMED + throw e + } + let pt: Bytes + try { + pt = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes(enc.slice(1, 1 + NONCE_LEN)), additionalData: ad }, keys.docKey, bytes(enc.slice(1 + NONCE_LEN)))) + } catch { + return unreadable('badTag') + } + let fields: BoardFields | CardFields | null + try { + fields = parseBoardTlv(d.bind.type, pt) + } finally { + pt.fill(0) + } + if (fields === null) return MALFORMED + if (ctx.burned?.has(epoch) === true && !ctx.members.has(d.ownerId)) return unreadable('late') + return { status: 'readable', fields } +} diff --git a/forge-web/lib/private/index.ts b/forge-web/lib/private/index.ts index 0de190b92..d7c89c520 100644 --- a/forge-web/lib/private/index.ts +++ b/forge-web/lib/private/index.ts @@ -21,7 +21,8 @@ * publish one document revision's per-object key (`membersObjKey`, `letterObjKey`) and open it * with no other key (`openMembersWithKey`, `openLetterWithKey`). `./release`'s `sealRelease` and `sealReleaseManifest` are, since the web writes * sealed releases (`private-repos.md` §16.8, `lib/repo/sealed-release.ts`): both draw hedged - * randomness, and only their fixed-nonce twins stay test-only. + * randomness, and only their fixed-nonce twins stay test-only. `./board` seals a private repository's + * boards and cards (§4.6, `docs/design/boards.md` §3.3); its fixed-nonce twin is test-only too. */ export { bytesToHex, concat as concatBytes, constantTimeEqual, hexToBytes, isU32, randomBytes, type Bytes } from './bytes' @@ -170,6 +171,23 @@ export { type ReleaseStatus, type StoredRelease, } from './release' +export { + BOARD_MAX_PLAINTEXT, + BOARD_TAG, + CARD_MAX_PLAINTEXT, + boardAd, + encodeBoardTlv, + encodeCardTlv, + openBoardDoc, + parseBoardTlv, + sealBoardDoc, + type BoardBind, + type BoardDocType, + type BoardFields, + type BoardOpenResult, + type CardFields, + type StoredBoardDoc, +} from './board' export { BlindMap, SALT_LEN, diff --git a/forge-web/lib/private/testing.ts b/forge-web/lib/private/testing.ts index 8d873540d..63f5f4c50 100644 --- a/forge-web/lib/private/testing.ts +++ b/forge-web/lib/private/testing.ts @@ -5,6 +5,7 @@ * `no-restricted-imports` bans importing it anywhere but `*.test.ts`. */ +import { __unsafeSealBoardDocWithNonce, type BoardBind, type BoardFields, type CardFields } from './board' import { __unsafeSealBotPostWithNonce, type PostKey } from './bot-post' import { __unsafeSealBranchPackWith, __unsafeSealBranchRefWith, type BranchKeys } from './branch-key' import { sha256, utf8, type Bytes } from './bytes' @@ -27,6 +28,17 @@ export function sealDocWithNonce( return __unsafeSealDocWithNonce(keys, doc, fields, nonce, options) } +/** `sealBoardDoc` with a fixed nonce; returns the AD and padded TLV too (the `sealed_board` vectors). */ +export function sealBoardDocWithNonce( + keys: EpochKeys, + ownerId: Uint8Array, + bind: BoardBind, + fields: BoardFields | CardFields, + nonce: Uint8Array, +): Promise<{ ad: Bytes; tlv: Bytes; enc: Bytes }> { + return __unsafeSealBoardDocWithNonce(keys, ownerId, bind, fields, nonce) +} + /** `sealMembersDoc` with a fixed nonce; returns the AD, raw `K_obj`, `COMMIT_obj` and padded TLV too. */ export function sealMembersDocWithNonce( keys: EpochKeys, diff --git a/forge-web/lib/repo/board-items.test.ts b/forge-web/lib/repo/board-items.test.ts new file mode 100644 index 000000000..830864d48 --- /dev/null +++ b/forge-web/lib/repo/board-items.test.ts @@ -0,0 +1,216 @@ +/** + * A board's items (`docs/design/boards.md` §2.3, §2.4): open items of the sources, the closed + * ones within the auto-archive window from the newest-first state changes (with `closedAt`), the + * items cards name (any repository; a private one's a placeholder), and the fold over them. + */ + +import { describe, expect, it } from 'vitest' + +import { base58Encode } from '../auth/base58' +import { defaultSpec, type BoardItem, type BoardSpec, type CardDoc, type ItemKind } from '../rules/boards' +import { ISSUE_CLOSE, ISSUE_LOCK, ISSUE_REOPEN, PR_MERGE } from '../rules/transition' +import { CLOSED_PER_REPO, addCardItems, assembleBoard, loadBoardItems, loadOlderClosed, type BoardItemReader } from './board-items' +import type { BoardView } from './boards' +import type { RepoRef } from './contract' +import type { TransitionView } from './transitions' + +const DAY = 86_400_000 +const NOW = Date.UTC(2026, 9, 27) +const id = (n: number): string => base58Encode(new Uint8Array(32).fill(n)) +const HOME = id(1) +const OTHER_REPO = id(2) +const PRIVATE_REPO = id(3) +const FORGE = { core: 'C', collab: 'L', community: 'M', meta: 'T', group: 'G' } +const repo = (repoId: string, visibility: 'public' | 'private' = 'public'): RepoRef => ({ forge: FORGE, repoId, ownerId: id(9), name: `r${repoId.slice(0, 3)}`, visibility }) + +function item(n: number, over: Partial = {}): BoardItem { + return { id: id(100 + n), number: n, repoId: HOME, kind: 'issue', state: 'open', createdAt: NOW - (100 - n) * DAY, closedAt: null, title: `Item ${n}`, labels: [], assignees: [], milestone: null, author: id(9), ...over } +} + +let tx = 0 +function t(target: number, kind: number, at: number): TransitionView { + return { id: `t${++tx}`, targetId: id(100 + target), kind, actor: id(9), asAuthor: 0, createdAt: at } +} + +/** A reader over fixed rows, recording its calls. */ +function reader(rows: { open?: BoardItem[]; closed?: BoardItem[]; transitions?: TransitionView[]; elsewhere?: Record; repos?: Record }) { + const calls: string[] = [] + const all = [...(rows.open ?? []), ...(rows.closed ?? []), ...Object.values(rows.elsewhere ?? {}).flat()] + const r: BoardItemReader = { + async openItems(rp, kind: ItemKind) { + calls.push(`open:${kind}`) + return { items: (rows.open ?? []).filter((i) => i.repoId === rp.repoId && i.kind === kind), complete: true } + }, + async transitions(rp, before) { + calls.push(`transitions:${before ?? 'newest'}`) + // Drive's descending walk: newest first, ties by `$id` descending + const sorted = (rows.transitions ?? []).filter((x) => before === null || x.createdAt <= before).sort((a, b) => b.createdAt - a.createdAt || (a.id < b.id ? 1 : -1)) + return sorted.slice(0, 100) + }, + async transitionsAt(_rp, at, startAfter) { + calls.push(`at:${at}:${startAfter ?? ''}`) + const tied = (rows.transitions ?? []).filter((x) => x.createdAt === at).sort((a, b) => (a.id < b.id ? -1 : 1)) + const from = startAfter === null ? 0 : tied.findIndex((x) => x.id === startAfter) + 1 + return tied.slice(from, from + 100) + }, + async itemsById(rp, ids) { + calls.push(`byId:${ids.length}`) + return all.filter((i) => i.repoId === rp.repoId && ids.includes(i.id)).map((i) => ({ ...i, closedAt: null })) + }, + async transitionsOf(_rp, ids) { + return (rows.transitions ?? []).filter((x) => ids.includes(x.targetId)) + }, + async locate(ids) { + return new Map(all.filter((i) => ids.includes(i.id)).map((i) => [i.id, { repoId: i.repoId, kind: i.kind }])) + }, + async repo(repoId) { + return rows.repos?.[repoId] ?? null + }, + } + return { r, calls } +} + +const SPEC: BoardSpec = defaultSpec(HOME, NOW) +const card = (target: number, over: Partial = {}): CardDoc => ({ id: `card${target}`, ownerId: id(9), updatedAt: NOW - DAY, item: id(100 + target), col: 2, rank: null, f: null, state: 0, ...over }) +const BOARD: BoardView = { + key: 7, + repoId: HOME, + state: 'open', + name: 'Board', + spec: SPEC, + specError: null, + sealed: false, + newest: { id: 'b', ownerId: id(9), updatedAt: 1 }, + revisions: [{ id: 'b', ownerId: id(9), updatedAt: 1 }], +} + +describe('loadBoardItems', () => { + it('reads open items, closed ones in the auto-archive window with their closedAt, and stops past it', async () => { + const open = [item(1), item(2, { kind: 'pr' })] + const closed = [item(3, { state: 'closed' }), item(4, { state: 'merged', kind: 'pr' }), item(5, { state: 'closed' }), item(6, { state: 'closed' })] + const transitions = [ + t(3, ISSUE_CLOSE, NOW - 2 * DAY), + t(3, ISSUE_LOCK, NOW - DAY), + t(4, PR_MERGE, NOW - 3 * DAY), + // reopened and closed again: the latest close counts + t(5, ISSUE_CLOSE, NOW - 40 * DAY), + t(5, ISSUE_REOPEN, NOW - 30 * DAY), + t(5, ISSUE_CLOSE, NOW - 5 * DAY), + // reopened since: open (it is an open item) + t(1, ISSUE_CLOSE, NOW - 6 * DAY), + t(1, ISSUE_REOPEN, NOW - 4 * DAY), + // closed long ago, past the 14-day window + ...Array.from({ length: 100 }, (_, i) => t(6, ISSUE_CLOSE, NOW - (60 + i) * DAY)), + ] + const { r } = reader({ open, closed, transitions }) + const set = await loadBoardItems(r, { home: repo(HOME), spec: SPEC, cards: [], now: NOW }) + const byNumber = new Map(set.items.map((i) => [i.number, i])) + expect([...byNumber.keys()].sort()).toEqual([1, 2, 3, 4, 5]) + expect(byNumber.get(3)?.closedAt).toBe(NOW - 2 * DAY) + expect(byNumber.get(4)?.closedAt).toBe(NOW - 3 * DAY) + expect(byNumber.get(5)?.closedAt).toBe(NOW - 5 * DAY) + expect(byNumber.get(1)?.closedAt).toBeNull() + expect(set.hasOlderClosed).toBe(true) + expect(set.partial).toBe(false) + // Done holds the closed and merged ones; the sources take every item + const fold = assembleBoard(BOARD, set, [], NOW) + expect(fold?.columns.find((c) => c.id === 3)?.items.length).toBe(3) + expect(fold?.items.every((p) => p.on)).toBe(true) + }) + + it('with auto-archive off reads the most recently closed per repository, and reads on when asked', async () => { + const spec: BoardSpec = { ...SPEC, arch: 0 } + const closed = Array.from({ length: CLOSED_PER_REPO + 50 }, (_, i) => item(i + 1, { id: base58Encode(new Uint8Array(32).fill(0).map((_, j) => (j === 0 ? 7 : j === 1 ? i >> 8 : j === 2 ? i & 255 : 1))), state: 'closed' })) + const transitions = closed.map((c, i): TransitionView => ({ id: `x${i}`, targetId: c.id, kind: ISSUE_CLOSE, actor: id(9), asAuthor: 0, createdAt: NOW - i * 1000 })) + const { r } = reader({ closed, transitions }) + const input = { home: repo(HOME), spec, cards: [], now: NOW } + const set = await loadBoardItems(r, input) + expect(set.items.length).toBeGreaterThanOrEqual(CLOSED_PER_REPO) + expect(set.items.length).toBeLessThan(closed.length) + expect(set.hasOlderClosed).toBe(true) + const older = await loadOlderClosed(r, input, set) + expect(older.items).toHaveLength(closed.length) + expect(older.hasOlderClosed).toBe(false) + }) + + it("reads the items cards name outside the sources, a private repo's as a placeholder", async () => { + const elsewhere = { [OTHER_REPO]: [item(7, { repoId: OTHER_REPO, state: 'closed' })], [PRIVATE_REPO]: [item(8, { repoId: PRIVATE_REPO })] } + const { r } = reader({ + elsewhere, + transitions: [t(7, ISSUE_CLOSE, NOW - 100 * DAY)], + repos: { [OTHER_REPO]: repo(OTHER_REPO), [PRIVATE_REPO]: repo(PRIVATE_REPO, 'private') }, + }) + const cards = [card(7), card(8), card(99)] + const set = await loadBoardItems(r, { home: repo(HOME), spec: SPEC, cards, now: NOW }) + const seven = set.items.find((i) => i.number === 7) + expect(seven).toMatchObject({ repoId: OTHER_REPO, state: 'closed', closedAt: NOW - 100 * DAY, repo: repo(OTHER_REPO).name }) + expect(set.hidden).toEqual(new Set([id(108)])) + expect(set.items.find((i) => i.id === id(108))).toMatchObject({ title: '', repoId: PRIVATE_REPO }) + expect(set.missing).toEqual(new Set([id(199)])) + // closed, so in Done; its card is newer than the close, so auto-archive spares it + const fold = assembleBoard(BOARD, set, cards, NOW) + expect(fold?.items.find((p) => p.id === id(107))).toMatchObject({ on: true, col: 3, archived: null }) + }) + + it('a poll that brings a card for a new item reads only that item', async () => { + const { r, calls } = reader({ open: [item(1)], elsewhere: { [OTHER_REPO]: [item(9, { repoId: OTHER_REPO })] }, repos: { [OTHER_REPO]: repo(OTHER_REPO) } }) + const input = { home: repo(HOME), spec: SPEC, cards: [], now: NOW } + const set = await loadBoardItems(r, input) + calls.length = 0 + const same = await addCardItems(r, { ...input, cards: [card(1)] }, set) + expect(same).toBe(set) + expect(calls).toEqual([]) + const more = await addCardItems(r, { ...input, cards: [card(1), card(9)] }, set) + expect(more.items.map((i) => i.number).sort()).toEqual([1, 9]) + expect(calls).toEqual(['byId:1']) + }) + + it('a repo whose every close is older than the window reads none at first, and has older ones', async () => { + const closed = [item(3, { state: 'closed' })] + const { r } = reader({ closed, transitions: [t(3, ISSUE_CLOSE, NOW - 90 * DAY)] }) + const input = { home: repo(HOME), spec: SPEC, cards: [], now: NOW } + const set = await loadBoardItems(r, input) + expect(set.items).toEqual([]) + expect(set.hasOlderClosed).toBe(true) + const older = await loadOlderClosed(r, input, set) + expect(older.items.map((i) => [i.number, i.closedAt])).toEqual([[3, NOW - 90 * DAY]]) + expect(older.hasOlderClosed).toBe(false) + // folded, it is auto-archived: hidden unless a view asks for archived items + expect(assembleBoard(BOARD, older, [], NOW)?.items[0]?.archived).toBe('auto') + }) + + it('walks past a block of more than a page of state changes at one time', async () => { + const spec: BoardSpec = { ...SPEC, arch: 0 } + const ids = Array.from({ length: 150 }, (_, i) => base58Encode(new Uint8Array(32).fill(0).map((_, j) => (j === 0 ? 9 : j === 1 ? i : 1)))) + const closed = [...ids.map((x, i) => item(i + 1, { id: x, state: 'closed' })), item(200, { state: 'closed' })] + const transitions: TransitionView[] = [ + ...ids.map((x, i): TransitionView => ({ id: `tie${String(i).padStart(3, '0')}`, targetId: x, kind: ISSUE_CLOSE, actor: id(9), asAuthor: 0, createdAt: NOW - DAY })), + t(200, ISSUE_CLOSE, NOW - 2 * DAY), + ] + const { r, calls } = reader({ closed, transitions }) + const set = await loadBoardItems(r, { home: repo(HOME), spec, cards: [], now: NOW }) + expect(set.items).toHaveLength(151) + expect(set.items.find((i) => i.number === 200)?.closedAt).toBe(NOW - 2 * DAY) + expect(set.hasOlderClosed).toBe(false) + expect(calls.filter((c) => c.startsWith('at:'))).toHaveLength(2) + }) + + it('counts only closes of the kinds the sources name toward the first read', async () => { + const spec: BoardSpec = { ...SPEC, arch: 0, sources: [{ r: HOME, k: 'i', q: '' }] } + const prs = Array.from({ length: CLOSED_PER_REPO }, (_, i) => item(i + 1, { id: base58Encode(new Uint8Array(32).fill(0).map((_, j) => (j === 0 ? 8 : j === 1 ? i : 1))), kind: 'pr', state: 'merged' })) + const issue = item(250, { state: 'closed' }) + const transitions: TransitionView[] = [...prs.map((p, i): TransitionView => ({ id: `m${i}`, targetId: p.id, kind: PR_MERGE, actor: id(9), asAuthor: 0, createdAt: NOW - i * 1000 })), t(250, ISSUE_CLOSE, NOW - DAY)] + const { r } = reader({ closed: [...prs, issue], transitions }) + const set = await loadBoardItems(r, { home: repo(HOME), spec, cards: [], now: NOW }) + expect(set.items.map((i) => i.number)).toEqual([250]) + expect(set.hasOlderClosed).toBe(false) + }) + + it('reads only the kinds the sources name', async () => { + const spec: BoardSpec = { ...SPEC, sources: [{ r: HOME, k: 'p', q: '' }] } + const { r, calls } = reader({ open: [item(1), item(2, { kind: 'pr' })] }) + const set = await loadBoardItems(r, { home: repo(HOME), spec, cards: [], now: NOW }) + expect(calls.filter((c) => c.startsWith('open'))).toEqual(['open:pr']) + expect(set.items.map((i) => i.number)).toEqual([2]) + }) +}) diff --git a/forge-web/lib/repo/board-items.ts b/forge-web/lib/repo/board-items.ts new file mode 100644 index 000000000..bbde9a63f --- /dev/null +++ b/forge-web/lib/repo/board-items.ts @@ -0,0 +1,512 @@ +/** + * The items a board folds (`docs/design/boards.md` §2.3, §2.4): the {@link BoardItem} facts of + * every issue and PR its sources include and its cards name, read through the Issues and Pull + * requests list indexes (labels, assignees, milestone, author, state: their folds, not a second + * copy), then {@link assembleBoard} folds them with `now`. + * + * Per source repository, for the kinds its sources name: + * + * - every **open** issue or PR (the list's Open tab, page after page); + * - the **recently closed or merged** ones: the repo's state changes newest first (`transition` + * `feed`, keyset pages of 100) name each target's latest move and its `closedAt` (the + * `$createdAt` of its latest move into closed or merged, §2.4); the walk stops past the + * auto-archive window (`arch` days: older ones are archived unless a card keeps them, and those + * are read by id below), or, with `arch` 0, at the {@link CLOSED_PER_REPO} most recently closed. + * {@link BoardItemSet.hasOlderClosed} says the walk stopped early; {@link loadOlderClosed} + * reads on (a view asking for `is:archived`, or "Show older"). + * + * Then every item a card names that the sources did not bring: located by id in forge-collab + * (`issue` or `patch`, any repository), read through its own repository's index, with its + * `closedAt` from its transitions. One of a private repository this reader holds no session for, + * or a public repository's members-only one it cannot open, is a placeholder + * ({@link BoardItemSet.hidden}: "a private item"), placed by its card like any other. + * + * A source repository that is private and that this reader holds no session for contributes + * nothing (its lists hide every item from a non-member); its items still show as placeholders + * where a card names them. + * + * The reads go through a {@link BoardItemReader} ({@link boardItemReader} is the SDK's), so the + * assembly is tested without one. + */ + +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { DEFAULT_NETWORK, type Network } from '../constants' +import type { ForgeIds } from '../deployments' +import { foldBoard, type BoardFold, type BoardItem, type BoardSpec, type CardDoc, type ItemKind } from '../rules/boards' +import { compareStrings } from '../rules/oid' +import { ISSUE_CLOSE, ISSUE_LOCK, ISSUE_UNLOCK, PR_CLOSE, PR_DRAFT_CLOSE, PR_LOCK, PR_MERGE, PR_UNLOCK } from '../rules/transition' +import { queryAllDocuments, queryDocumentsWithProof } from '../sdk' +import { DOC, asIdentifierString, type RepoRef } from './contract' +import type { BoardView } from './boards' +import { issueRowsById, queryIssues, type IssueRow, type IssueSelection } from './issue-index' +import { pullRowsById, queryPulls, type PullRow, type PullSelection } from './pull-index' +import { readRepoById, repoRefOf } from './resolveRepo' +import { repoSource } from './source' +import { transitionOf, type TransitionView } from './transitions' + +const DAY_MS = 86_400_000 +/** With auto-archive off, a source repository's closed items read at first are its most recently closed this many (§2.4). */ +export const CLOSED_PER_REPO = 200 +/** State-change pages (100 each) one load walks at most per repository. */ +export const TRANSITION_PAGES = 20 +/** A state-change page. */ +const PAGE = 100 +/** The transition kinds that move a target into closed or merged, and the kind of item each closes. */ +const CLOSES: Readonly> = { [ISSUE_CLOSE]: 'issue', [PR_CLOSE]: 'pr', [PR_MERGE]: 'pr', [PR_DRAFT_CLOSE]: 'pr' } +/** Lock moves change no state: a target's latest state move is read past them. */ +const LOCK_KINDS: ReadonlySet = new Set([ISSUE_LOCK, ISSUE_UNLOCK, PR_LOCK, PR_UNLOCK]) + +/** What a board's item reads need (the SDK's: {@link boardItemReader}). */ +export interface BoardItemReader { + /** Every open issue (`issue`) or PR (`pr`) of `repo`; `complete` false when the list stopped short. */ + openItems(repo: RepoRef, kind: ItemKind): Promise<{ readonly items: readonly BoardItem[]; readonly complete: boolean }> + /** One page of `repo`'s state changes, newest first, created at or before `before` (null: the newest). */ + transitions(repo: RepoRef, before: number | null): Promise + /** One page of `repo`'s state changes created at exactly `at`, in `$id` order, after `startAfter` (a block of more than a page). */ + transitionsAt(repo: RepoRef, at: number, startAfter: string | null): Promise + /** `repo`'s issues and PRs among `ids`, as the lists show them (an id that is neither, or hidden, is left out). */ + itemsById(repo: RepoRef, ids: readonly string[]): Promise + /** Every transition of `ids` (`perTarget`), for their `closedAt`. */ + transitionsOf(repo: RepoRef, ids: readonly string[]): Promise + /** The repository and kind of each of `ids` that is an issue or a PR (any repository). */ + locate(ids: readonly string[]): Promise> + /** Repository `repoId`, or null. */ + repo(repoId: string): Promise +} + +/** What a board's item assembly starts from. */ +export interface BoardItemsInput { + /** The board's home repository (as the page holds it: with its session, when private). */ + readonly home: RepoRef + readonly spec: BoardSpec + readonly cards: readonly CardDoc[] + readonly now: number + /** + * The repositories the page already holds (with their sessions), by id: a source or card + * repository found here is read as is, so a private one the reader is a member of opens. + */ + readonly repos?: ReadonlyMap + /** How a repository is named on its items (`owner/name`, for `repo:` and the card's label); default its name. */ + readonly label?: (repo: RepoRef) => string +} + +/** One source repository's closed-item walk. */ +export interface ClosedWalk { + /** Where the next page starts (`$createdAt <=`); null: at the newest change. */ + readonly before: number | null + /** The walk reached the repo's first change: nothing older is left. */ + readonly done: boolean + /** Targets whose latest state move the walk has seen (their state is settled by it). */ + readonly seen: ReadonlySet + /** Transitions already read at the `before` boundary (a `<=` page repeats them). */ + readonly boundary: ReadonlySet +} + +/** A board's items, ready to fold. */ +export interface BoardItemSet { + readonly items: readonly BoardItem[] + /** Items shown as "a private item": a private repository's (no session) or a members-only one this reader cannot open. */ + readonly hidden: ReadonlySet + /** Card items that are no issue or PR this reader can find (dropped from the board). */ + readonly missing: ReadonlySet + /** A source's open list stopped short: the board may lack some open items. */ + readonly partial: boolean + /** Some source repository has closed items older than were read ({@link loadOlderClosed}). */ + readonly hasOlderClosed: boolean + /** Each source repository's closed walk, by repository id. */ + readonly walks: ReadonlyMap +} + +/** The source repositories of `spec` and the kinds each is read for. */ +function sourceKinds(spec: BoardSpec, home: string): Map> { + const out = new Map>() + for (const s of spec.sources) { + const r = s.r ?? home + const kinds = out.get(r) ?? new Set() + if (s.k !== 'p') kinds.add('issue') + if (s.k !== 'i') kinds.add('pr') + out.set(r, kinds) + } + return out +} + +async function repoOf(reader: BoardItemReader, input: BoardItemsInput, repoId: string): Promise { + if (repoId === input.home.repoId) return input.home + return input.repos?.get(repoId) ?? (await reader.repo(repoId)) +} + +/** A placeholder for an item this reader cannot open ("a private item"): only what is plaintext about it. */ +function placeholder(id: string, repoId: string, kind: ItemKind): BoardItem { + return { id, number: 0, repoId, kind, state: 'open', createdAt: 0, closedAt: null, title: '', labels: [], assignees: [], milestone: null, author: '' } +} + +/** + * Walk `repo`'s state changes newest first from `walk`, stopping before the first change `stop` + * refuses (or at the repo's first change, or after {@link TRANSITION_PAGES} pages): each target's + * latest state move decides whether it is closed (with its `closedAt`). The walk it returns + * resumes exactly where this one stopped: the next page reads `$createdAt <=` the last change + * read, skipping those of that time already read. + */ +async function walkClosed( + reader: BoardItemReader, + repo: RepoRef, + walk: ClosedWalk, + kinds: ReadonlySet, + stop: (counted: number, next: TransitionView) => boolean, +): Promise<{ readonly closed: Map; readonly walk: ClosedWalk }> { + const seen = new Set(walk.seen) + const closed = new Map() + // closed items of the sources' kinds found so far + let counted = 0 + let before = walk.before + // the changes read at `before`'s time (a later page at `<=` repeats them) + let boundary = new Set(walk.boundary) + /** Take one change; false when `stop` ends the walk before it. */ + const take = (t: TransitionView): boolean => { + if (stop(counted, t)) return false + if (t.createdAt !== before) { + before = t.createdAt + boundary = new Set() + } + boundary.add(t.id) + if (LOCK_KINDS.has(t.kind) || t.targetId === '' || seen.has(t.targetId)) return true + seen.add(t.targetId) + const closes = CLOSES[t.kind] + if (closes !== undefined) { + closed.set(t.targetId, t.createdAt) + if (kinds.has(closes)) counted++ + } + return true + } + const paused = () => ({ closed, walk: { before, done: false, seen, boundary } }) + for (let page = 0; page < TRANSITION_PAGES; page++) { + const rows = await reader.transitions(repo, before) + let progressed = false + for (const t of rows) { + if (before !== null && t.createdAt === before && boundary.has(t.id)) continue + if (!take(t)) return paused() + progressed = true + } + if (rows.length < PAGE) return { closed, walk: { before, done: true, seen, boundary } } + if (progressed || before === null) continue + // A full page of one time, every row already read: a block of more than a page. Read the rest + // of that time by `$id`, then step past it (`<=` one millisecond earlier). + const at: number = before + let after: string | null = null + for (;;) { + const tied = await reader.transitionsAt(repo, at, after) + for (const t of tied) { + if (boundary.has(t.id)) continue + if (!take(t)) return paused() + } + if (tied.length < PAGE) break + after = tied[tied.length - 1]?.id ?? null + } + before = at - 1 + boundary = new Set() + } + return paused() +} + +/** An issue row as the board reads it. */ +export function boardItemOfIssue(row: IssueRow, repo: RepoRef, closedAt: number | null, label: string): BoardItem { + return { + id: row.id, + number: row.number, + repoId: repo.repoId, + repo: label, + kind: 'issue', + state: row.state.open ? 'open' : 'closed', + createdAt: row.createdAt, + closedAt: row.state.open ? null : closedAt, + title: row.title, + labels: row.state.labels, + assignees: row.state.assignees, + milestone: row.milestone ?? null, + author: row.author, + } +} + +/** A PR row as the board reads it. */ +export function boardItemOfPull(row: PullRow, repo: RepoRef, closedAt: number | null, label: string): BoardItem { + const state = row.state.merged ? 'merged' : row.state.open ? 'open' : 'closed' + return { + id: row.id, + number: row.number, + repoId: repo.repoId, + repo: label, + kind: 'pr', + state, + createdAt: row.createdAt, + closedAt: state === 'open' ? null : closedAt, + title: row.title, + labels: row.state.labels, + assignees: row.state.assignees, + milestone: row.review.milestone, + author: row.author, + } +} + +/** Each of `ids`' `closedAt`: the `$createdAt` of its latest move into closed or merged. */ +function closedAtOf(transitions: readonly TransitionView[]): Map { + const out = new Map() + for (const t of transitions) { + if (CLOSES[t.kind] === undefined) continue + const prev = out.get(t.targetId) + if (prev === undefined || t.createdAt > prev) out.set(t.targetId, t.createdAt) + } + return out +} + +/** `items` with `closedAt` set from `closed` where it was unknown. */ +function withClosedAt(items: readonly BoardItem[], closed: ReadonlyMap): BoardItem[] { + return items.map((i) => (i.state === 'open' || i.closedAt !== null || !closed.has(i.id) ? i : { ...i, closedAt: closed.get(i.id) as number })) +} + +/** + * Where a board's first walk stops (§2.4): before the first change older than the auto-archive + * window (`arch` days: older closes are archived unless a card keeps them, and those are read by + * id), or, with `arch` 0, once {@link CLOSED_PER_REPO} closed items are found. + */ +function stopFor(arch: number, now: number): (counted: number, next: TransitionView) => boolean { + return arch > 0 ? (_counted, next) => next.createdAt < now - arch * DAY_MS : stopAtCount +} + +/** Stop once {@link CLOSED_PER_REPO} closed items of the sources' kinds are found. */ +const stopAtCount = (counted: number): boolean => counted >= CLOSED_PER_REPO + +/** The items `cards` name that `items` lacks, read by id in their own repositories (placeholders where they cannot be opened). */ +async function cardItems(reader: BoardItemReader, input: BoardItemsInput, have: ReadonlySet): Promise<{ items: BoardItem[]; hidden: Set; missing: Set }> { + const label = input.label ?? ((r: RepoRef) => r.name) + const wanted = [...new Set(input.cards.map((c) => c.item))].filter((id) => !have.has(id)).sort(compareStrings) + const items: BoardItem[] = [] + const hidden = new Set() + const missing = new Set() + if (wanted.length === 0) return { items, hidden, missing } + const located = await reader.locate(wanted) + const byRepo = new Map() + for (const id of wanted) { + const at = located.get(id) + if (at === undefined) missing.add(id) + else byRepo.set(at.repoId, [...(byRepo.get(at.repoId) ?? []), id]) + } + for (const [repoId, ids] of byRepo) { + const repo = await repoOf(reader, input, repoId) + if (repo === null) { + for (const id of ids) missing.add(id) + continue + } + if (repo.visibility === 'private' && repo.session === undefined) { + for (const id of ids) { + hidden.add(id) + items.push(placeholder(id, repoId, located.get(id)?.kind ?? 'issue')) + } + continue + } + const rows = await reader.itemsById(repo, ids) + const closed = closedAtOf(await reader.transitionsOf(repo, rows.filter((r) => r.state !== 'open').map((r) => r.id))) + const got = new Set() + for (const r of withClosedAt(rows, closed)) { + got.add(r.id) + items.push(r.repo === undefined ? { ...r, repo: label(repo) } : r) + } + for (const id of ids) { + if (got.has(id)) continue + // located but not shown by its list: a members-only (or malformed) item this reader cannot open + hidden.add(id) + items.push(placeholder(id, repoId, located.get(id)?.kind ?? 'issue')) + } + } + return { items, hidden, missing } +} + +/** Whether `row` is a placeholder the lists keep for content this reader cannot open. */ +function membersOnlyRow(row: { readonly membersOnly?: true }): boolean { + return row.membersOnly === true +} + +/** + * Every item of the board `input` describes (see the module header): its sources' open items, + * their closed ones in the window, and the items its cards name. Ready for {@link assembleBoard}. + */ +export async function loadBoardItems(reader: BoardItemReader, input: BoardItemsInput): Promise { + const sources = sourceKinds(input.spec, input.home.repoId) + const byId = new Map() + const walks = new Map() + let partial = false + for (const [repoId, kinds] of sources) { + const repo = await repoOf(reader, input, repoId) + if (repo === null) continue + for (const kind of kinds) { + const open = await reader.openItems(repo, kind) + partial ||= !open.complete + for (const i of open.items) byId.set(i.id, i) + } + const { closed, walk } = await walkClosed(reader, repo, { before: null, done: false, seen: new Set(), boundary: new Set() }, kinds, stopFor(input.spec.arch, input.now)) + walks.set(repoId, walk) + await addClosed(reader, repo, kinds, closed, byId) + } + const extra = await cardItems(reader, input, new Set(byId.keys())) + for (const i of extra.items) byId.set(i.id, i) + return { items: [...byId.values()], hidden: extra.hidden, missing: extra.missing, partial, hasOlderClosed: [...walks.values()].some((w) => !w.done), walks } +} + +/** Read the closed items `closed` names (of the source `kinds`) into `byId`, each with its `closedAt`. */ +async function addClosed(reader: BoardItemReader, repo: RepoRef, kinds: ReadonlySet, closed: ReadonlyMap, byId: Map): Promise { + const ids = [...closed.keys()].filter((id) => !byId.has(id)) + for (const r of withClosedAt(await reader.itemsById(repo, ids), closed)) { + // the walk said closed; the row's own proved state decides (a reopen the page missed) + if (kinds.has(r.kind)) byId.set(r.id, r) + } +} + +/** + * `set` with the next stretch of each source repository's older closed items ({@link + * CLOSED_PER_REPO} more, or {@link TRANSITION_PAGES} pages): what a view asking for archived + * items, or "Show older", reads. Unchanged when nothing is older. + */ +export async function loadOlderClosed(reader: BoardItemReader, input: BoardItemsInput, set: BoardItemSet): Promise { + const sources = sourceKinds(input.spec, input.home.repoId) + const byId = new Map(set.items.map((i) => [i.id, i])) + const walks = new Map(set.walks) + for (const [repoId, walk] of set.walks) { + if (walk.done) continue + const repo = await repoOf(reader, input, repoId) + const kinds = sources.get(repoId) + if (repo === null || kinds === undefined) continue + const { closed, walk: next } = await walkClosed(reader, repo, walk, kinds, stopAtCount) + walks.set(repoId, next) + await addClosed(reader, repo, kinds, closed, byId) + } + return { ...set, items: [...byId.values()], walks, hasOlderClosed: [...walks.values()].some((w) => !w.done) } +} + +/** + * `set` with the items `cards` name that it lacks (a poll's new cards, a quick add's new issue), + * read as {@link loadBoardItems} reads card items. + */ +export async function addCardItems(reader: BoardItemReader, input: BoardItemsInput, set: BoardItemSet): Promise { + const have = new Set([...set.items.map((i) => i.id), ...set.missing]) + if (input.cards.every((c) => have.has(c.item))) return set + const extra = await cardItems(reader, input, have) + return { + ...set, + items: [...set.items, ...extra.items], + hidden: new Set([...set.hidden, ...extra.hidden]), + missing: new Set([...set.missing, ...extra.missing]), + } +} + +/** `set` with `item` in it (replacing the one with its id): an item a write just changed or made. */ +export function withItem(set: BoardItemSet, item: BoardItem): BoardItemSet { + return { ...set, items: [...set.items.filter((i) => i.id !== item.id), item] } +} + +/** Board `board` folded over `set` and `cards` at `now` (§2.4); null when its definition did not open. */ +export function assembleBoard(board: BoardView, set: BoardItemSet, cards: readonly CardDoc[], now: number): BoardFold | null { + if (board.spec === null) return null + return foldBoard({ spec: board.spec, home: board.repoId, items: set.items, cards, now }) +} + +// --------------------------------------------------------------------------------------------- +// The SDK's reader +// --------------------------------------------------------------------------------------------- + +/** Open-list pages one source reads at most (100 each). */ +const OPEN_PAGES = 30 +/** Times one page is read on when it stopped at its chunk budget. */ +const READ_ON = 5 + +/** Every row of a list's Open tab, page after page (each read on while it stopped at its budget). */ +async function allOpen(page: (p: number) => Promise<{ readonly rows: readonly Row[]; readonly hasNext: boolean; readonly searchedOf: { readonly more: boolean } | null }>): Promise<{ rows: Row[]; complete: boolean }> { + const byId = new Map() + for (let p = 1, tries = 0; p <= OPEN_PAGES; ) { + const r = await page(p) + for (const row of r.rows) byId.set(row.id, row) + if (r.hasNext) { + p++ + tries = 0 + } else if (r.searchedOf?.more === true && tries < READ_ON) { + tries++ + } else { + return { rows: [...byId.values()], complete: r.searchedOf?.more !== true } + } + } + return { rows: [...byId.values()], complete: false } +} + +const OPEN_ISSUES: Omit = { state: 'open', labels: [], author: null, assignee: null, mentions: null, sort: 'newest', text: '', pageSize: PAGE } +const OPEN_PULLS: Omit = { state: 'open', labels: [], author: null, assignee: null, sort: 'newest', text: '', pageSize: PAGE } + +/** + * The SDK's {@link BoardItemReader} for the deployment `forge` on `network`: the Issues and Pull + * requests list indexes (cached per repo for the session, dropped by a write), the `transition` + * `feed` and `perTarget` indexes, forge-collab by `$id`, and the `repo` document by id. `label` + * names a repository on its items. + */ +export function boardItemReader(sdk: EvoSDK, forge: ForgeIds, network: Network = DEFAULT_NETWORK, label: (repo: RepoRef) => string = (r) => r.name): BoardItemReader { + return { + async openItems(repo, kind) { + if (kind === 'issue') { + const { rows, complete } = await allOpen((page) => queryIssues(sdk, repo, { ...OPEN_ISSUES, page }, null, network)) + return { items: rows.filter((r) => !membersOnlyRow(r)).map((r) => boardItemOfIssue(r, repo, null, label(repo))), complete } + } + const { rows, complete } = await allOpen((page) => queryPulls(sdk, repo, { ...OPEN_PULLS, page }, null, network)) + return { items: rows.filter((r) => !membersOnlyRow(r)).map((r) => boardItemOfPull(r, repo, null, label(repo))), complete } + }, + async transitions(repo, before) { + const { documents } = await queryDocumentsWithProof(sdk, { + ...repoSource(repo).repoQuery(DOC.transition, { where: before === null ? [] : [['$createdAt', '<=', before]], orderBy: [['$createdAt', 'desc']] }), + limit: PAGE, + }) + return documents.map(transitionOf) + }, + async transitionsAt(repo, at, startAfter) { + const { documents } = await queryDocumentsWithProof(sdk, { + ...repoSource(repo).repoQuery(DOC.transition, { where: [['$createdAt', '==', at]], orderBy: [['$createdAt', 'asc']] }), + limit: PAGE, + ...(startAfter !== null ? { startAfter } : {}), + }) + return documents.map(transitionOf) + }, + async itemsById(repo, ids) { + const issues = (await issueRowsById(sdk, repo, ids, network)).filter((r) => !membersOnlyRow(r)) + const got = new Set(issues.map((r) => r.id)) + const pulls = (await pullRowsById(sdk, repo, ids.filter((id) => !got.has(id)), network)).filter((r) => !membersOnlyRow(r)) + return [...issues.map((r) => boardItemOfIssue(r, repo, null, label(repo))), ...pulls.map((r) => boardItemOfPull(r, repo, null, label(repo)))] + }, + async transitionsOf(repo, ids) { + const out: TransitionView[] = [] + const sorted = [...new Set(ids)].sort() + for (let i = 0; i < sorted.length; i += PAGE) { + const batch = sorted.slice(i, i + PAGE) + const docs = await queryAllDocuments(sdk, repoSource(repo).targetQuery(DOC.transition, { where: [['targetId', 'in', batch]], orderBy: [['targetId', 'asc']] })) + out.push(...docs.map(transitionOf)) + } + return out + }, + async locate(ids) { + const out = new Map() + // any repository's forge-collab: the network's, which every repository shares + const anyRepo: RepoRef = { forge, repoId: '', ownerId: '', name: '', visibility: 'public' } + for (const [type, kind] of [[DOC.issue, 'issue'], [DOC.patch, 'pr']] as const) { + const todo = ids.filter((id) => !out.has(id)) + for (let i = 0; i < todo.length; i += PAGE) { + const batch = todo.slice(i, i + PAGE) + const { documents } = await queryDocumentsWithProof(sdk, { ...repoSource(anyRepo).targetQuery(type, { where: [['$id', 'in', batch]], orderBy: [['$id', 'asc']] }), limit: PAGE }) + for (const d of documents) { + const id = typeof d['$id'] === 'string' ? d['$id'] : '' + const repoId = asIdentifierString(d['repoId']) + if (id !== '' && repoId !== '') out.set(id, { repoId, kind }) + } + } + } + return out + }, + async repo(repoId) { + const doc = await readRepoById(sdk, forge, repoId) + return doc === null ? null : repoRefOf(forge, doc) + }, + } +} diff --git a/forge-web/lib/repo/board-writes.ts b/forge-web/lib/repo/board-writes.ts new file mode 100644 index 000000000..2dabe984d --- /dev/null +++ b/forge-web/lib/repo/board-writes.ts @@ -0,0 +1,657 @@ +/** + * Board and card writes (`docs/design/boards.md` §3, §5): every one a single document operation + * on forge-meta, the signer's role checked first (`roleClaim`: a board claims `r` 1, a card 1 or + * 2; a refusal drops the cached membership, `refreshRoleOnRefusal`), and refused before signing + * where the contract or the board rules would refuse it ({@link BoardWriteError}): a role that + * may not, a name or definition the schema refuses, a closed or deleted board (read-only), a + * column, rank or field value the board does not have, a rank with no room (`re-rank`). + * + * Both types are one mutable document per member (§3: a board per (home repo, key, member), a + * card per (item, home repo, board, member)), so a write replaces the signer's own document when + * they have one and creates it otherwise. A card carries a member's whole view of the item, and + * the newest card over every member's wins whole (§2.4), so {@link writeCard} reads the item's + * newest card immediately before signing and applies only its own change to it (§3.2): two + * members editing different fields both land unless their writes cross within the read-to-sign + * latency. + * + * A private repository's board (`name`, `spec`) and card (`col`, `rank`, `f`) are sealed into + * `enc` under the current epoch (`lib/private/board.ts`, private-repos.md §4.6); every save + * re-seals the whole payload. A card from a private home repository naming another repository's + * item publishes that the home repository tracks it (§3.3): {@link writeCard} refuses it unless + * the caller confirmed ({@link crossRepoCardNeedsConfirm}). + */ + +import type { EvoSDK } from '@dashevo/evo-sdk' +import { sha256 } from '@noble/hashes/sha2.js' + +import { decodeIdentifier } from '../auth/base58' +import { sealBoardDoc, type BoardFields, type CardFields } from '../private' +import { + CARD_ACTIVE, + CARD_ARCHIVED, + CARD_REMOVED, + NAME_MAX, + SPEC_MAX_BYTES, + bottomRank, + fieldById, + fieldValueOk, + isExplicitRank, + iterationAt, + newestCards, + parseFieldValues, + rankBetween, + rerank, + serializeFieldValues, + serializeSpec, + topRank, + type BoardItem, + type BoardSpec, + type FieldValue, + type Placement, + type RankError, + type SpecError, +} from '../rules/boards' +import { ConsensusRefusal, DUPLICATE_UNIQUE_CODE, contentHash, createDocumentIdempotent, queryDocumentsWithProof, replaceDocumentIdempotent, type ReplaceResult, type WriteAuth, type WriteResult } from '../sdk' +import { utf8Length } from '../view/issue-query' +import { BOARD_STATE_CODE, noteBoardWrite, ownRevision, readBoardDefinition, readItemCardDocs, type BoardCard, type BoardState, type BoardView } from './boards' +import { DOC, type RepoRef } from './contract' +import { keyedContentKey } from './members-writes' +import { privateWriter, sealedIntent } from './private-writes' +import { refreshRoleOnRefusal, roleClaim } from './role-claim' +import { contractOf, repoSource } from './source' +import { createIssue } from './writes' + +/** Why a board write was refused before anything was signed. */ +export type BoardRefusal = + /** The board is closed or deleted: read-only until reopened. */ + | 'closed' + /** The board's definition did not open or parse: nothing on it can be checked. */ + | 'unreadable' + /** The name, definition, column, rank or a field value is not one the schema or the board admits. */ + | 'input' + /** No rank fits between the neighbours: re-rank the column first (§2.6). */ + | 're-rank' + /** A private home repository's card naming another repository's item, not confirmed (§3.3). */ + | 'cross-repo' + /** No such board. */ + | 'missing' + +/** A board write refused before signing, with the reason shown as is. */ +export class BoardWriteError extends Error { + constructor( + readonly refusal: BoardRefusal, + message: string, + /** For `re-rank`: the column (or grouping value) to re-rank. */ + readonly column?: number, + ) { + super(message) + this.name = 'BoardWriteError' + } +} + +const SPEC_PROBLEM: Readonly> = { + json: 'the board definition is not valid JSON', + version: 'the board definition is of a version this build does not write', + size: `a board definition is at most ${SPEC_MAX_BYTES} bytes`, + desc: 'a board description is at most 1024 characters', + columns: 'a board has 1 to 20 columns', + column: 'a column needs a unique name of 1-63 characters and an id of 1-255', + def: 'the default column is not one of the board’s columns', + done: 'the Done column is not one of the board’s columns', + sources: 'a board has at most 5 sources', + source: 'a source names issues, pull requests or both, with a query of at most 512 characters', + fields: 'a board has at most 12 fields', + field: 'a field needs a unique name and an id of 1-255, and may not be named like a query key', + options: 'a select field has 1-30 options with unique names', + views: 'a board has at most 8 views', + view: 'a view’s grouping, swimlanes, sort and columns must name the board’s own fields', + arch: 'auto-archive is 0 to 3650 days', +} + +/** The `board.name` schema: 1-63 characters, at most 252 bytes, no control character, something visible. */ +const BOARD_NAME = /^[^\x00-\x1f\x7f]*[^\s\x00-\x1f\x7f][^\x00-\x1f\x7f]*$/u + +/** + * The name and canonical definition JSON a board write stores, or the refusal: a name the schema + * refuses, or a definition the board rules refuse (`serializeSpec`, which also keeps it within + * 4096 bytes). + */ +export function checkBoardInput(input: { readonly name: string; readonly spec: BoardSpec }): { readonly name: string; readonly spec: string } { + const name = input.name.trim() + if (name === '' || [...name].length > NAME_MAX || utf8Length(name) > 252 || !BOARD_NAME.test(name)) { + throw new BoardWriteError('input', 'a board name is 1-63 characters, with no control characters') + } + const out = serializeSpec(input.spec) + if ('error' in out) throw new BoardWriteError('input', SPEC_PROBLEM[out.error]) + return { name, spec: out.json } +} + +function refuseUnlessOpen(board: BoardView): void { + if (board.state !== 'open') throw new BoardWriteError('closed', board.state === 'deleted' ? 'this board was deleted' : 'this board is closed: reopen it to change it') +} + +/** A board key (1 … 2³²−1) from `bytes`. */ +function keyOf(bytes: Uint8Array): number { + const k = (((bytes[0] as number) << 24) | ((bytes[1] as number) << 16) | ((bytes[2] as number) << 8) | (bytes[3] as number)) >>> 0 + return k === 0 ? 1 : k +} + +/** + * A new board's key (§2.1): a random u32, drawn from `crypto`; with an `intent`, derived from it + * and the repository (`sha256`), so a retry of one create names the same board and the write + * engine replays it rather than making a second. + */ +export function newBoardKey(repo: Pick, intent?: string, attempt = 0): number { + if (intent === undefined) return keyOf(crypto.getRandomValues(new Uint8Array(4))) + return keyOf(sha256(new TextEncoder().encode(`dash-forge board key\u0000${repo.repoId}\u0000${intent}\u0000${attempt}`))) +} + +/** Every board revision (by anyone) that names key `key` of `repo`: none when the key is free. */ +async function keyTaken(sdk: EvoSDK, repo: RepoRef, key: number): Promise { + const { documents } = await queryDocumentsWithProof(sdk, { ...repoSource(repo).repoQuery(DOC.board, { where: [['key', '==', key]], orderBy: [['key', 'asc'], ['$ownerId', 'asc']] }), limit: 100 }) + return documents.map((d) => ({ id: String(d['$id'] ?? ''), ownerId: String(d['$ownerId'] ?? '') })) +} + +/** The fields a board write carries: plaintext, or sealed under the repository's current epoch. */ +async function boardPayload(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, key: number, fields: BoardFields, intent?: string): Promise<{ readonly data: Record; readonly intent?: string; readonly contentKey?: string }> { + if (repo.visibility !== 'private') return { data: { name: fields.name, spec: fields.spec }, ...(intent ? { intent } : {}) } + const w = await privateWriter(sdk, auth, repo) + const enc = await sealBoardDoc(w.keys, decodeIdentifier(auth.identityId), { type: 'board', key }, fields) + const sealedFor = sealedIntent(intent, w.keys) + return { data: { epoch: w.keys.epoch, enc }, ...(sealedFor ? { intent: sealedFor } : {}), contentKey: await keyedContentKey(w.keys, contentHash(DOC.board, { repoId: repo.repoId, key, ...fields })) } +} + +/** The outcome of a board write. */ +export interface BoardWritten { + readonly key: number + readonly documentId: string + /** A new document (the signer's first revision of this board), or a replace of theirs. */ + readonly created: boolean + readonly result: WriteResult | ReplaceResult +} + +/** + * Write the signer's revision of board `key`: replace their own document when they have one + * (`own`), else create one. `state` is plaintext; the name and definition sealed in a private + * repository. + */ +async function writeBoardRevision( + sdk: EvoSDK, + auth: WriteAuth, + repo: RepoRef, + key: number, + fields: BoardFields, + state: BoardState, + own: { readonly id: string } | null, + intent?: string, +): Promise { + const contractId = contractOf(repo.forge, DOC.board) + const base = { repoId: decodeIdentifier(repo.repoId), key, state: BOARD_STATE_CODE[state] } + const claim = await roleClaim(sdk, auth, repo, DOC.board, base) + const payload = await boardPayload(sdk, auth, repo, key, fields, intent) + try { + if (own !== null) { + // A replace re-states every content field: a sealed revision drops the plaintext ones and back. + const changes = repo.visibility === 'private' ? { ...payload.data, name: undefined, spec: undefined, state: base.state, ...claim } : { ...payload.data, enc: undefined, epoch: undefined, state: base.state, ...claim } + const result = await refreshRoleOnRefusal(repo, auth, DOC.board, () => replaceDocumentIdempotent(sdk, auth, { contractId, documentType: DOC.board, documentId: own.id, changes, repo: repo.repoId, expectRepoId: repo.repoId })) + return { key, documentId: own.id, created: false, result } + } + const result = await refreshRoleOnRefusal(repo, auth, DOC.board, () => + createDocumentIdempotent(sdk, auth, { + contractId, + documentType: DOC.board, + data: { ...base, ...payload.data, ...claim }, + ...(payload.intent ? { intent: payload.intent } : {}), + ...(payload.contentKey ? { contentKey: payload.contentKey } : {}), + }), + ) + return { key, documentId: result.documentId, created: true, result } + } finally { + noteBoardWrite(repo) + } +} + +/** + * Create a board in `repo` (§2.1): a new key, unused by any revision (checked before signing; + * with `intent`, derived from it so a retry names the same board), and the signer's first + * revision of it. Maintainers and writers only. + */ +export async function createBoard(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, input: { readonly name: string; readonly spec: BoardSpec; readonly intent?: string }): Promise { + const fields = checkBoardInput(input) + for (let attempt = 0; attempt < 8; attempt++) { + const key = newBoardKey(repo, input.intent, attempt) + const taken = await keyTaken(sdk, repo, key) + if (taken.length === 0) return writeBoardRevision(sdk, auth, repo, key, fields, 'open', null, input.intent) + // a retry of this create whose first attempt landed: its own revision holds the key + const own = taken[0] + if (input.intent !== undefined && taken.length === 1 && own?.ownerId === auth.identityId) return writeBoardRevision(sdk, auth, repo, key, fields, 'open', own, input.intent) + } + // copy-lint-ignore: 2^32 keys and eight draws: never seen in practice + throw new Error('could not find an unused board key; try again') +} + +/** What {@link saveBoard} changes: the name, the definition, or both. */ +export interface BoardChange { + readonly name?: string + readonly spec?: BoardSpec +} + +/** + * Save a change to board `key` (its name or definition, views included): read its newest + * revision fresh, apply the change, and replace the signer's own revision (or create one). + * Refused for a closed or deleted board, or one whose definition did not open. + */ +export async function saveBoard(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, key: number, change: BoardChange, { intent }: { readonly intent?: string } = {}): Promise { + const board = await readBoardDefinition(sdk, repo, key) + if (board === null) throw new BoardWriteError('missing', 'no such board') + refuseUnlessOpen(board) + if (board.spec === null || board.name === null) throw new BoardWriteError('unreadable', "this board's definition can't be read here, so it can't be edited") + const fields = checkBoardInput({ name: change.name ?? board.name, spec: change.spec ?? board.spec }) + return writeBoardRevision(sdk, auth, repo, key, fields, 'open', ownRevision(board, auth.identityId), intent) +} + +/** + * Open, close (read-only, listed under Closed) or delete board `key` (§3.1 `state`): a new + * revision with the newest one's name and definition. A writer may close or delete a + * maintainer's board, as with labels. A deleted board stays deleted. + */ +export async function setBoardState(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, key: number, state: BoardState, { intent }: { readonly intent?: string } = {}): Promise { + const board = await readBoardDefinition(sdk, repo, key) + if (board === null) throw new BoardWriteError('missing', 'no such board') + if (board.state === 'deleted') throw new BoardWriteError('closed', 'this board was deleted') + if (board.spec === null || board.name === null) throw new BoardWriteError('unreadable', "this board's definition can't be read here, so it can't be changed") + const fields = checkBoardInput({ name: board.name, spec: board.spec }) + return writeBoardRevision(sdk, auth, repo, key, fields, state, ownRevision(board, auth.identityId), intent) +} + +// --------------------------------------------------------------------------------------------- +// Cards +// --------------------------------------------------------------------------------------------- + +/** The item a card names: its id, and its repository (for the cross-repository confirm, §3.3). */ +export interface CardItem { + readonly id: string + readonly repoId: string +} + +/** What a card write changes; everything else is carried over from the item's newest card. */ +export interface CardPatch { + /** The column id; 0 for "No status". */ + readonly col?: number + /** An explicit rank (§2.6). */ + readonly rank?: string + /** Field values by field id: a value sets it, null clears it. */ + readonly fields?: Readonly> + /** 0 active, 1 archived, 2 removed (`CARD_*`). */ + readonly state?: number +} + +/** A card write's options. */ +export interface CardWriteOptions { + readonly intent?: string + /** The signer confirmed a private home repository's card for another repository's item (§3.3). */ + readonly confirmCrossRepo?: boolean +} + +/** The outcome of a card write. */ +export interface CardWritten { + /** + * The card as written, for an optimistic view: its `updatedAt` is this client's clock, not the + * block time, so never merge it into read cards (`mergeCards`); the next poll reads the real one. + */ + readonly card: BoardCard + readonly created: boolean + readonly result: WriteResult | ReplaceResult +} + +/** + * Whether a card for `item` on a board of `home` must be confirmed first (§3.3): `item` is + * plaintext and indexed, so a private repository's card naming another repository's item tells + * everyone that the private repository tracks it. + */ +export function crossRepoCardNeedsConfirm(home: Pick, itemRepoId: string): boolean { + return home.visibility === 'private' && itemRepoId !== home.repoId +} + +/** Refuse an unconfirmed card from a private `home` for another repository's item (§3.3). */ +function refuseUnlessConfirmed(home: Pick, itemRepoId: string, confirmed: boolean | undefined): void { + if (crossRepoCardNeedsConfirm(home, itemRepoId) && confirmed !== true) { + throw new BoardWriteError('cross-repo', 'This board is in a private repository. Placing an item of another repository on it shows everyone that this repository tracks that item.') + } +} + +/** Refuse a patch the board or the schema would refuse. */ +function checkPatch(spec: BoardSpec, patch: CardPatch): void { + if (patch.col !== undefined && patch.col !== 0 && !spec.columns.some((c) => c.id === patch.col)) throw new BoardWriteError('input', 'that column is not on this board') + if (patch.rank !== undefined && !isExplicitRank(patch.rank)) throw new BoardWriteError('input', 'a rank is 1-63 rank digits, not ending in 0') + if (patch.state !== undefined && ![CARD_ACTIVE, CARD_ARCHIVED, CARD_REMOVED].includes(patch.state)) throw new BoardWriteError('input', 'a card is active, archived or removed') + for (const [id, v] of Object.entries(patch.fields ?? {})) { + const field = fieldById(spec, Number(id)) + if (field === undefined) throw new BoardWriteError('input', 'that field is not on this board') + if (v !== null && !fieldValueOk(field, v)) throw new BoardWriteError('input', `that is not a valid value for ${field.name}`) + } +} + +/** + * The card `patch` makes over `base` (the item's newest card, any member's, or none): its column, + * rank and state replaced where given, its field values merged (a null clears one). + */ +export function patchedCard(spec: BoardSpec, base: BoardCard | null, patch: CardPatch): { readonly col: number | null; readonly rank: string | null; readonly f: string | null; readonly state: number } { + const values: Record = { ...parseFieldValues(base?.f ?? null, spec) } + for (const [id, v] of Object.entries(patch.fields ?? {})) { + if (v === null) delete values[id] + else values[id] = v + } + const f = serializeFieldValues(values, spec) + if ('error' in f) throw new BoardWriteError('input', 'these field values are over 2048 bytes') + const rank = patch.rank ?? (base !== null && isExplicitRank(base.rank) ? base.rank : null) + return { col: patch.col ?? base?.col ?? null, rank, f: f.json === '{}' ? null : f.json, state: patch.state ?? base?.state ?? CARD_ACTIVE } +} + +/** + * Write the signer's card for `item` on `board` of `repo` (§3.2): refused for a closed board, a + * patch the board does not admit, or (unconfirmed) a private home's cross-repository item; then + * the item's cards are read fresh, `patch` is applied to the newest, and the signer's own card is + * replaced (or created: a create that meets the signer's card made meanwhile, in another tab, + * replaces it instead). + */ +export async function writeCard(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, board: BoardView, item: CardItem, patch: CardPatch, opts: CardWriteOptions = {}): Promise { + // What the page's copy of the board refuses is refused at once; the fresh read below decides. + refuseUnlessOpen(board) + refuseUnlessConfirmed(repo, item.repoId, opts.confirmCrossRepo) + const ids = { repoId: decodeIdentifier(repo.repoId), board: board.key, item: decodeIdentifier(item.id) } + // The role and (private) the write epoch first: the item's cards are read as late as possible. + const claim = await roleClaim(sdk, auth, repo, DOC.card, ids) + const writer = repo.visibility === 'private' ? await privateWriter(sdk, auth, repo) : null + // The definition read with the cards: a field, option or column another member added since the + // page read it is kept (the values a stale definition does not know would be dropped), and a + // board closed meanwhile is read-only. + const [fresh, { cards, own: ownId }] = await Promise.all([readBoardDefinition(sdk, repo, board.key), readItemCardDocs(sdk, repo, board.key, item.id, auth.identityId)]) + if (fresh === null) throw new BoardWriteError('missing', 'no such board') + refuseUnlessOpen(fresh) + const spec = fresh.spec + if (spec === null) throw new BoardWriteError('unreadable', "this board's definition can't be read here, so its cards can't be changed") + checkPatch(spec, patch) + // A newest card this reader cannot open holds values it cannot carry over: the newest it can open is the base. + const next = patchedCard(spec, newestCards(cards.filter((c) => c.unreadable !== true)).get(item.id) ?? null, patch) + const contractId = contractOf(repo.forge, DOC.card) + const base = { ...ids, state: next.state } + const fields: CardFields = { ...(next.col !== null ? { col: next.col } : {}), ...(next.rank !== null ? { rank: next.rank } : {}), ...(next.f !== null ? { f: next.f } : {}) } + let content: Record = { ...fields } + let intent = opts.intent + let contentKey: string | undefined + if (writer !== null) { + content = { epoch: writer.keys.epoch, enc: await sealBoardDoc(writer.keys, decodeIdentifier(auth.identityId), { type: 'card', board: board.key, item: ids.item }, fields) } + intent = sealedIntent(intent, writer.keys) + contentKey = await keyedContentKey(writer.keys,contentHash(DOC.card, { repoId: repo.repoId, board: board.key, item: item.id, state: next.state, ...fields })) + } + const replace = (documentId: string): Promise => { + // every content field re-stated: an absent one is removed (a cleared rank or field values) + const plain = repo.visibility === 'private' ? { col: undefined, rank: undefined, f: undefined } : { col: next.col ?? undefined, rank: next.rank ?? undefined, f: next.f ?? undefined, enc: undefined, epoch: undefined } + return refreshRoleOnRefusal(repo, auth, DOC.card, () => replaceDocumentIdempotent(sdk, auth, { contractId, documentType: DOC.card, documentId, changes: { ...plain, ...content, state: next.state, ...claim }, repo: repo.repoId, expectRepoId: repo.repoId })) + } + const written = (documentId: string, created: boolean, result: WriteResult | ReplaceResult): CardWritten => ({ + card: { id: documentId, ownerId: auth.identityId, updatedAt: Date.now(), item: item.id, col: next.col, rank: next.rank, f: next.f, state: next.state }, + created, + result, + }) + try { + if (ownId !== null) return written(ownId, false, await replace(ownId)) + try { + const result = await refreshRoleOnRefusal(repo, auth, DOC.card, () => + createDocumentIdempotent(sdk, auth, { contractId, documentType: DOC.card, data: { ...base, ...content, ...claim }, ...(intent ? { intent } : {}), ...(contentKey ? { contentKey } : {}) }), + ) + return written(result.documentId, true, result) + } catch (e) { + if (!(e instanceof ConsensusRefusal && e.code === DUPLICATE_UNIQUE_CODE)) throw e + // the signer's card for this item appeared since the read (another tab): replace it + const mine = (await readItemCardDocs(sdk, repo, board.key, item.id, auth.identityId)).own + if (mine === null) throw e + return written(mine, false, await replace(mine)) + } + } finally { + noteBoardWrite(repo) + } +} + +// --------------------------------------------------------------------------------------------- +// Moving and ranking (§2.6, §5.2) +// --------------------------------------------------------------------------------------------- + +/** A card in a column's shown order, as a move reads it: its item and its effective rank (the fold's). */ +export interface RankedCard { + readonly id: string + readonly rank: string +} + +const RANK_PROBLEM: Readonly> = { + invalid: 'the neighbouring ranks are not ranks', + order: 'the neighbours are out of order: reload the board', + 're-rank': 'There is no room left between these cards. Re-rank this column first.', +} + +/** + * The rank that drops a card at position `index` (0 = the top) of `column`, the column's cards in + * rank order without the one moving (§2.6): the top is `topRank` (above the sourced pool), the + * bottom `bottomRank` (below it), elsewhere `rankBetween` the two neighbours. + */ +export function rankForDrop(column: readonly RankedCard[], index: number): { readonly rank: string } | { readonly error: RankError } { + const at = Math.max(0, Math.min(Math.floor(index), column.length)) + if (column.length === 0) return topRank(null) + if (at === 0) return topRank(column[0]?.rank ?? null) + if (at === column.length) return bottomRank(column[column.length - 1]?.rank ?? null) + return rankBetween(column[at - 1]?.rank ?? null, column[at]?.rank ?? null) +} + +/** Where a move puts the card: a column, or (a view grouped by a field, §4.1) a field's value. */ +export type MoveTarget = { readonly col: number } | { readonly field: number; readonly value: FieldValue | null } + +/** + * The rank that drops `item` just before item `before` of `column` (the target column's cards in + * rank order; the moving card itself may be among them and is left out), or at its bottom when + * `before` is null (or not in it): what a drop "above card X" asks for, whatever the card's + * place before the move. + */ +export function rankBefore(column: readonly RankedCard[], item: string, before: string | null): { readonly rank: string } | { readonly error: RankError } { + const others = column.filter((c) => c.id !== item) + const at = before === null ? -1 : others.findIndex((c) => c.id === before) + return rankForDrop(others, at < 0 ? others.length : at) +} + +/** + * Move `item` to `target`, just before item `before` of `column` (the target column's cards in + * rank order; null: at the bottom; see {@link rankBefore}): one card write with the new column + * (or field value) and rank. Refused before signing with `re-rank` when no rank fits + * ({@link rerankColumn}). + */ +export async function moveCard( + sdk: EvoSDK, + auth: WriteAuth, + repo: RepoRef, + board: BoardView, + item: CardItem, + target: MoveTarget, + column: readonly RankedCard[], + before: string | null, + opts: CardWriteOptions = {}, +): Promise { + const r = rankBefore(column, item.id, before) + if ('error' in r) throw new BoardWriteError(r.error === 're-rank' ? 're-rank' : 'input', RANK_PROBLEM[r.error], 'col' in target ? target.col : undefined) + const patch: CardPatch = 'col' in target ? { col: target.col, rank: r.rank } : { fields: { [target.field]: target.value }, rank: r.rank } + return writeCard(sdk, auth, repo, board, item, patch, opts) +} + +/** The outcome of a write to several cards: each item's, in order; the first failure stops the rest. */ +export interface BulkWritten { + readonly written: readonly CardWritten[] + /** The item whose write failed, and why; null when every write landed. */ + readonly failed: { readonly item: string; readonly error: unknown } | null + /** Items not written because an earlier write failed. */ + readonly skipped: readonly string[] +} + +/** Write `patchOf(item)` to each of `items` in turn, stopping at the first failure. */ +async function writeEach(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, board: BoardView, items: readonly CardItem[], patchOf: (item: CardItem, i: number) => CardPatch, opts: CardWriteOptions): Promise { + const written: CardWritten[] = [] + for (const [i, item] of items.entries()) { + try { + written.push(await writeCard(sdk, auth, repo, board, item, patchOf(item, i), { ...opts, ...(opts.intent ? { intent: `${opts.intent}:${item.id}` } : {}) })) + } catch (error) { + return { written, failed: { item: item.id, error }, skipped: items.slice(i + 1).map((x) => x.id) } + } + } + return { written, failed: null, skipped: [] } +} + +/** How many of the writes to `items` create a card (the signer has none for it) and how many replace one: what is priced first. */ +export function planCardWrites(cards: readonly BoardCard[], me: string, items: readonly string[]): { readonly creates: number; readonly replaces: number } { + const mine = new Set(cards.filter((c) => c.ownerId === me).map((c) => c.item)) + const creates = items.filter((id) => !mine.has(id)).length + return { creates, replaces: items.length - creates } +} + +/** + * Re-rank a column (§2.6): `items`, the column's cards in their shown order, get evenly spaced + * ranks between `0` and `V` (`rerank`), one write each (a create for each item the signer has no + * card for, priced first with {@link planCardWrites}). + */ +export async function rerankColumn(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, board: BoardView, items: readonly CardItem[], opts: CardWriteOptions = {}): Promise { + const r = rerank(items.length) + if ('error' in r) throw new BoardWriteError('input', 'too many cards to re-rank at once') + return writeEach(sdk, auth, repo, board, items, (_item, i) => ({ rank: r.ranks[i] as string }), opts) +} + +/** Put `items` on the board (§5.3): an active card each, in column `col` when given. */ +export function addItems(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, board: BoardView, items: readonly CardItem[], col?: number, opts: CardWriteOptions = {}): Promise { + return writeEach(sdk, auth, repo, board, items, () => ({ state: CARD_ACTIVE, ...(col !== undefined ? { col } : {}) }), opts) +} + +/** Archive `items` (hidden unless a view asks for `is:archived`, §2.4). */ +export function archiveItems(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, board: BoardView, items: readonly CardItem[], opts: CardWriteOptions = {}): Promise { + return writeEach(sdk, auth, repo, board, items, () => ({ state: CARD_ARCHIVED }), opts) +} + +/** Restore archived `items` (an active card each). */ +export function unarchiveItems(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, board: BoardView, items: readonly CardItem[], opts: CardWriteOptions = {}): Promise { + return writeEach(sdk, auth, repo, board, items, () => ({ state: CARD_ACTIVE }), opts) +} + +/** Remove `items` from the board, even where a source includes them (§2.4). */ +export function removeItems(sdk: EvoSDK, auth: WriteAuth, repo: RepoRef, board: BoardView, items: readonly CardItem[], opts: CardWriteOptions = {}): Promise { + return writeEach(sdk, auth, repo, board, items, () => ({ state: CARD_REMOVED }), opts) +} + +/** + * The items "move open items to the next iteration" moves (§5.4): every open item on the board + * (not archived) whose iteration field `fieldId` is the current iteration at `now`, outside the + * Done column; and that next iteration's index. Nothing when there is no current iteration. + */ +export function nextIterationPlan(spec: BoardSpec, fieldId: number, items: readonly BoardItem[], placements: readonly Placement[], now: number): { readonly next: number; readonly items: readonly CardItem[] } | null { + const field = fieldById(spec, fieldId) + if (field === undefined || field.type !== 'iter') return null + const current = iterationAt(field, now) + if (current === null || current + 1 > 65535) return null + const byId = new Map(items.map((i) => [i.id, i])) + const moving: CardItem[] = [] + for (const p of placements) { + const item = byId.get(p.id) + if (item === undefined || item.state !== 'open' || !p.on || p.archived !== null) continue + if (spec.done !== 0 && p.col === spec.done) continue + if (p.fields[String(fieldId)] !== current) continue + moving.push({ id: item.id, repoId: item.repoId }) + } + return { next: current + 1, items: moving } +} + +/** Carry the current iteration's unfinished items into the next (§5.4): {@link nextIterationPlan}, one write each. */ +export async function moveOpenToNextIteration( + sdk: EvoSDK, + auth: WriteAuth, + repo: RepoRef, + board: BoardView, + fieldId: number, + items: readonly BoardItem[], + placements: readonly Placement[], + now: number, + opts: CardWriteOptions = {}, +): Promise { + if (board.spec === null) throw new BoardWriteError('unreadable', "this board's definition can't be read here") + const plan = nextIterationPlan(board.spec, fieldId, items, placements, now) + if (plan === null) throw new BoardWriteError('input', 'there is no current iteration to move items from') + return writeEach(sdk, auth, repo, board, plan.items, () => ({ fields: { [fieldId]: plan.next } }), opts) +} + +/** The outcome of {@link quickAddIssue}: the new issue, as the board reads it, and its card (null when only the issue landed). */ +export interface QuickAdded { + readonly item: BoardItem + readonly card: CardWritten | null + /** Why the card was not written after the issue was (the issue exists; place it again). */ + readonly cardError: unknown +} + +/** + * Quick add (§5.3): a title makes a real issue in `target` (the home repository, or a source + * repository from the menu) with the issue create everyone uses, then places it in column `col` + * at the bottom of `column` (the column's cards in rank order). Two writes; a card that fails + * after the issue landed is reported, not thrown, so the issue is not made twice. + */ +export async function quickAddIssue( + sdk: EvoSDK, + auth: WriteAuth, + home: RepoRef, + board: BoardView, + input: { readonly title: string; readonly col: number; readonly column?: readonly RankedCard[]; readonly target?: RepoRef; readonly intent?: string; readonly confirmCrossRepo?: boolean }, +): Promise { + refuseUnlessOpen(board) + if (board.spec === null) throw new BoardWriteError('unreadable', "this board's definition can't be read here") + checkPatch(board.spec, { col: input.col }) + const target = input.target ?? home + refuseUnlessConfirmed(home, target.repoId, input.confirmCrossRepo) + const title = input.title.trim() + if (title === '') throw new BoardWriteError('input', 'an issue needs a title') + const issue = await createIssue(sdk, auth, target, { title, body: '', ...(input.intent ? { intent: input.intent } : {}) }) + const item: BoardItem = { id: issue.documentId, number: issue.number, repoId: target.repoId, repo: target.name, kind: 'issue', state: 'open', createdAt: Date.now(), closedAt: null, title, labels: [], assignees: [], milestone: null, author: auth.identityId } + const column = input.column ?? [] + const rank = column.length === 0 ? null : rankBefore(column, '', null) + try { + const card = await writeCard(sdk, auth, home, board, item, { col: input.col, ...(rank !== null && 'rank' in rank ? { rank: rank.rank } : {}) }, { ...(input.intent ? { intent: `${input.intent}:card` } : {}), confirmCrossRepo: true }) + return { item, card, cardError: null } + } catch (cardError) { + return { item, card: null, cardError } + } +} + +/** + * An existing item a quick add names (§5.3): `#12`, `owner/name#12`, or an issue, PR or number + * link of this app (`/repo/issue/?owner=…&name=…&number=12`, `target-href.ts`); null for a title. + * The owner and name are as written (an owner's DPNS name or identity id), resolved by the caller. + */ +export function parseItemReference(text: string): { readonly owner?: string; readonly name?: string; readonly number: number } | null { + const t = text.trim() + let m = /^#(\d{1,10})$/.exec(t) + if (m) return { number: Number(m[1]) } + m = /^([^\s/#]+)\/([^\s/#]+)#(\d{1,10})$/.exec(t) + if (m) return { owner: m[1] as string, name: m[2] as string, number: Number(m[3]) } + let url: URL + try { + url = new URL(t) + } catch { + return null + } + if (!/^\/repo\/(issue|pull|number)\/?$/.test(url.pathname)) return null + const owner = url.searchParams.get('owner') + const name = url.searchParams.get('name') + const n = url.searchParams.get('number') + if (owner === null || name === null || n === null || !/^\d{1,10}$/.test(n)) return null + return { owner, name, number: Number(n) } +} + +/** Issue or PR number `number` of `repo` (the `number` index of each), or null. */ +export async function resolveItemByNumber(sdk: EvoSDK, repo: RepoRef, number: number): Promise<{ readonly id: string; readonly kind: 'issue' | 'pr' } | null> { + for (const [type, kind] of [[DOC.issue, 'issue'], [DOC.patch, 'pr']] as const) { + const { documents } = await queryDocumentsWithProof(sdk, { ...repoSource(repo).repoQuery(type, { where: [['number', '==', number]], orderBy: [['number', 'asc']] }), limit: 1 }) + const id = documents[0]?.['$id'] + if (typeof id === 'string') return { id, kind } + } + return null +} diff --git a/forge-web/lib/repo/boards.test.ts b/forge-web/lib/repo/boards.test.ts new file mode 100644 index 000000000..26a45fbf3 --- /dev/null +++ b/forge-web/lib/repo/boards.test.ts @@ -0,0 +1,468 @@ +/** + * The board data layer (`docs/design/boards.md`): reads (newest revision per key, cards, the + * poll's `>=` and its dedupe, an item's boards), card writes over a fresh read of the item's + * newest card (§3.2), ranks on a move (§2.6), refusals before signing, and a private repo's + * sealed boards and cards round-tripping through the writes and the reads (§3.3). + */ + +import type { EvoSDK } from '@dashevo/evo-sdk' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { base58Encode } from '../auth/base58' +import { IdSet } from '../private/ids' +import { EpochKeys } from '../private/keys' +import { RoleRefusedError } from '../rules/roles' +import { defaultSpec, foldBoard, parseFieldValues, serializeSpec, type BoardItem, type BoardSpec } from '../rules/boards' +import type { CardPatch } from './board-writes' +import type { RepoRef } from './contract' +import type { PrivateSession } from './private-session' + +type Doc = Record +const id = (n: number): string => base58Encode(new Uint8Array(32).fill(n)) +const ME = id(1) +const OTHER = id(2) +const REPO_ID = id(9) +const ITEM = id(20) +const ITEM2 = id(21) +const FORGE = { core: 'CORE', collab: 'COLLAB', community: 'COMMUNITY', meta: 'META', group: 'GROUP' } +const REPO: RepoRef = { forge: FORGE, repoId: REPO_ID, ownerId: ME, name: 'repo', visibility: 'public' } +const AUTH = { identityId: ME, network: 'devnet' as const, getSigningKeyWif: () => 'W' } +const sdk = {} as EvoSDK +const SPEC: BoardSpec = defaultSpec(REPO_ID, Date.UTC(2026, 9, 26)) + +/** The documents queries answer, by type. */ +let stored: Record = {} +const created: { type: string; data: Doc; intent?: string }[] = [] +const replaced: { type: string; id: string; changes: Doc }[] = [] +let role: 'maintainer' | 'writer' | 'triage' | 'reader' = 'writer' +let duplicateOnCreate = false + +function matches(d: Doc, [field, op, value]: readonly [string, string, unknown]): boolean { + const v = d[field] + if (op === '==') return v === value + if (op === '>=') return (v as number) >= (value as number) + if (op === '<=') return (v as number) <= (value as number) + if (op === 'in') return (value as unknown[]).includes(v) + throw new Error(`mock: ${op}`) +} +function answer(q: { documentTypeName: string; where?: readonly (readonly [string, string, unknown])[] }): Doc[] { + return (stored[q.documentTypeName] ?? []).filter((d) => (q.where ?? []).every((w) => matches(d, w))) +} + +vi.mock('./role-claim', async (orig) => { + const { claimedRole } = await import('../rules/roles') + return { + ...(await orig()), + roleClaim: async (_sdk: unknown, _auth: unknown, _repo: unknown, type: string, data: Record) => ({ r: claimedRole(type, data, role) }), + } +}) +vi.mock('../sdk', async (orig) => { + const real = await orig() + return { + ...real, + queryAllDocuments: async (_sdk: unknown, q: { documentTypeName: string; where?: readonly (readonly [string, string, unknown])[] }) => answer(q), + queryDocumentsWithProof: async (_sdk: unknown, q: { documentTypeName: string; where?: readonly (readonly [string, string, unknown])[] }) => ({ documents: answer(q), proofMetadata: null }), + createDocumentIdempotent: async (_sdk: unknown, _auth: unknown, p: { documentType: string; data: Doc; intent?: string }) => { + if (duplicateOnCreate) throw new real.ConsensusRefusal(real.DUPLICATE_UNIQUE_CODE, 'duplicate unique index') + created.push({ type: p.documentType, data: p.data, ...(p.intent ? { intent: p.intent } : {}) }) + return { documentId: `new${created.length}`, confirmed: true, cost: { credits: 0, dash: 0 }, actualCredits: 0 } + }, + replaceDocumentIdempotent: async (_sdk: unknown, _auth: unknown, p: { documentType: string; documentId: string; changes: Doc }) => { + replaced.push({ type: p.documentType, id: p.documentId, changes: p.changes }) + return { documentId: p.documentId, revision: 2n, cost: { credits: 0, dash: 0 }, actualCredits: 0 } + }, + } +}) +let writerKeys: EpochKeys | null = null +vi.mock('./private-writes', async (orig) => ({ + ...(await orig()), + privateWriter: async () => ({ keys: writerKeys, protectedPatterns: [], isMember: true }), +})) +const repos: Record = {} +vi.mock('./resolveRepo', async (orig) => ({ + ...(await orig()), + readRepoById: async (_sdk: unknown, _forge: unknown, repoId: string) => repos[repoId] ?? null, +})) + +const boards = await import('./boards') +const writes = await import('./board-writes') + +function specJson(s: BoardSpec = SPEC): string { + const r = serializeSpec(s) + if ('error' in r) throw new Error(r.error) + return r.json +} + +function boardDoc(over: Doc): Doc { + return { $id: 'b1', $ownerId: ME, $updatedAt: 100, repoId: REPO_ID, key: 7, name: 'Roadmap', spec: specJson(), state: 0, r: 1, ...over } +} +function cardDoc(over: Doc): Doc { + return { $id: 'c1', $ownerId: ME, $updatedAt: 100, repoId: REPO_ID, board: 7, item: ITEM, state: 0, r: 1, ...over } +} + +beforeEach(() => { + stored = {} + created.length = 0 + replaced.length = 0 + role = 'writer' + duplicateOnCreate = false + writerKeys = null +}) + +describe('readBoards', () => { + it('takes the newest revision per key over every member, drops deleted and malformed ones', async () => { + stored['board'] = [ + boardDoc({ $id: 'a', key: 7, name: 'Old', $updatedAt: 10 }), + boardDoc({ $id: 'b', $ownerId: OTHER, key: 7, name: 'New', $updatedAt: 20 }), + boardDoc({ $id: 'c', key: 8, state: 2, $updatedAt: 30 }), + boardDoc({ $id: 'd', key: 9, state: 1, $updatedAt: 30 }), + // a public repo's board carrying enc is malformed here + boardDoc({ $id: 'e', key: 10, enc: 'AAAA', epoch: 0 }), + ] + const list = await boards.readBoards(sdk, REPO) + expect(list.map((b) => [b.key, b.name, b.state])).toEqual([ + [7, 'New', 'open'], + [9, 'Roadmap', 'closed'], + ]) + expect(list[0]?.revisions.map((r) => r.ownerId)).toEqual([ME, OTHER]) + expect(list[0]?.spec?.columns.map((c) => c.name)).toEqual(['Todo', 'In progress', 'Done']) + expect((await boards.readBoards(sdk, REPO, { withDeleted: true })).map((b) => b.key)).toEqual([7, 8, 9]) + }) + + it("lists a public repository's sealed board as unreadable rather than dropping it (newest-wins never goes back)", async () => { + stored['board'] = [boardDoc({ $id: 'old', $updatedAt: 10, name: 'Old' }), { $id: 'sealed', $ownerId: OTHER, $updatedAt: 20, repoId: REPO_ID, key: 7, state: 0, epoch: 0, enc: 'AAAA', r: 1 }] + const [b] = await boards.readBoards(sdk, REPO) + expect(b).toMatchObject({ key: 7, name: null, sealed: true, specError: 'unreadable', newest: { id: 'sealed' } }) + }) + + it('reports a definition the rules refuse', async () => { + stored['board'] = [boardDoc({ spec: '{"v":2}' })] + const [b] = await boards.readBoards(sdk, REPO) + expect(b?.spec).toBeNull() + expect(b?.specError).toBe('version') + }) +}) + +describe('readBoard and the poll', () => { + it('reads the definition and every card, and the poll reads >= the last time, deduplicated by $id', async () => { + stored['board'] = [boardDoc({})] + stored['card'] = [cardDoc({ $id: 'c1', $updatedAt: 100, col: 1 }), cardDoc({ $id: 'c2', item: ITEM2, $updatedAt: 200, col: 2 })] + const read = await boards.readBoard(sdk, REPO, 7) + expect(read?.cards.map((c) => c.id)).toEqual(['c1', 'c2']) + expect(read?.since).toBe(200) + // a replace of c1 lands, and c3 shares c2's block time + stored['card'] = [cardDoc({ $id: 'c1', $updatedAt: 300, col: 3 }), cardDoc({ $id: 'c2', item: ITEM2, $updatedAt: 200, col: 2 }), cardDoc({ $id: 'c3', $ownerId: OTHER, $updatedAt: 200, col: 2 })] + const fresh = await boards.readCardsSince(sdk, REPO, 7, read?.since ?? 0) + expect(fresh.map((c) => c.id).sort()).toEqual(['c1', 'c2', 'c3']) + const merged = boards.mergeCards(read?.cards ?? [], fresh) + expect(merged.map((c) => [c.id, c.col])).toEqual([ + ['c2', 2], + ['c3', 2], + ['c1', 3], + ]) + // an older copy never replaces a newer one + expect(boards.mergeCards(merged, [{ ...(merged[2] as (typeof merged)[number]), updatedAt: 1, col: 1 }]).find((c) => c.id === 'c1')?.col).toBe(3) + }) + + it('is null for a board with no revision', async () => { + expect(await boards.readBoard(sdk, REPO, 7)).toBeNull() + }) +}) + +describe('readItemCards (§5.6)', () => { + it("keeps the item's repo and the owner's other public repos, never a stranger's board", async () => { + const SIBLING = id(10) + const STRANGER = id(11) + repos[SIBLING] = { repoId: SIBLING, ownerId: ME, name: 'plan', visibility: 'public' } + repos[STRANGER] = { repoId: STRANGER, ownerId: OTHER, name: 'theirs', visibility: 'public' } + stored['board'] = [boardDoc({}), boardDoc({ $id: 'sb', repoId: SIBLING, key: 3, name: 'Plan' }), boardDoc({ $id: 'xb', repoId: STRANGER, key: 4, name: 'Spam' })] + stored['card'] = [cardDoc({ $id: 'c1', col: 2 }), cardDoc({ $id: 'c2', repoId: SIBLING, board: 3, col: 1 }), cardDoc({ $id: 'c3', repoId: STRANGER, board: 4 })] + const list = await boards.readItemCards(sdk, REPO, ITEM) + expect(list.map((e) => [e.home.repoId, e.board.key, e.card?.id])).toEqual([ + [REPO_ID, 7, 'c1'], + [SIBLING, 3, 'c2'], + ]) + // a private sibling's boards are sealed with a key this page does not hold: left out + const SECRET = id(12) + repos[SECRET] = { repoId: SECRET, ownerId: ME, name: 'secret', visibility: 'private' } + stored['card'].push(cardDoc({ $id: 'c4', repoId: SECRET, board: 5, enc: 'AAAA', epoch: 0 })) + expect((await boards.readItemCards(sdk, REPO, ITEM)).map((e) => e.home.repoId)).toEqual([REPO_ID, SIBLING]) + const item: BoardItem = { id: ITEM, number: 1, repoId: REPO_ID, kind: 'issue', state: 'open', createdAt: 1, closedAt: null, title: 't', labels: [], assignees: [], milestone: null, author: ME } + expect(boards.itemPlacement(list[0] as (typeof list)[number], item, 1000)?.col).toBe(2) + }) +}) + +const ITEM_REF = { id: ITEM, repoId: REPO_ID } + +async function openBoard(over: Doc = {}) { + stored['board'] = [boardDoc(over)] + return (await boards.readBoardDefinition(sdk, REPO, 7)) as NonNullable>> +} + +describe('writeCard: a fresh read of the newest card, then only the change (§3.2)', () => { + it("applies the patch over another member's newer card and creates the signer's own", async () => { + const board = await openBoard() + stored['card'] = [cardDoc({ $id: 'mine', $ownerId: OTHER, $updatedAt: 50, col: 1 }), cardDoc({ $id: 'theirs', $ownerId: OTHER, $updatedAt: 90, col: 2, rank: 'Vx', f: '{"1":1}' })] + // ...but `mine` is not the signer's: both are OTHER's, so this is a create + const out = await writes.writeCard(sdk, AUTH, REPO, board, ITEM_REF, { fields: { 2: 5 } }) + expect(out.created).toBe(true) + expect(created).toHaveLength(1) + const data = created[0]?.data as Doc + expect(data['col']).toBe(2) + expect(data['rank']).toBe('Vx') + expect(parseFieldValues(data['f'] as string, SPEC)).toEqual({ 1: 1, 2: 5 }) + expect(data['state']).toBe(0) + expect(data['r']).toBe(1) + expect(data['board']).toBe(7) + expect(out.card).toMatchObject({ col: 2, rank: 'Vx', item: ITEM }) + }) + + it("replaces the signer's own card, removing a cleared field's values", async () => { + const board = await openBoard() + stored['card'] = [cardDoc({ $id: 'mine', $updatedAt: 90, col: 2, rank: 'Vx', f: '{"1":1}' })] + const out = await writes.writeCard(sdk, AUTH, REPO, board, ITEM_REF, { fields: { 1: null }, col: 3 }) + expect(out.created).toBe(false) + expect(replaced).toEqual([{ type: 'card', id: 'mine', changes: expect.objectContaining({ col: 3, rank: 'Vx', f: undefined, state: 0, r: 1 }) }]) + }) + + it("replaces the signer's own card even when this reader skips it as malformed", async () => { + const board = await openBoard() + // plaintext beside enc: malformed, skipped by readers, but still the signer's document + stored['card'] = [cardDoc({ $id: 'broken', col: 1, enc: 'AAAA', epoch: 0 }), cardDoc({ $id: 'theirs', $ownerId: OTHER, $updatedAt: 200, col: 3 })] + const out = await writes.writeCard(sdk, AUTH, REPO, board, ITEM_REF, { rank: 'Vz' }) + expect(out.created).toBe(false) + expect(replaced[0]).toMatchObject({ id: 'broken', changes: { col: 3, rank: 'Vz', enc: undefined, epoch: undefined } }) + }) + + it('reads the definition fresh: a column another member added since is accepted, a board closed since is refused', async () => { + const stale = await openBoard() + stored['board'] = [boardDoc({ $id: 'b2', $ownerId: OTHER, $updatedAt: 500, spec: specJson({ ...SPEC, columns: [...SPEC.columns, { id: 9, name: 'Verified' }] }) })] + await writes.writeCard(sdk, AUTH, REPO, stale, ITEM_REF, { col: 9 }) + expect(created[0]?.data['col']).toBe(9) + stored['board'] = [boardDoc({ $id: 'b3', $ownerId: OTHER, $updatedAt: 600, state: 1 })] + await expect(writes.writeCard(sdk, AUTH, REPO, stale, ITEM_REF, { col: 1 })).rejects.toMatchObject({ refusal: 'closed' }) + }) + + it('a create that meets the signer\'s card made meanwhile replaces it instead', async () => { + const board = await openBoard() + duplicateOnCreate = true + const read = { n: 0 } + const original = stored + stored = new Proxy(original, { + get(t, k: string) { + if (k === 'card') return read.n++ === 0 ? [] : [cardDoc({ $id: 'tab2' })] + return t[k] + }, + }) + const out = await writes.writeCard(sdk, AUTH, REPO, board, ITEM_REF, { col: 1 }) + expect(out.created).toBe(false) + expect(replaced.map((r) => r.id)).toEqual(['tab2']) + }) +}) + +describe('refused before signing', () => { + it('a closed board is read-only', async () => { + const board = await openBoard({ state: 1 }) + await expect(writes.writeCard(sdk, AUTH, REPO, board, ITEM_REF, { col: 1 })).rejects.toMatchObject({ refusal: 'closed' }) + await expect(writes.saveBoard(sdk, AUTH, REPO, 7, { name: 'x' })).rejects.toMatchObject({ refusal: 'closed' }) + expect(created.length + replaced.length).toBe(0) + }) + + it('a column, rank, field or value the board does not have', async () => { + const board = await openBoard() + const patches: CardPatch[] = [{ col: 99 }, { rank: 'V0' }, { fields: { 77: 1 } }, { fields: { 1: 99 } }, { fields: { 3: -1 } }, { state: 3 }] + for (const patch of patches) { + await expect(writes.writeCard(sdk, AUTH, REPO, board, ITEM_REF, patch)).rejects.toMatchObject({ refusal: 'input' }) + } + expect(created.length + replaced.length).toBe(0) + }) + + it('triage places cards but does not define boards; a reader does neither', async () => { + const board = await openBoard() + role = 'triage' + await writes.writeCard(sdk, AUTH, REPO, board, ITEM_REF, { col: 1 }) + expect(created[0]?.data['r']).toBe(2) + await expect(writes.createBoard(sdk, AUTH, REPO, { name: 'Mine', spec: SPEC })).rejects.toBeInstanceOf(RoleRefusedError) + role = 'reader' + await expect(writes.writeCard(sdk, AUTH, REPO, board, ITEM_REF, { col: 1 })).rejects.toBeInstanceOf(RoleRefusedError) + expect(created).toHaveLength(1) + }) + + it('a board name or definition the schema or the rules refuse', () => { + expect(() => writes.checkBoardInput({ name: ' ', spec: SPEC })).toThrow(/board name/) + expect(() => writes.checkBoardInput({ name: 'n'.repeat(64), spec: SPEC })).toThrow(/board name/) + expect(() => writes.checkBoardInput({ name: 'ok', spec: { ...SPEC, columns: [] } })).toThrow(/columns/) + expect(writes.checkBoardInput({ name: ' Roadmap ', spec: SPEC }).name).toBe('Roadmap') + }) + + it("a private home's card for another repository's item, until confirmed (§3.3)", async () => { + const priv: RepoRef = { ...REPO, visibility: 'private' } + expect(writes.crossRepoCardNeedsConfirm(priv, id(30))).toBe(true) + expect(writes.crossRepoCardNeedsConfirm(priv, REPO_ID)).toBe(false) + expect(writes.crossRepoCardNeedsConfirm(REPO, id(30))).toBe(false) + const board = await openBoard() + await expect(writes.writeCard(sdk, AUTH, priv, board, { id: ITEM, repoId: id(30) }, { col: 1 })).rejects.toMatchObject({ refusal: 'cross-repo' }) + }) +}) + +describe('moving: ranks between neighbours (§2.6)', () => { + const col = (...ranks: string[]) => ranks.map((rank, i) => ({ id: id(40 + i), rank })) + + it('top, bottom, between, empty, and the moving card itself left out', () => { + expect(writes.rankForDrop([], 0)).toEqual({ rank: 'F' }) + const c = col('A', 'V1000000', 'b') + expect(writes.rankForDrop(c, 0)).toEqual({ rank: '5' }) + expect(writes.rankForDrop(c, 3)).toEqual({ rank: 'n' }) + const mid = writes.rankForDrop(c, 1) + expect('rank' in mid && mid.rank > 'A' && mid.rank < 'V1000000').toBe(true) + // the top bracket stays above the sourced pool (V…) even when the first card is in it + const top = writes.rankForDrop(col('V2', 'V3'), 0) + expect('rank' in top && top.rank < 'V').toBe(true) + }) + + it('a drop "before X" means before X whether the card came from above or below it', () => { + const [a, m, b, c] = col('A', 'M', 'b', 'q') + const column = [a, m, b, c] as { id: string; rank: string }[] + // M dropped before c (moving down): between b and q, not below q + const down = writes.rankBefore(column, m!.id, c!.id) + expect('rank' in down && down.rank > 'b' && down.rank < 'q').toBe(true) + // c dropped before a (moving up): the top + expect(writes.rankBefore(column, c!.id, a!.id)).toEqual(writes.rankForDrop([a!, m!, b!], 0)) + // null, or a card not in the column: the bottom + expect(writes.rankBefore(column, a!.id, null)).toEqual(writes.rankForDrop([m!, b!, c!], 3)) + }) + + it('moveCard writes the column and the rank; no room is refused with re-rank before signing', async () => { + const board = await openBoard() + const ac = col('A', 'C') + await writes.moveCard(sdk, AUTH, REPO, board, ITEM_REF, { col: 2 }, ac, ac[1]?.id ?? null) + expect(created[0]?.data).toMatchObject({ col: 2, rank: 'B' }) + const aa = col('A', 'A') + await expect(writes.moveCard(sdk, AUTH, REPO, board, ITEM_REF, { col: 2 }, aa, aa[1]?.id ?? null)).rejects.toMatchObject({ refusal: 're-rank', column: 2 }) + const vv = col('V', 'V0') + await expect(writes.moveCard(sdk, AUTH, REPO, board, ITEM_REF, { col: 2 }, vv, vv[1]?.id ?? null)).rejects.toMatchObject({ refusal: 're-rank' }) + expect(created).toHaveLength(1) + }) + + it('a move on a view grouped by a field sets the field', async () => { + const board = await openBoard() + await writes.moveCard(sdk, AUTH, REPO, board, ITEM_REF, { field: 1, value: 2 }, [], null) + expect(parseFieldValues(created[0]?.data['f'] as string, SPEC)).toEqual({ 1: 2 }) + }) + + it('re-rank: evenly spaced ranks below the pool, one write each, priced first', async () => { + const board = await openBoard() + stored['card'] = [cardDoc({ $id: 'mine', item: ITEM2 })] + expect(writes.planCardWrites(stored['card'].map((d) => ({ id: String(d['$id']), ownerId: String(d['$ownerId']), updatedAt: 1, item: String(d['item']), col: null, rank: null, f: null, state: 0 })), ME, [ITEM, ITEM2])).toEqual({ creates: 1, replaces: 1 }) + stored['card'] = [] + const out = await writes.rerankColumn(sdk, AUTH, REPO, board, [ITEM_REF, { id: ITEM2, repoId: REPO_ID }]) + expect(out.failed).toBeNull() + const ranks = created.map((c) => c.data['rank'] as string) + expect(ranks).toHaveLength(2) + expect(ranks[0]! < ranks[1]! && ranks[1]! < 'V').toBe(true) + }) + + it('a bulk write stops at the first failure and says what was skipped', async () => { + const board = await openBoard() + role = 'reader' + const out = await writes.archiveItems(sdk, AUTH, REPO, board, [ITEM_REF, { id: ITEM2, repoId: REPO_ID }]) + expect(out.written).toHaveLength(0) + expect(out.failed?.item).toBe(ITEM) + expect(out.skipped).toEqual([ITEM2]) + }) +}) + +describe('boards: create, save, close', () => { + it('creates under a key derived from the intent, skipping a taken one', async () => { + const k0 = writes.newBoardKey(REPO, 'intent-1', 0) + stored['board'] = [boardDoc({ $ownerId: OTHER, key: k0 })] + const out = await writes.createBoard(sdk, AUTH, REPO, { name: 'Sprint', spec: SPEC, intent: 'intent-1' }) + expect(out.key).toBe(writes.newBoardKey(REPO, 'intent-1', 1)) + expect(out.created).toBe(true) + expect(created[0]?.data).toMatchObject({ key: out.key, name: 'Sprint', state: 0, r: 1 }) + expect(writes.newBoardKey(REPO)).toBeGreaterThan(0) + }) + + it('a retry of a create whose first attempt landed replaces the signer\'s revision', async () => { + const k0 = writes.newBoardKey(REPO, 'intent-2', 0) + stored['board'] = [boardDoc({ $id: 'landed', key: k0, name: 'Sprint' })] + const out = await writes.createBoard(sdk, AUTH, REPO, { name: 'Sprint', spec: SPEC, intent: 'intent-2' }) + expect(out).toMatchObject({ key: k0, created: false, documentId: 'landed' }) + }) + + it("saves over the newest revision, replacing the signer's own or creating it", async () => { + stored['board'] = [boardDoc({ $id: 'theirs', $ownerId: OTHER, $updatedAt: 50, name: 'Theirs' })] + await writes.saveBoard(sdk, AUTH, REPO, 7, { spec: { ...SPEC, arch: 30 } }) + expect(created[0]?.data).toMatchObject({ key: 7, name: 'Theirs' }) + expect(JSON.parse(created[0]?.data['spec'] as string).arch).toBe(30) + stored['board'].push(boardDoc({ $id: 'mine', $updatedAt: 10 })) + await writes.setBoardState(sdk, AUTH, REPO, 7, 'closed') + expect(replaced[0]).toMatchObject({ id: 'mine', changes: { state: 1, name: 'Theirs' } }) + }) +}) + +describe('next iteration (§5.4)', () => { + it("moves the current iteration's open items outside Done", () => { + const now = Date.UTC(2026, 9, 28) + const item = (n: number, state: BoardItem['state'] = 'open'): BoardItem => ({ id: id(50 + n), number: n, repoId: REPO_ID, kind: 'issue', state, createdAt: n, closedAt: state === 'open' ? null : 1, title: `#${n}`, labels: [], assignees: [], milestone: null, author: ME }) + const items = [item(1), item(2), item(3, 'closed'), item(4)] + const cards = [ + { id: 'k1', ownerId: ME, updatedAt: 5, item: id(51), col: 1, rank: null, f: '{"3":0}', state: 0 }, + { id: 'k2', ownerId: ME, updatedAt: 5, item: id(52), col: 3, rank: null, f: '{"3":0}', state: 0 }, + { id: 'k3', ownerId: ME, updatedAt: 5, item: id(53), col: 1, rank: null, f: '{"3":0}', state: 0 }, + { id: 'k4', ownerId: ME, updatedAt: 5, item: id(54), col: 1, rank: null, f: '{"3":1}', state: 0 }, + ] + const fold = foldBoard({ spec: SPEC, home: REPO_ID, items, cards, now }) + const plan = writes.nextIterationPlan(SPEC, 3, items, fold.items, now) + expect(plan).toEqual({ next: 1, items: [{ id: id(51), repoId: REPO_ID }] }) + }) +}) + +describe('quick add references', () => { + it('reads #n, owner/name#n and this app\'s links', () => { + expect(writes.parseItemReference('#12')).toEqual({ number: 12 }) + expect(writes.parseItemReference('alice/forge#7')).toEqual({ owner: 'alice', name: 'forge', number: 7 }) + expect(writes.parseItemReference('https://git-forge.dashhq.org/repo/issue/?owner=alice&name=forge&number=3')).toEqual({ owner: 'alice', name: 'forge', number: 3 }) + expect(writes.parseItemReference('Fix the build')).toBeNull() + expect(writes.parseItemReference('https://example.com/a?owner=a&name=b&number=1')).toBeNull() + }) +}) + +describe('a private repository: sealed boards and cards (§3.3)', () => { + it('seals on write and opens on read with the session; without it nothing is shown', async () => { + const repoBytes = new Uint8Array(32).fill(9) + const keys = await EpochKeys.import(repoBytes, 0, new Uint8Array(32).fill(3)) + writerKeys = keys + const session = { ctx: { keys: new Map([[0, keys]]), anchors: new Map([[0, { id: new Uint8Array(32), height: 1, statedHeight: 1 }]]), members: new IdSet([]) } } as unknown as PrivateSession + const priv: RepoRef = { ...REPO, visibility: 'private', session } + const made = await writes.createBoard(sdk, AUTH, priv, { name: 'Secret plan', spec: SPEC }) + const boardData = created[0]?.data as Doc + expect(boardData['name']).toBeUndefined() + expect(boardData['spec']).toBeUndefined() + expect(boardData['epoch']).toBe(0) + expect(boardData['enc']).toBeInstanceOf(Uint8Array) + const toB64 = (u: Uint8Array) => Buffer.from(u).toString('base64') + stored['board'] = [{ $id: 'sb', $ownerId: ME, $updatedAt: 5, repoId: REPO_ID, key: made.key, state: 0, epoch: 0, enc: toB64(boardData['enc'] as Uint8Array), r: 1 }] + const [b] = await boards.readBoards(sdk, priv) + expect(b).toMatchObject({ name: 'Secret plan', sealed: true, state: 'open' }) + expect(b?.spec?.columns).toHaveLength(3) + + await writes.writeCard(sdk, AUTH, priv, b as NonNullable, ITEM_REF, { col: 2, rank: 'Vq', fields: { 2: 3 } }) + const cardData = created[1]?.data as Doc + expect(['col', 'rank', 'f'].filter((k) => cardData[k] !== undefined)).toEqual([]) + stored['card'] = [{ $id: 'sc', $ownerId: ME, $updatedAt: 6, repoId: REPO_ID, board: made.key, item: ITEM, state: 0, epoch: 0, enc: toB64(cardData['enc'] as Uint8Array), r: 1 }] + const read = await boards.readBoard(sdk, priv, made.key) + expect(read?.cards[0]).toMatchObject({ col: 2, rank: 'Vq', f: '{"2":3}' }) + // moved to another item, the seal fails: the card keeps only its state + stored['card'] = [{ ...(stored['card'][0] as Doc), item: ITEM2 }] + expect((await boards.readBoard(sdk, priv, made.key))?.cards[0]).toMatchObject({ item: ITEM2, col: null, rank: null, f: null }) + + // a reader without the session sees no name or definition + const locked: RepoRef = { ...REPO, visibility: 'private' } + const [lockedBoard] = await boards.readBoards(sdk, locked) + expect(lockedBoard).toMatchObject({ name: null, spec: null, specError: 'unreadable', sealed: true }) + // a private board carrying a plaintext name is malformed and skipped + stored['board'].push({ ...(stored['board'][0] as Doc), $id: 'bad', key: 99, name: 'leak' }) + expect((await boards.readBoards(sdk, priv)).map((x) => x.key)).toEqual([made.key]) + }) +}) diff --git a/forge-web/lib/repo/boards.ts b/forge-web/lib/repo/boards.ts new file mode 100644 index 000000000..72dab6186 --- /dev/null +++ b/forge-web/lib/repo/boards.ts @@ -0,0 +1,418 @@ +/** + * Boards: reading a repository's boards and cards (`docs/design/boards.md`; forge-meta `board` + * and `card`, UPDATE-3). The data layer the board pages are built on, in three modules: + * + * - **Reads** (here): {@link readBoards} (a repo's boards, newest revision per key over every + * member's, deleted dropped), {@link readBoard} (one board's definition and every card, the + * `card.recent` index, 100 per page), {@link readCardsSince} (the 20 s poll, §5.7: `$updatedAt + * >=` the last read, deduplicated by `$id` with {@link mergeCards}), {@link readItemCards} (an + * issue's or PR's sidebar, §5.6: `card.onItem`, only boards whose home is the item's repository + * or another repository of the same owner) and {@link itemPlacement} (its status there). + * - **Items** (`./board-items`): the fold's {@link BoardItem} facts for a board's sources and + * cards, from the issue and pull list indexes, then {@link foldBoard} (`lib/rules/boards.ts`). + * - **Writes** (`./board-writes`): create / save / close / delete a board, and every card write + * (move, fields, add, archive, remove, quick add, re-rank, next iteration), each one document + * operation, role-checked and refused before signing where the contract or the rules would + * refuse it, a card written over a fresh read of the item's newest card (§3.2). + * + * A private repository's boards and cards are sealed (`lib/private/board.ts`, private-repos.md + * §4.6): a reader with the repo's session opens them; without it a board reads with no name or + * definition and a card with no column, rank or fields. A public repository's sealed ones (a + * repository made public, §18: opened with its published keys; a later client's members-only + * boards) read the same way when they do not open: unreadable, never dropped, so newest-wins + * never brings an older revision back. A document carrying plaintext content beside `enc`, a + * private one without `enc`, or one whose seal is malformed is skipped by every reader; a write + * still finds the signer's own document among the raw rows ({@link BoardView.revisions}, + * {@link readItemCardDocs}), so a member is never locked out of replacing it. + * + * Which writes a signer may make (`boards.md` §5.1): {@link canPlaceCards} (maintainers, writers, + * triage) and {@link canEditBoards} (maintainers, writers). + */ + +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { decodeIdentifier } from '../auth/base58' +import { openBoardDoc, type BoardBind, type BoardFields, type CardFields, type StoredBoardDoc } from '../private' +import { BOARD_CLOSED, BOARD_DELETED, BOARD_OPEN, foldBoard, newestBoards, newestCards, parseSpec, type BoardDoc, type BoardItem, type BoardSpec, type CardDoc, type Placement, type SpecError } from '../rules/boards' +import { compareStrings } from '../rules/oid' +import type { Role } from '../rules/v2' +import { queryAllDocuments, type PlainDocument } from '../sdk' +import { DOC, asIdentifierString, num, str, type RepoRef } from './contract' +import { bytesField, idField } from './private-content' +import { readRepoById, repoRefOf } from './resolveRepo' +import { repoSource } from './source' + +/** A board's state (§3.1 `state`): open, closed (read-only, listed under Closed) or deleted. */ +export type BoardState = 'open' | 'closed' | 'deleted' + +const STATE_OF: Readonly> = { [BOARD_OPEN]: 'open', [BOARD_CLOSED]: 'closed', [BOARD_DELETED]: 'deleted' } +/** The `board.state` integer of each state. */ +export const BOARD_STATE_CODE: Readonly> = { open: BOARD_OPEN, closed: BOARD_CLOSED, deleted: BOARD_DELETED } + +/** One member's revision of a board: one document per (home repo, key, member), replaced in place. */ +export interface BoardRevision { + readonly id: string + readonly ownerId: string + readonly updatedAt: number +} + +/** A board as its newest revision defines it. */ +export interface BoardView { + readonly key: number + /** The home repository's id. */ + readonly repoId: string + readonly state: BoardState + /** Null when it could not be read: a private repository's board without the repo's key. */ + readonly name: string | null + /** The parsed definition; null when it could not be read or was refused ({@link specError}). */ + readonly spec: BoardSpec | null + /** Why {@link spec} is null: the rules' refusal, or `unreadable` (sealed, no key). */ + readonly specError: SpecError | 'unreadable' | null + /** The definition is sealed (a private repository's). */ + readonly sealed: boolean + /** The newest revision (its writer and time: "edited by … "). */ + readonly newest: BoardRevision + /** + * Every member's revision document, oldest first, malformed ones included (a save replaces the + * signer's own, {@link ownRevision}, whatever it holds). + */ + readonly revisions: readonly BoardRevision[] +} + +/** + * A card as read (the rules' {@link CardDoc}). `unreadable`: a sealed card this reader could not + * open (no key, a later client's version): its column, rank and fields are unknown, not empty. + */ +export type BoardCard = CardDoc & { readonly unreadable?: true } + +/** One board and every card on it, as {@link readBoard} reads them. */ +export interface BoardRead { + readonly board: BoardView + readonly cards: readonly BoardCard[] + /** The newest `$updatedAt` among the cards (0 when none): the next poll reads from here. */ + readonly since: number +} + +/** The signer's own revision of a board, if they wrote one. */ +export function ownRevision(board: BoardView, me: string): BoardRevision | null { + return board.revisions.find((r) => r.ownerId === me) ?? null +} + +/** Whether `role` may place cards: move, rank, set fields, add, archive, remove (§5.1). */ +export function canPlaceCards(role: Role | null | undefined): boolean { + return role === 'maintainer' || role === 'writer' || role === 'triage' +} + +/** Whether `role` may create, edit, close or delete a board and save views (§5.1). */ +export function canEditBoards(role: Role | null | undefined): boolean { + return role === 'maintainer' || role === 'writer' +} + +// --------------------------------------------------------------------------------------------- +// Documents +// --------------------------------------------------------------------------------------------- + +/** A u32 integer field (content integers come back as bigint or number), or null. */ +function u32Of(doc: PlainDocument, field: string): number | null { + const v = doc[field] + const n = typeof v === 'bigint' ? Number(v) : v + return typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= 0xffffffff ? n : null +} + +function present(doc: PlainDocument, field: string): boolean { + return doc[field] !== undefined && doc[field] !== null +} + +/** A stored document's sealed form for `openBoardDoc`, or null when it names no owner. */ +function storedOf(doc: PlainDocument, bind: BoardBind, plain: readonly string[]): StoredBoardDoc | null { + const ownerId = idField(doc, '$ownerId') + if (ownerId === undefined) return null + const epoch = u32Of(doc, 'epoch') + const enc = bytesField(doc, 'enc') + return { bind, ownerId, ...(epoch !== null ? { epoch } : {}), ...(enc !== undefined ? { enc } : {}), hasPlaintextContent: plain.some((f) => present(doc, f)) } +} + +/** The session that opens `repo`'s sealed boards and cards: a member's, or a repository made public's published keys. */ +function openerOf(repo: RepoRef) { + return repo.visibility === 'private' ? repo.session : repo.published +} + +/** + * A `board` document as the rules read it ({@link BoardDoc}), opened where it is sealed; null + * when malformed (plaintext content beside `enc`, a private board without `enc`, a broken seal), + * which every reader skips. A sealed board this reader cannot open reads with no name or spec. + */ +export async function boardDocOf(repo: RepoRef, doc: PlainDocument): Promise<(BoardDoc & { readonly sealed: boolean }) | null> { + const key = u32Of(doc, 'key') + const state = u32Of(doc, 'state') + if (key === null || key === 0 || state === null || state > BOARD_DELETED) return null + const base = { id: str(doc, '$id'), ownerId: str(doc, '$ownerId'), updatedAt: num(doc, '$updatedAt'), key, state } + if (!present(doc, 'enc')) { + if (repo.visibility === 'private') return null + return { ...base, name: typeof doc['name'] === 'string' ? doc['name'] : null, spec: typeof doc['spec'] === 'string' ? doc['spec'] : null, sealed: false } + } + const stored = storedOf(doc, { type: 'board', key }, ['name', 'spec']) + if (stored === null || stored.hasPlaintextContent) return null + const opener = openerOf(repo) + if (opener === undefined) return { ...base, name: null, spec: null, sealed: true } + const opened = await openBoardDoc(opener.ctx, stored) + if (opened.status === 'malformed') return null + const fields = opened.status === 'readable' ? (opened.fields as BoardFields) : null + return { ...base, name: fields?.name ?? null, spec: fields?.spec ?? null, sealed: true } +} + +/** + * A `card` document as the rules read it ({@link CardDoc}), opened where it is sealed: one this + * reader cannot open keeps its `state`, marked `unreadable`. Null when malformed (as + * {@link boardDocOf}). + */ +export async function cardDocOf(repo: RepoRef, doc: PlainDocument): Promise { + const board = u32Of(doc, 'board') + const state = u32Of(doc, 'state') + const item = asIdentifierString(doc['item']) + if (board === null || board === 0 || state === null || state > 2 || item === '') return null + const base = { id: str(doc, '$id'), ownerId: str(doc, '$ownerId'), updatedAt: num(doc, '$updatedAt'), item, state } + if (!present(doc, 'enc')) { + if (repo.visibility === 'private') return null + const col = u32Of(doc, 'col') + return { ...base, col: col !== null && col <= 255 ? col : null, rank: typeof doc['rank'] === 'string' ? doc['rank'] : null, f: typeof doc['f'] === 'string' ? doc['f'] : null } + } + let itemBytes: Uint8Array + try { + itemBytes = decodeIdentifier(item) + } catch { + return null + } + const stored = storedOf(doc, { type: 'card', board, item: itemBytes }, ['col', 'rank', 'f']) + if (stored === null || stored.hasPlaintextContent) return null + const unread: BoardCard = { ...base, col: null, rank: null, f: null, unreadable: true } + const opener = openerOf(repo) + if (opener === undefined) return unread + const opened = await openBoardDoc(opener.ctx, stored) + if (opened.status === 'malformed') return null + if (opened.status !== 'readable') return unread + const fields = opened.fields as CardFields + return { ...base, col: fields.col ?? null, rank: fields.rank ?? null, f: fields.f ?? null } +} + +/** `docs` as cards of `repo`, the malformed dropped. */ +async function cardsOf(repo: RepoRef, docs: readonly PlainDocument[]): Promise { + return (await Promise.all(docs.map((d) => cardDocOf(repo, d)))).filter((c): c is BoardCard => c !== null) +} + +/** The views of `repo`'s board documents, newest revision per key ({@link newestBoards}). */ +async function boardViews(repo: RepoRef, docs: readonly PlainDocument[], withDeleted: boolean): Promise { + const opened = (await Promise.all(docs.map((d) => boardDocOf(repo, d)))).filter((d): d is NonNullable => d !== null) + const sealed = new Map(opened.map((d) => [d.id, d.sealed])) + // every revision document, the skipped ones too: a write replaces the signer's own whatever it holds + const byKey = new Map() + for (const d of docs) { + const key = u32Of(d, 'key') + if (key !== null) byKey.set(key, [...(byKey.get(key) ?? []), { id: str(d, '$id'), ownerId: str(d, '$ownerId'), updatedAt: num(d, '$updatedAt') }]) + } + return newestBoards(opened, withDeleted).map((d) => { + const parsed = d.spec === null ? null : parseSpec(d.spec) + const revisions = (byKey.get(d.key) ?? []).sort((a, b) => a.updatedAt - b.updatedAt || compareStrings(a.id, b.id)) + return { + key: d.key, + repoId: repo.repoId, + state: STATE_OF[d.state] ?? 'open', + name: d.name, + spec: parsed !== null && 'spec' in parsed ? parsed.spec : null, + specError: parsed === null ? 'unreadable' : 'error' in parsed ? parsed.error : null, + sealed: sealed.get(d.id) === true, + newest: { id: d.id, ownerId: d.ownerId, updatedAt: d.updatedAt }, + revisions, + } + }) +} + +// --------------------------------------------------------------------------------------------- +// Reads +// --------------------------------------------------------------------------------------------- + +/** Card pages a board read follows at most (100 each: 100,000 cards). */ +const CARD_MAX_PAGES = 1000 + +/** + * Every board of `repo` (`board.byKey`, `repoId ==`): per key the newest revision over every + * member's by (`$updatedAt`, `$id`), ascending by key, open and closed; deleted ones (state 2) + * only with `withDeleted`. + */ +export async function readBoards(sdk: EvoSDK, repo: RepoRef, { withDeleted = false }: { readonly withDeleted?: boolean } = {}): Promise { + const docs = await queryAllDocuments(sdk, repoSource(repo).repoQuery(DOC.board, { orderBy: [['key', 'asc'], ['$ownerId', 'asc']] })) + return boardViews(repo, docs, withDeleted) +} + +/** + * Board `key` of `repo` as its newest revision defines it (every member's revision of it read + * fresh), or null when it has none. A deleted board reads as deleted (never null), so a page can + * say so. + */ +export async function readBoardDefinition(sdk: EvoSDK, repo: RepoRef, key: number): Promise { + const docs = await queryAllDocuments(sdk, repoSource(repo).repoQuery(DOC.board, { where: [['key', '==', key]], orderBy: [['key', 'asc'], ['$ownerId', 'asc']] })) + return (await boardViews(repo, docs, true))[0] ?? null +} + +/** The `card.recent` query of board `key` of `repo`, oldest change first (from `sinceMs`, inclusive). */ +function recentQuery(repo: RepoRef, key: number, sinceMs: number | null) { + return repoSource(repo).repoQuery(DOC.card, { + where: [['board', '==', key], ...(sinceMs === null ? [] : [['$updatedAt', '>=', sinceMs] as const])], + orderBy: [['board', 'asc'], ['$updatedAt', 'asc']], + }) +} + +/** The newest `$updatedAt` of `cards`, or 0. */ +export function cardsSince(cards: readonly BoardCard[]): number { + return cards.reduce((m, c) => Math.max(m, c.updatedAt), 0) +} + +/** + * Board `key` of `repo`: its definition and every card on it, every member's (`card.recent`, + * 100 per page), or null when the board has no revision. Cards of a board whose definition did + * not open are still read (their states are plaintext). + */ +export async function readBoard(sdk: EvoSDK, repo: RepoRef, key: number): Promise { + const [board, docs] = await Promise.all([readBoardDefinition(sdk, repo, key), queryAllDocuments(sdk, recentQuery(repo, key, null), { maxPages: CARD_MAX_PAGES })]) + if (board === null) return null + const cards = mergeCards([], await cardsOf(repo, docs)) + return { board, cards, since: cardsSince(cards) } +} + +/** + * The cards of board `key` written or replaced at or after `sinceMs` (§5.7's poll): `>=`, since + * several cards can share a block time and the last read may have stopped inside it, so a caller + * merges them by `$id` ({@link mergeCards}). + */ +export async function readCardsSince(sdk: EvoSDK, repo: RepoRef, key: number, sinceMs: number): Promise { + return cardsOf(repo, await queryAllDocuments(sdk, recentQuery(repo, key, sinceMs), { maxPages: CARD_MAX_PAGES })) +} + +/** + * `held` with `fresh` merged in by `$id`: a card document is replaced in place (same `$id`, a + * later `$updatedAt`), so the later of two copies wins; a copy read twice (a poll's `>=` + * boundary) is kept once. Ordered by (`$updatedAt`, `$id`). + */ +export function mergeCards(held: readonly BoardCard[], fresh: readonly BoardCard[]): BoardCard[] { + const byId = new Map() + for (const c of [...held, ...fresh]) { + const prev = byId.get(c.id) + if (prev === undefined || c.updatedAt >= prev.updatedAt) byId.set(c.id, c) + } + return [...byId.values()].sort((a, b) => a.updatedAt - b.updatedAt || compareStrings(a.id, b.id)) +} + +/** Every member's card for one item on one board, and the `$id` of `me`'s own card document (whatever it holds). */ +export interface ItemCardDocs { + readonly cards: readonly BoardCard[] + readonly own: string | null +} + +/** + * Every member's card for one item on board `key` of `repo`, read fresh (`card.onItem`, `item ==` + * then the home repo and board): what a card write applies its change to (§3.2), and the signer + * `me`'s own card document, found among the raw rows (one this reader skips as malformed is still + * the one the unique index holds, and the one a write replaces). + */ +export async function readItemCardDocs(sdk: EvoSDK, repo: RepoRef, key: number, itemId: string, me: string): Promise { + const docs = await queryAllDocuments( + sdk, + repoSource(repo).targetQuery(DOC.card, { + where: [ + ['item', '==', itemId], + ['repoId', '==', repo.repoId], + ['board', '==', key], + ], + orderBy: [['repoId', 'asc'], ['board', 'asc']], + }), + ) + const own = docs.find((d) => str(d, '$ownerId') === me) + return { cards: await cardsOf(repo, docs), own: own === undefined ? null : str(own, '$id') } +} + +/** One board an issue or PR is on, for its sidebar (§5.6). */ +export interface ItemBoard { + /** The board's home repository. */ + readonly home: RepoRef + readonly board: BoardView + /** Every member's card for the item on this board. */ + readonly cards: readonly BoardCard[] + /** The newest of them (§2.4), or null. */ + readonly card: BoardCard | null +} + +/** + * The boards issue or PR `itemId` of `repo` has a card on (`card.onItem`, `item ==`), keeping + * only boards whose home is `repo` or another repository of the same owner (§5.6: a stranger's + * board naming the issue never shows) that this reader can open: another owner repository that + * is private is left out (its boards are sealed with a key this page does not hold). Deleted + * boards are left out; closed ones are kept (read-only). Ordered by home repository, then key. + */ +export async function readItemCards(sdk: EvoSDK, repo: RepoRef, itemId: string): Promise { + const docs = await queryAllDocuments(sdk, repoSource(repo).targetQuery(DOC.card, { where: [['item', '==', itemId]], orderBy: [['repoId', 'asc'], ['board', 'asc']] })) + const byHome = new Map() + for (const d of docs) { + const home = asIdentifierString(d['repoId']) + if (home !== '') byHome.set(home, [...(byHome.get(home) ?? []), d]) + } + const out: ItemBoard[] = [] + for (const [homeId, homeDocs] of [...byHome].sort(([a], [b]) => (a === repo.repoId ? -1 : b === repo.repoId ? 1 : compareStrings(a, b)))) { + let home: RepoRef | null = homeId === repo.repoId ? repo : null + if (home === null) { + const doc = await readRepoById(sdk, repo.forge, homeId) + if (doc === null || doc.ownerId !== repo.ownerId || doc.visibility === 'private') continue + home = repoRefOf(repo.forge, doc) + } + const byKey = new Map() + for (const d of homeDocs) { + const key = u32Of(d, 'board') + if (key !== null && key > 0) byKey.set(key, [...(byKey.get(key) ?? []), d]) + } + for (const [key, keyDocs] of [...byKey].sort(([a], [b]) => a - b)) { + const board = await readBoardDefinition(sdk, home, key) + if (board === null || board.state === 'deleted') continue + const onBoard = await cardsOf(home, keyDocs) + out.push({ home, board, cards: onBoard, card: newestCards(onBoard).get(itemId) ?? null }) + } + } + return out +} + +/** + * Where `item` shows on `entry`'s board (§2.4): its column, rank, archive state and field values, + * folded as the board page folds it; null when the board's definition did not open. + */ +export function itemPlacement(entry: ItemBoard, item: BoardItem, now: number): Placement | null { + if (entry.board.spec === null) return null + return foldBoard({ spec: entry.board.spec, home: entry.home.repoId, items: [item], cards: entry.cards, now }).items[0] ?? null +} + +// --------------------------------------------------------------------------------------------- +// Write generation +// --------------------------------------------------------------------------------------------- + +const generations = new Map() +const listeners = new Set<() => void>() + +let allWrites = 0 + +/** + * Note a board or card write to `repo`: the lists of its boards (`useBoards`) and the item + * sidebars (`useItemBoards`) re-read. (A board page re-reads its own writes by polling at once.) + */ +export function noteBoardWrite(repo: Pick): void { + generations.set(repo.repoId, (generations.get(repo.repoId) ?? 0) + 1) + allWrites++ + for (const l of listeners) l() +} + +/** How many board or card writes to `repo` (none given: to any repository) this session made. */ +export function boardWriteGeneration(repo?: Pick): number { + return repo === undefined ? allWrites : (generations.get(repo.repoId) ?? 0) +} + +/** Be told of every {@link noteBoardWrite}; returns the unsubscribe. */ +export function subscribeBoardWrites(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} diff --git a/forge-web/lib/repo/index.ts b/forge-web/lib/repo/index.ts index b14e1d75c..8a7c4afc6 100644 --- a/forge-web/lib/repo/index.ts +++ b/forge-web/lib/repo/index.ts @@ -178,6 +178,84 @@ export { toLabelDef, type LabelDef, } from './labels' +export { + BOARD_STATE_CODE, + boardDocOf, + boardWriteGeneration, + canEditBoards, + canPlaceCards, + cardDocOf, + cardsSince, + itemPlacement, + mergeCards, + noteBoardWrite, + ownRevision, + readBoard, + readBoardDefinition, + readBoards, + readItemCardDocs, + readCardsSince, + readItemCards, + subscribeBoardWrites, + type BoardCard, + type BoardRead, + type BoardRevision, + type BoardState, + type BoardView, + type ItemBoard, + type ItemCardDocs, +} from './boards' +export { + CLOSED_PER_REPO, + addCardItems, + assembleBoard, + boardItemOfIssue, + boardItemOfPull, + boardItemReader, + loadBoardItems, + loadOlderClosed, + withItem, + type BoardItemReader, + type BoardItemSet, + type BoardItemsInput, + type ClosedWalk, +} from './board-items' +export { + BoardWriteError, + addItems, + archiveItems, + checkBoardInput, + createBoard, + crossRepoCardNeedsConfirm, + moveCard, + moveOpenToNextIteration, + newBoardKey, + nextIterationPlan, + parseItemReference, + patchedCard, + planCardWrites, + quickAddIssue, + rankBefore, + rankForDrop, + removeItems, + rerankColumn, + resolveItemByNumber, + saveBoard, + setBoardState, + unarchiveItems, + writeCard, + type BoardChange, + type BoardRefusal, + type BoardWritten, + type BulkWritten, + type CardItem, + type CardPatch, + type CardWriteOptions, + type CardWritten, + type MoveTarget, + type QuickAdded, + type RankedCard, +} from './board-writes' export { compareRows, matchesText, diff --git a/forge-web/lib/repo/issue-index.ts b/forge-web/lib/repo/issue-index.ts index f7ac5bd27..40ab329c0 100644 --- a/forge-web/lib/repo/issue-index.ts +++ b/forge-web/lib/repo/issue-index.ts @@ -516,3 +516,16 @@ export async function issueMilestoneItems(sdk: EvoSDK, repo: RepoRef, network: N const rows = await rowsWithEvent(sdk, await indexOf(sdk, repo, network), 'milestoneSet') return rows?.map((r) => ({ open: r.state.open, milestone: r.milestone ?? null })) ?? null } + +/** + * The issue rows of `ids` (any not this repo's issues, or not shown, are left out), each with its + * labels, assignees and milestone: a board's closed and card-named items (`./board-items`). Read + * through the list's index, so a row the list already holds costs nothing. + */ +export async function issueRowsById(sdk: EvoSDK, repo: RepoRef, ids: readonly string[], network: Network = DEFAULT_NETWORK): Promise { + if (ids.length === 0) return [] + const index = await indexOf(sdk, repo, network) + await resolveIds(sdk, index, ids) + await hydrate(sdk, index, ids) + return rowsOf(index, ids) +} diff --git a/forge-web/lib/repo/pull-index.ts b/forge-web/lib/repo/pull-index.ts index 392132ac8..deb5f9245 100644 --- a/forge-web/lib/repo/pull-index.ts +++ b/forge-web/lib/repo/pull-index.ts @@ -57,6 +57,7 @@ import { authorCandidates, candidatesCheaper, feedOf, + hydrate, indexCache, membersOnlyOfIndex, intersect, @@ -67,7 +68,9 @@ import { pageOf, pageWalk, repoCountsOf, + resolveIds, rowsInAnyState, + rowsOf, rowsWithEvent, scanCheaper, scanSelect, @@ -514,3 +517,15 @@ export async function openPullsOnBranch( .map((p) => ({ ...p, repoId: p.repoId === repo.repoId ? null : p.repoId })) return { pulls: [...here, ...elsewhere], searched: selected.complete ? null : selected.searched } } + +/** + * The PR rows of `ids` (any not this repo's PRs, or not shown, are left out), each with its + * labels, assignees and milestone: a board's closed and card-named items (`./board-items`). + */ +export async function pullRowsById(sdk: EvoSDK, repo: RepoRef, ids: readonly string[], network: Network = DEFAULT_NETWORK): Promise { + if (ids.length === 0) return [] + const index = await indexOf(sdk, repo, network) + await resolveIds(sdk, index, ids) + await hydrate(sdk, index, ids) + return rowsOf(index, ids) +} diff --git a/forge-web/lib/rules/conformance.test.ts b/forge-web/lib/rules/conformance.test.ts index 5b870f372..0545cbaa7 100644 --- a/forge-web/lib/rules/conformance.test.ts +++ b/forge-web/lib/rules/conformance.test.ts @@ -1206,7 +1206,8 @@ describe('FORGE_RULES conformance vectors', () => { // to bots (`access_notice`) in `lib/private/access-notice.conformance.test.ts`; the narrower branches // (`branch_key`) in `lib/private/branch-key.conformance.test.ts`; a bot's members-only posts // (`bot_post`) in `lib/private/bot-post.conformance.test.ts`; bot push grants (`bot_push`) in - // `./push-grant.conformance.test.ts`. + // `./push-grant.conformance.test.ts`; a private repository's sealed boards and cards + // (`sealed_board`, boards.md §3.3) in `lib/private/board.conformance.test.ts`. // The members-only branch and PR cases (private-repos.md §19): `oid_blind`, `sealed_ref` and // `sealed_patch` run in `lib/private/members-git.conformance.test.ts`; `members_pack_plan` and // `publish_guard` pin the git remote helper's push planning and publish guard, which only the @@ -1217,7 +1218,7 @@ describe('FORGE_RULES conformance vectors', () => { const isMembersGit = (v: Vector) => MEMBERS_GIT_CASES.includes(v.case) || v.case === 'members_check' || v.case === 'members_index' const isPrivate = (v: Vector) => isMembersGit(v) || - ['private_', 'mixed_doc_', 'named_envelope', 'named_artifact', 'converted_repo_', 'seal_off_marker', 'env_snapshot', 'key_letter', 'access_notice', 'branch_key', 'bot_post', 'bot_push'].some((p) => v.case.startsWith(p)) + ['private_', 'mixed_doc_', 'named_envelope', 'named_artifact', 'converted_repo_', 'seal_off_marker', 'env_snapshot', 'key_letter', 'access_notice', 'branch_key', 'bot_post', 'bot_push', 'sealed_board'].some((p) => v.case.startsWith(p)) // boards (`board_*`, boards.md) run in `./boards.conformance.test.ts` const isBoard = (v: Vector) => v.case.startsWith('board_') const v2Vectors = vectors.filter((v) => v.rules === 'v2' && !isPrivate(v) && !isBoard(v)) diff --git a/forge-web/lib/rules/roles.test.ts b/forge-web/lib/rules/roles.test.ts index e44eccceb..9b135b38d 100644 --- a/forge-web/lib/rules/roles.test.ts +++ b/forge-web/lib/rules/roles.test.ts @@ -61,6 +61,15 @@ describe('claimedRole: the r a gated write carries', () => { for (const type of ['label', 'milestone']) expect(roles.map((role) => claim(type, {}, role))).toEqual([1, 1, 2, 'refused', 1]) }) + it('boards (UPDATE-3): a board claims 1 and is refused for triage and readers; a card is triage-gated', () => { + expect(roles.map((role) => claim('board', {}, role))).toEqual([1, 1, 'refused', 'refused', 1]) + expect(roles.map((role) => claim('card', {}, role))).toEqual([1, 1, 2, 'refused', 1]) + expect(isRoleGated('board') && isRoleGated('card')).toBe(true) + expect(() => claimedRole('board', {}, 'triage')).toThrow(/a triage member cannot create, edit, close or delete boards/) + expect(() => claimedRole('card', {}, 'reader')).toThrow(/a reader cannot move, add or archive items on a board/) + expect(() => claimedRole('card', {}, 'bot')).toThrow(/a bot cannot/) + }) + it('transition: triage closes, reopens and locks (2), never merges, drafts or readies; the author always claims 1', () => { for (const kind of [1, 2, 3, 4, 11, 12, 16, 17, 18, 19]) expect(roles.map((role) => claim('transition', { kind, asAuthor: 0 }, role))).toEqual([1, 1, 2, 'refused', 1]) for (const kind of [13, 14, 15]) expect(roles.map((role) => claim('transition', { kind, asAuthor: 0 }, role))).toEqual([1, 1, 'refused', 'refused', 1]) diff --git a/forge-web/lib/rules/roles.ts b/forge-web/lib/rules/roles.ts index 89f929d37..3d8776f3f 100644 --- a/forge-web/lib/rules/roles.ts +++ b/forge-web/lib/rules/roles.ts @@ -8,6 +8,8 @@ * - `refUpdate`, `packManifest`, `chunk`, `checkRun`: `r` 1 only (push and checks: role 1). * - `label`, `milestone`, `transition`, `event`: `r` 1 or 2; a transition of kind 13/14/15 * (merge, draft, ready) and an event of kind 8, 15, 16, 19, 20 or 23 need `r` 1. + * - forge-meta's `board` (UPDATE-3, `docs/design/boards.md` §3.1): `r` 1 only (writers define + * boards, triage does not); `card` (§3.2): `r` 1 or 2 (triage places cards). * * Maintainers (the repo owner's own maintainer document included), authors (`transition` * `asAuthor` > 0) and runners pass through other operands, so they always claim 1. A reader @@ -294,7 +296,13 @@ export function whoCan(cap: keyof Capabilities, form: 'plural' | 'one' = 'plural /** The types whose gate admits role 1 only (`r` maximum 1). */ export const PUSH_GATED_TYPES: ReadonlySet = new Set(['refUpdate', 'packManifest', 'chunk', 'checkRun']) /** The types whose gate admits roles 1 and 2 (`r` 1..2). */ -export const TRIAGE_GATED_TYPES: ReadonlySet = new Set(['label', 'milestone', 'transition', 'event']) +export const TRIAGE_GATED_TYPES: ReadonlySet = new Set(['label', 'milestone', 'transition', 'event', 'card']) +/** + * The member-gated types whose gate admits role 1 only and that are not pushes: a board's + * definition (`board.r` is 1, rule `rClaim`; boards.md §3.1). Maintainers and writers define, + * close and delete boards; triage only places cards on them. + */ +export const WRITER_GATED_TYPES: ReadonlySet = new Set(['board']) /** Transition kinds that need `r` 1 (`e_mergeOid`): merge, draft, ready. */ export const WRITER_TRANSITION_KINDS: ReadonlySet = new Set([13, 14, 15]) /** @@ -312,7 +320,7 @@ export const CLIENT_WRITER_EVENT_KINDS: ReadonlySet = new Set([26, 27, 2 /** Whether `documentType` carries `r` (its gate proves the writer document's role). */ export function isRoleGated(documentType: string): boolean { - return PUSH_GATED_TYPES.has(documentType) || TRIAGE_GATED_TYPES.has(documentType) + return PUSH_GATED_TYPES.has(documentType) || TRIAGE_GATED_TYPES.has(documentType) || WRITER_GATED_TYPES.has(documentType) } /** A write the signer's role cannot make: refused before signing. */ @@ -355,6 +363,7 @@ const TRANSITION_WHAT: Readonly> = { * whom consensus judges by its other operands). Null for a type that carries no `r`. * * - push class and `checkRun`: 1; refused for triage and reader; + * - `board`: 1; refused for triage and reader (boards.md §5.1); * - an author's transition (`asAuthor` > 0): 1; * - a maintainer, a role-1 writer, or no membership: 1; * - triage: 2, refused for the writer-only transition and event kinds; @@ -369,11 +378,22 @@ export function claimedRole(documentType: string, data: Readonly 0) return 1 if (role === null || role === 'maintainer' || role === 'writer') return 1 const kind = intOf(data['kind']) if (role === 'reader' || role === 'bot') { - const what = documentType === 'transition' ? 'change its state as a member (only as the author of your own issue or pull request)' : documentType === 'event' ? 'label, assign, or otherwise change issues and pull requests as a member' : `define ${documentType}s` + const what = + documentType === 'transition' + ? 'change its state as a member (only as the author of your own issue or pull request)' + : documentType === 'event' + ? 'label, assign, or otherwise change issues and pull requests as a member' + : documentType === 'card' + ? 'move, add or archive items on a board' + : `define ${documentType}s` throw new RoleRefusedError(role, what) } if (documentType === 'transition' && kind !== null && WRITER_TRANSITION_KINDS.has(kind)) { diff --git a/forge-web/lib/sdk/cost.test.ts b/forge-web/lib/sdk/cost.test.ts index 76db01f15..afce71ff6 100644 --- a/forge-web/lib/sdk/cost.test.ts +++ b/forge-web/lib/sdk/cost.test.ts @@ -15,6 +15,7 @@ import { previewCreate, previewDelete, previewReplace, + priceBoardWrites, REPLACE_MIN_CREDITS, sumPreviews, type FirstWrite, @@ -377,3 +378,25 @@ describe('a passkey entry (vaultEntry)', () => { expect(-previewDelete('vaultEntry').credits).toBeLessThanOrEqual(26_654_372) }) }) + +describe('boards (UPDATE-3, estimated)', () => { + it('prices a card as design §7 quotes: about 0.0005 DASH to create, a few hundred-thousandths to move', () => { + const create = previewCreate('card', { rank: 'V' }, S).dash + expect(create).toBeGreaterThan(0.0004) + expect(create).toBeLessThan(0.0006) + const move = previewReplace('card', { rank: 'Vx' }) + expect(move.dash).toBeLessThan(0.00005) + expect(move.minCredits).toBeLessThanOrEqual(move.credits) + }) + + it('priceBoardWrites sums creates and replaces, and nothing costs nothing', () => { + expect(priceBoardWrites(0, 0).credits).toBe(0) + const one = priceBoardWrites(1, 0).credits + const replace = priceBoardWrites(0, 1).credits + expect(replace).toBeLessThan(one / 5) + expect(priceBoardWrites(3, 2).credits).toBe(3 * one + 2 * replace) + // sealed writes store their framing too; a board's definition costs more than a card + expect(priceBoardWrites(1, 0, { sealed: true }).credits).toBeGreaterThan(one) + expect(priceBoardWrites(1, 0, { type: 'board' }).credits).toBeGreaterThan(one) + }) +}) diff --git a/forge-web/lib/sdk/cost.ts b/forge-web/lib/sdk/cost.ts index 8f4d0b5f7..2ee45ae85 100644 --- a/forge-web/lib/sdk/cost.ts +++ b/forge-web/lib/sdk/cost.ts @@ -139,6 +139,12 @@ export const BASE_CREDITS: Readonly> = { // UPDATE-2 (the passkey vault), measured on testnet (2026-10-26, passkey-vault.live.test.ts): a // later entry 33.11M, an identity's first 42.9M–51.5M. Its byte fields are in the base (not text). vaultEntry: 34_000_000, + // UPDATE-3 (boards, `docs/design/boards.md` §3, §7): ESTIMATED, never measured. Both are member + // documents shaped like the vault's entry (a few integers, one or two short strings, a unique + // index ending in `$ownerId`); a card also writes the `recent` index, a board its definition + // text (priced per byte). Re-measure once a network carries forge-meta v3. + board: 40_000_000, + card: 42_000_000, } /** @@ -215,6 +221,11 @@ export const FIRST_WRITE_CREDITS: Readonly> = { packMirror: { repo: 16_000_000 }, // The owner's first entry builds its `byCredential` subtree: 51.5M first vs 33.1M on testnet. vaultEntry: { author: 18_000_000 }, + // UPDATE-3, ESTIMATED from the vault's 18.4M first-entry surcharge: `repo` the home repo's first + // board (its `byKey` repo level) or a board's first card (`recent`); `target` an item's first + // card anywhere (`onItem`'s item level). + board: { repo: 10_000_000 }, + card: { repo: 10_000_000, target: 18_000_000 }, } /** @@ -601,15 +612,51 @@ export const REPLACE_BASE_CREDITS = 17_000_000 */ export const REPLACE_MIN_CREDITS = 3_500_000 +/** + * The fixed part of a replace of the types whose replace was measured (or is estimated) far + * below {@link REPLACE_BASE_CREDITS}: the passkey vault's entry replace measured 3.1M credits on + * testnet (UPDATE-2); a board's or card's replace (UPDATE-3) is ESTIMATED from it, since a card + * move changes as little (its column and rank). Their text is priced per byte as for any replace. + */ +export const REPLACE_BASE_BY_TYPE: Readonly> = { + board: 4_000_000, + card: 4_000_000, +} + /** Preview for replacing a document's `changes`: a range, from {@link REPLACE_MIN_CREDITS}. */ export function previewReplace(documentType: string, changes: Readonly> = {}): CostPreview { const bytes = textBytes(changes) - const credits = REPLACE_BASE_CREDITS + CREDITS_PER_TEXT_BYTE * bytes + const credits = (REPLACE_BASE_BY_TYPE[documentType] ?? REPLACE_BASE_CREDITS) + CREDITS_PER_TEXT_BYTE * bytes // Drive estimates a replace like a create of the document; its requirement is at most that. const measured = ADMISSION_CREDITS[documentType] return { ...previewCredits(credits, measured ? admissionFor(documentType, bytes, credits) : undefined), minCredits: REPLACE_MIN_CREDITS } } +/** + * The typical bytes one board write stores beyond its fixed shape, for {@link priceBoardWrites}: + * a card's rank and a few field values; a board's name and a template-sized definition (§2.7). + * A private repository's write stores them sealed (`enc`), with 29 bytes of framing and padding + * to 32 (`private-repos.md` §4.6). + */ +const BOARD_WRITE_BYTES = { card: 40, board: 1200 } as const +const SEALED_EXTRA_BYTES = 29 + 32 + +/** + * What a multi-write board action costs before it is signed (`docs/design/boards.md` §5.3, §5.4, + * §2.6's re-rank): `creates` member documents written for the first time (a card for an item the + * signer has none for) and `replaces` replaces of the signer's own. `type`: `card` (the default) + * or `board`; `sealed`: a private repository's (its fields in `enc`). ESTIMATED: neither type has + * been measured on a network yet ({@link BASE_CREDITS}). + */ +export function priceBoardWrites(creates: number, replaces: number, { type = 'card', sealed = false }: { readonly type?: 'card' | 'board'; readonly sealed?: boolean } = {}): CostPreview { + const n = BOARD_WRITE_BYTES[type] + (sealed ? SEALED_EXTRA_BYTES : 0) + const sample = { text: 'x'.repeat(n) } + const parts: CostPreview[] = [] + for (let i = 0; i < creates; i++) parts.push(previewCreate(type, sample)) + for (let i = 0; i < replaces; i++) parts.push(previewReplace(type, sample)) + return parts.length === 0 ? previewCredits(0) : sumPreviews(parts) +} + /** Preview for deleting one document of `documentType` (usually a refund: negative credits). */ export function previewDelete(documentType: string): CostPreview { return previewCredits(DELETE_CREDITS[documentType] ?? DEFAULT_DELETE_CREDITS) diff --git a/forge-web/lib/sdk/index.ts b/forge-web/lib/sdk/index.ts index ed89ef792..842236c33 100644 --- a/forge-web/lib/sdk/index.ts +++ b/forge-web/lib/sdk/index.ts @@ -67,6 +67,7 @@ export { previewCredits, previewDelete, previewReplace, + priceBoardWrites, sumPreviews, withAddressee, type CostPreview, diff --git a/tools/private-repos-vectors/boards.py b/tools/private-repos-vectors/boards.py new file mode 100644 index 000000000..c83f58a19 --- /dev/null +++ b/tools/private-repos-vectors/boards.py @@ -0,0 +1,243 @@ +"""Independent reference for sealed boards and cards (docs/security/private-repos.md §4.6, +docs/design/boards.md §3.3). No contract generation changes. + +python3 tools/private-repos-vectors/boards.py --write-vectors +python3 tools/private-repos-vectors/boards.py --check + +Writes forge-contracts/vectors/sealed_board__*.json: `seal` (the TLV, its padding, the AD and the +enc under a fixed nonce, or the writer's refusal) and `open` (what a reader makes of a stored +document). forge-web `lib/private/board.conformance.test.ts` runs them byte for byte; forge-core +has no reader yet and its rules harness skips the case. +""" +import argparse +import json +import pathlib +import re +import struct + +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +import gen as G + +OUT = pathlib.Path(__file__).resolve().parents[2] / 'forge-contracts/vectors' +CASE = 'sealed_board' +VECTORS = [] + +TAG = dict(name=32, spec=33, col=34, rank=35, fields=36, padding=64) +MAX_PT = dict(board=5120 - 29, card=2560 - 29) +OTHER_OWNER = bytes([0x23]) * 32 +ITEM = bytes([0x44]) * 32 +OTHER_ITEM = bytes([0x45]) * 32 +SPEC = '{"v":1,"columns":[{"id":1,"name":"Todo"},{"id":2,"name":"In progress"},{"id":3,"name":"Done"}],"def":1,"done":3}' +RANK = re.compile(r'^[0-9A-Za-z]{0,62}[1-9A-Za-z]$') +NAME = re.compile(r'^[^\x00-\x1f\x7f]*[^\s\x00-\x1f\x7f][^\x00-\x1f\x7f]*$') + + +def vector(name, description, op, inp, expected): + VECTORS.append(dict(name=name, description=description, case=CASE, rules='v2', input=dict(op=op, **inp), expected=expected)) + + +def records(kind, f): + """The records of `f`, ascending, without padding (§4.6).""" + if kind == 'board': + return G.tlv((TAG['name'], f['name'].encode()), (TAG['spec'], f['spec'].encode())) + out = [] + if 'col' in f: + out.append((TAG['col'], bytes([f['col']]))) + if 'rank' in f: + out.append((TAG['rank'], f['rank'].encode())) + if 'f' in f: + out.append((TAG['fields'], f['f'].encode())) + return G.tlv(*out) + + +def padded(kind, body): + """`body` plus the tag-64 record that pads it to a multiple of 32 within the type's cap.""" + cap = MAX_PT[kind] + if len(body) + 3 > cap: + return body + r = min((32 - (len(body) + 3) % 32) % 32, cap - 3 - len(body)) + return body + G.rec(TAG['padding'], bytes(r)) + + +def writer_check(kind, f): + """None when `f` may be sealed, else the writer's error ('malformed').""" + if kind == 'board': + name, spec = f['name'], f['spec'] + if not (1 <= len(name) <= 63 and len(name.encode()) <= 252 and NAME.match(name)): + return 'malformed' + if not 1 <= len(spec.encode()) <= 4096: + return 'malformed' + return None + if 'col' in f and not 0 <= f['col'] <= 255: + return 'malformed' + if 'rank' in f and not RANK.match(f['rank']): + return 'malformed' + if 'f' in f and not 1 <= len(f['f'].encode()) <= 2048: + return 'malformed' + return None + + +def bind(doc): + if doc['type'] == 'board': + return struct.pack('>I', doc['key']) + return struct.pack('>I', doc['board']) + bytes.fromhex(doc['item']) + + +def ad(owner, e, doc): + return b'dash-forge/v2/doc\x00\x01' + G.repoId + owner + G.u32(e) + doc['type'].encode() + b'\x00' + bind(doc) + + +def seal(K, e, owner, doc, pt, nonce=G.NONCE): + A = ad(owner, e, doc) + return A, b'\x01' + nonce + AESGCM(G.k_doc(K, e)).encrypt(nonce, pt, A) + + +def board(key=7): + return dict(type='board', key=key) + + +def card(board_key=7, item=ITEM): + return dict(type='card', board=board_key, item=item.hex()) + + +def seal_vectors(): + def v(name, desc, doc, f, K=G.K0, e=0): + inp = dict(repoId=G.H(G.repoId), key=G.H(K), epoch=e, ownerId=G.H(G.ownerId), nonce=G.H(G.NONCE), doc=doc, fields=f) + err = writer_check(doc['type'], f) + if err is None and doc['type'] == 'board' and not 1 <= doc['key'] <= 0xffffffff: + err = 'malformed' + if err is not None: + vector('seal_' + name, desc, 'seal', inp, dict(error=err)) + return + pt = padded(doc['type'], records(doc['type'], f)) + A, enc = seal(K, e, G.ownerId, doc, pt) + vector('seal_' + name, desc, 'seal', inp, dict(ad=G.H(A), tlv=G.H(pt), enc=G.H(enc))) + + v('board', 'a board under epoch 0: its name (TLV 32) and definition (33), padded to 32 bytes; the AD binds ' + 'u32(key).', board(), dict(name='Roadmap', spec=SPEC)) + v('board_epoch1', 'the same board under epoch 1: another key, another epoch in the AD.', board(), dict(name='Roadmap', spec=SPEC), G.K1, 1) + v('board_key_max', 'the largest key, 4294967295.', board(0xffffffff), dict(name='Ops', spec='{"v":1,"columns":[{"id":1,"name":"Todo"}]}')) + v('board_unicode_name', 'a name of 11 characters and 13 bytes.', board(), dict(name='Sprint ✨ 12', spec=SPEC)) + v('board_name_63_chars', 'a name at its 63-character cap.', board(), dict(name='n' * 63, spec=SPEC)) + v('board_name_64_chars', 'a name over 63 characters is refused before sealing.', board(), dict(name='n' * 64, spec=SPEC)) + v('board_name_blank', 'a name of only white space is refused (the schema pattern needs a visible character).', board(), dict(name=' ', spec=SPEC)) + v('board_name_control', 'a name with a control character is refused.', board(), dict(name='a\tb', spec=SPEC)) + v('board_spec_4096_bytes', 'a definition at its 4096-byte cap (the TLV does not judge its JSON: the board rules do).', board(), dict(name='Big', spec='x' * 4096)) + v('board_spec_4097_bytes', 'a definition over 4096 bytes is refused.', board(), dict(name='Big', spec='x' * 4097)) + v('board_spec_empty', 'a board needs a definition.', board(), dict(name='Empty', spec='')) + v('board_key_zero', 'key 0 is not a board key.', board(0), dict(name='Zero', spec=SPEC)) + v('card', 'a card: column (TLV 34, one byte), rank (35) and field values (36); the AD binds u32(board) and the ' + 'item id.', card(), dict(col=2, rank='V', f='{"1":3,"2":5}')) + v('card_empty', 'a card with nothing but its state (an archive or removal of an item never placed): only the ' + 'padding record.', card(), {}) + v('card_col_zero', 'column 0 ("No status") is written: one byte 0x00.', card(), dict(col=0)) + v('card_rank_63', 'a rank at its 63-digit cap.', card(), dict(rank='z' * 63)) + v('card_rank_trailing_zero', 'an explicit rank never ends in 0.', card(), dict(rank='V0')) + v('card_rank_64', 'a rank over 63 digits is refused.', card(), dict(rank='z' * 64)) + v('card_col_256', 'a column is 0-255.', card(), dict(col=256)) + v('card_fields_2048_bytes', 'field values at their 2048-byte cap.', card(), dict(f='{"5":"' + 't' * 2040 + '"}')) + v('card_fields_2049_bytes', 'field values over 2048 bytes are refused.', card(), dict(f='{"5":"' + 't' * 2041 + '"}')) + + +CTX0 = G.CTX0 +CTX01 = G.CTX01 + + +def open_vectors(): + def v(name, desc, doc, context, expected, enc=None, f=None, pt=None, K=G.K0, owner=G.ownerId, **extra): + d = dict(doc, ownerId=G.H(owner), epoch=extra.pop('epoch', 0), plaintext=extra.pop('plaintext', False)) + if enc is None: + body = pt if pt is not None else padded(doc['type'], records(doc['type'], f)) + _, enc = seal(K, d['epoch'], G.ownerId, doc, body) + if enc is not False: + d['enc'] = G.H(enc) + assert not extra, extra + vector('open_' + name, desc, 'open', dict(repoId=G.H(G.repoId), context=context, doc=d), expected) + + B = dict(name='Roadmap', spec=SPEC) + C = dict(col=2, rank='V', f='{"1":3}') + _, board_enc = seal(G.K0, 0, G.ownerId, board(), padded('board', records('board', B))) + _, card_enc = seal(G.K0, 0, G.ownerId, card(), padded('card', records('card', C))) + v('board', 'a sealed board opens under K_0 to its name and definition.', board(), CTX0, G.readable(B), f=B) + v('card', 'a sealed card opens to its column, rank and field values.', card(), CTX0, G.readable(C), f=C) + v('card_empty', 'a card sealed with no fields opens to none.', card(), CTX0, G.readable({}), f={}) + v('board_epoch1', 'a board sealed under epoch 1 opens with K_1.', board(), CTX01, G.readable(B), f=B, K=G.K1, epoch=1) + v('superseded_epoch_still_opens', 'a board under superseded epoch 0 by a member removed since still opens: both ' + 'types are member-gated at consensus on every write, so the height part of the late rule (§8.2) does not apply.', + board(), CTX01, G.readable(B), f=B) + v('card_moved_to_other_item', 'the AD binds the item: a card\'s enc copied onto a card for another item fails the ' + 'tag.', card(item=OTHER_ITEM), CTX0, G.unreadable('badTag'), enc=card_enc) + v('card_moved_to_other_board', 'the AD binds the board key: the enc copied to another board fails the tag.', + card(board_key=8), CTX0, G.unreadable('badTag'), enc=card_enc) + v('board_moved_to_other_key', 'a board\'s enc copied under another key fails the tag.', board(8), CTX0, + G.unreadable('badTag'), enc=board_enc) + v('other_owner', 'the AD binds $ownerId: another member cannot re-post this enc as theirs.', board(), CTX0, + G.unreadable('badTag'), enc=board_enc, owner=OTHER_OWNER) + v('card_enc_as_board', 'the AD binds the type: a card\'s enc stored as a board (key 7, the card\'s board) fails ' + 'the tag.', board(), CTX0, G.unreadable('badTag'), enc=card_enc) + v('no_key', 'epoch 0 exists but the reader holds only K_1: Unreadable(NoKey).', board(), + G.ctx({1: G.K1}, {0: ('c0', 10), 1: ('c1', 1000)}), G.unreadable('noKey'), enc=board_enc) + v('no_epoch', 'an epoch without an anchor does not exist: Unreadable(NoEpoch).', board(), + G.ctx({0: G.K0}, {1: ('c1', 1000)}), G.unreadable('noEpoch'), enc=board_enc) + v('plaintext_beside_enc', 'a sealed board that also carries a plaintext name or spec is malformed (the contract\'s ' + 'noPlain refuses it; a reader does too).', board(), CTX0, G.MALFORMED, enc=board_enc, plaintext=True) + v('private_without_enc', 'a private repository\'s board without enc is malformed: its readers read only sealed ' + 'boards.', board(), CTX0, G.MALFORMED, enc=False) + v('version_3', 'a version other than 0x01 is a later client\'s (a public repository\'s members-only board): ' + 'Unreadable(UnknownVersion), listed, never malformed.', board(), CTX0, G.unreadable('unknownVersion'), + enc=b'\x03' + board_enc[1:]) + v('short_enc', 'an enc shorter than 29 bytes is malformed before any key is used.', board(), CTX0, G.MALFORMED, + enc=board_enc[:28]) + burned1 = G.ctx({0: G.K0, 1: G.K1}, {0: ('c0', 10), 1: ('c1', 1000)}, burned=[1]) + v('under_burned_epoch_by_removed_member', 'the burned clause of §8.2 still applies: a card under burned epoch 1 by ' + 'someone who is no longer a member is Unreadable(Late).', card(), burned1, G.unreadable('late'), f=C, K=G.K1, epoch=1) + v('under_burned_epoch_by_member', 'the same card by a current member opens.', card(), dict(burned1, members=[G.H(G.ownerId)]), + G.readable(C), f=C, K=G.K1, epoch=1) + rec = G.rec + v('tlv_out_of_order', 'records out of order (rank before column) are malformed.', card(), CTX0, G.MALFORMED, + pt=rec(35, b'V') + rec(34, b'\x02')) + v('tlv_repeated', 'a repeated record is malformed.', card(), CTX0, G.MALFORMED, pt=rec(34, b'\x02') + rec(34, b'\x03')) + v('tlv_board_tag_in_card', 'a board\'s tag (33) in a card is malformed.', card(), CTX0, G.MALFORMED, pt=rec(33, b'{}')) + v('tlv_content_tag_in_board', 'another kind\'s tag (2, a body) in a board is malformed.', board(), CTX0, G.MALFORMED, + pt=rec(2, b'x') + rec(32, b'Roadmap') + rec(33, SPEC.encode())) + v('tlv_extension_skipped', 'tags 64-255 are extensions: skipped.', card(), CTX0, G.readable(dict(col=1)), + pt=rec(34, b'\x01') + rec(70, b'later')) + v('tlv_col_two_bytes', 'a column is exactly one byte.', card(), CTX0, G.MALFORMED, pt=rec(34, b'\x00\x01')) + v('tlv_rank_trailing_zero', 'a sealed rank ending in 0 is malformed, as the plaintext pattern refuses it.', card(), + CTX0, G.MALFORMED, pt=rec(35, b'V0')) + v('tlv_empty_rank_absent', 'a zero-length record of a field with minLength 1 counts as absent.', card(), CTX0, + G.readable(dict(col=1)), pt=rec(34, b'\x01') + rec(35, b'')) + v('tlv_board_without_spec', 'a board needs its definition.', board(), CTX0, G.MALFORMED, pt=rec(32, b'Roadmap')) + v('tlv_truncated', 'a record running past the end is malformed.', board(), CTX0, G.MALFORMED, + pt=rec(32, b'Roadmap') + bytes([33, 0, 9]) + b'{}') + + +def build(): + seal_vectors() + open_vectors() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--write-vectors', action='store_true') + ap.add_argument('--check', action='store_true') + args = ap.parse_args() + build() + expected = {f"{CASE}__{v['name']}.json": json.dumps(v, indent=2, ensure_ascii=False) + '\n' for v in VECTORS} + assert len(expected) == len(VECTORS), 'duplicate vector names' + if args.write_vectors: + for path in OUT.glob(f'{CASE}__*.json'): + if path.name not in expected: + path.unlink() + for name, text in expected.items(): + (OUT / name).write_text(text) + if args.check: + actual = {p.name: p.read_text() for p in OUT.glob(f'{CASE}__*.json')} + if actual != expected: + raise SystemExit('sealed board vectors are stale') + print(f'sealed board vectors: {len(expected)}' + (' checked' if args.check else '')) + + +if __name__ == '__main__': + main() From c6b9a8264aa597e194e65eb55e05a84918ea1d29 Mon Sep 17 00:00:00 2001 From: pasta Date: Tue, 27 Oct 2026 21:16:55 +0000 Subject: [PATCH 04/26] feat(web): board table and roadmap layout skeletons BoardTable and BoardRoadmap exports for the board shell to import; the layout props gain an optional onViewChange (additive) for sort/group changes that the shell writes into the URL. Co-Authored-By: Claude Opus 5.5 --- .../components/repo/boards/board-roadmap.tsx | 9 ++++++ .../components/repo/boards/board-table.tsx | 9 ++++++ .../components/repo/boards/layout-props.ts | 30 +++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 forge-web/components/repo/boards/board-roadmap.tsx create mode 100644 forge-web/components/repo/boards/board-table.tsx create mode 100644 forge-web/components/repo/boards/layout-props.ts diff --git a/forge-web/components/repo/boards/board-roadmap.tsx b/forge-web/components/repo/boards/board-roadmap.tsx new file mode 100644 index 000000000..89a2b029b --- /dev/null +++ b/forge-web/components/repo/boards/board-roadmap.tsx @@ -0,0 +1,9 @@ +'use client' + +/** The roadmap layout of a board (design `docs/design/boards.md` §4.3). Skeleton: fleshed out next. */ + +import type { BoardLayoutProps } from './layout-props' + +export function BoardRoadmap(props: BoardLayoutProps): JSX.Element { + return
{props.items.length} items
+} diff --git a/forge-web/components/repo/boards/board-table.tsx b/forge-web/components/repo/boards/board-table.tsx new file mode 100644 index 000000000..70c1e835c --- /dev/null +++ b/forge-web/components/repo/boards/board-table.tsx @@ -0,0 +1,9 @@ +'use client' + +/** The table layout of a board (design `docs/design/boards.md` §4.2). Skeleton: fleshed out next. */ + +import type { BoardLayoutProps } from './layout-props' + +export function BoardTable(props: BoardLayoutProps): JSX.Element { + return
{props.items.length} items
+} diff --git a/forge-web/components/repo/boards/layout-props.ts b/forge-web/components/repo/boards/layout-props.ts new file mode 100644 index 000000000..6c50a20dd --- /dev/null +++ b/forge-web/components/repo/boards/layout-props.ts @@ -0,0 +1,30 @@ +/** + * What the board page hands each layout (design `docs/design/boards.md` §4): the board shell + * (`board-page.tsx`) owns loading, the view, the query and the item panel; a layout + * (`board-kanban.tsx`, `board-table.tsx`, `board-roadmap.tsx`) renders the shown items and asks + * the shell to write. + */ + +import type { BoardHookState } from '@/hooks/use-board' +import type { BoardItem, BoardSpec, BoardView as SavedView, Placement } from '@/lib/rules/boards' + +export interface BoardLayoutProps { + /** The board hook: fold, cards, role (`can`), pending writes and every mutation. */ + readonly state: BoardHookState + /** The parsed definition the layout renders (never null here: the shell shows errors itself). */ + readonly spec: BoardSpec + /** The view in force: a saved view, or the URL's unsaved changes over one. */ + readonly view: SavedView + /** The items the view's query matches, archived ones only when the query asks for them. */ + readonly items: readonly BoardItem[] + /** Each shown item's placement, by item id. */ + readonly placements: ReadonlyMap + /** Open the item panel (§5.5) on an item. */ + onOpenItem(itemId: string): void + /** + * Change the view in force (§4: unsaved changes live in the URL): a layout asks for a sort, a + * grouping or a roadmap zoom it offers; the shell writes it into the URL. Absent: the layout's + * controls that would change the view are read-only. + */ + onViewChange?(change: Partial): void +} From cbb4a611e4892f32f7344b0c204c6dc8a2a2bf5e Mon Sep 17 00:00:00 2001 From: pasta Date: Tue, 27 Oct 2026 21:29:13 +0000 Subject: [PATCH 05/26] feat(web): board table and roadmap layouts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The table layout (boards.md §4.2): view columns with Title first, header sort through onViewChange, sections by view.group with counts, WIP and the first number field's sum, Status and custom fields edited in place (one card write each), a roving-tabindex keyboard grid, private, archived and pending rows. The roadmap layout (§4.3): bars across an iteration or between two date fields, weeks/months/quarters zoom, today's line and iteration bands, unscheduled items beside, a list for screen readers, and drag to move or stretch a date bar (one card write on release). board-fields.tsx holds the value editors and labels the table, settings and issue sidebar share. layout-props gains the shell's home/addr/labels (additive). Co-Authored-By: Claude Opus 5.5 --- .../components/repo/boards/board-fields.tsx | 432 ++++++++++++++++ .../repo/boards/board-roadmap.test.tsx | 146 ++++++ .../components/repo/boards/board-roadmap.tsx | 478 +++++++++++++++++- .../repo/boards/board-table.test.tsx | 184 +++++++ .../components/repo/boards/board-table.tsx | 409 ++++++++++++++- .../components/repo/boards/layout-fixture.ts | 145 ++++++ .../components/repo/boards/layout-props.ts | 11 + 7 files changed, 1799 insertions(+), 6 deletions(-) create mode 100644 forge-web/components/repo/boards/board-fields.tsx create mode 100644 forge-web/components/repo/boards/board-roadmap.test.tsx create mode 100644 forge-web/components/repo/boards/board-table.test.tsx create mode 100644 forge-web/components/repo/boards/layout-fixture.ts diff --git a/forge-web/components/repo/boards/board-fields.tsx b/forge-web/components/repo/boards/board-fields.tsx new file mode 100644 index 000000000..ec7da826f --- /dev/null +++ b/forge-web/components/repo/boards/board-fields.tsx @@ -0,0 +1,432 @@ +'use client' + +/** + * Pieces the board layouts, the board settings and the issue sidebar share (design + * `docs/design/boards.md` §2.2, §4, §5.6): board URLs, how a field value and a view key read, + * the editor of one field value and the Status select, an item's state icon, a colour dot. + */ + +import { useEffect, useRef, useState } from 'react' +import { CheckCircle2, CircleDot } from 'lucide-react' +import { repoHref, type RepoAddress } from '@/hooks/use-query-param' +import { STATE_TEXT } from '@/lib/design/state' +import { dateDays, fieldKeyId, fieldValueOk, iterationAt, iterationRange, type BoardField, type BoardItem, type BoardSpec, type FieldValue, type IterationRange } from '@/lib/rules/boards' +import { disabledField } from '@/components/ui/input' +import { pullStateView } from '@/components/repo/pull-state' +import { LabelChip } from '@/components/repo/issue-bits' +import { Author } from '@/components/author' +import { cn } from '@/lib/utils' + +// --------------------------------------------------------------------------------------------- +// URLs (§2.1: `/repo/board?owner=&name=&b=`) +// --------------------------------------------------------------------------------------------- + +/** A repository's boards list. */ +export function boardsHref(addr: RepoAddress, extra: Record = {}): string { + return repoHref('/repo/boards', addr, extra) +} + +/** Board `key` of `addr`. */ +export function boardHref(addr: RepoAddress, key: number, extra: Record = {}): string { + return repoHref('/repo/board', addr, { b: String(key), ...extra }) +} + +/** Board `key`'s settings. */ +export function boardSettingsHref(addr: RepoAddress, key: number): string { + return repoHref('/repo/board/settings', addr, { b: String(key) }) +} + +// --------------------------------------------------------------------------------------------- +// How values read +// --------------------------------------------------------------------------------------------- + +const DAY_MS = 86_400_000 + +/** `YYYY-MM-DD` as "Oct 26, 2026" (UTC, as the board stores dates); `year: false` drops the year. */ +export function dayText(day: string, { year = true }: { readonly year?: boolean } = {}): string { + const d = dateDays(day) + if (d === null) return day + return new Date(d * DAY_MS).toLocaleDateString(undefined, { month: 'short', day: 'numeric', ...(year ? { year: 'numeric' } : {}), timeZone: 'UTC' }) +} + +/** "Oct 26 – Nov 8, 2026" (the start's year shown only when the two differ). */ +export function dayRangeText(start: string, end: string): string { + if (start === end) return dayText(start) + const sameYear = start.slice(0, 4) === end.slice(0, 4) + return `${dayText(start, { year: !sameYear })} – ${dayText(end)}` +} + +/** Iteration `k` of an `iter` field by name ("Iteration 3"). */ +export function iterationName(field: BoardField, k: number): string { + return iterationRange(field, k)?.name ?? `${field.name} ${k + 1}` +} + +/** A field value as text: an option's name, a number as stored, a date, an iteration's name; '' for none. */ +export function fieldValueText(field: BoardField, v: FieldValue | undefined): string { + if (v === undefined) return '' + switch (field.type) { + case 'sel': + return field.options?.find((o) => o.id === v)?.name ?? '' + case 'date': + return dayText(String(v)) + case 'iter': + return typeof v === 'number' ? iterationName(field, v) : '' + default: + return String(v) + } +} + +/** What each built-in view key is called (§2.7). */ +export const BUILTIN_KEY_LABEL: Readonly> = { + title: 'Title', + number: 'Number', + repo: 'Repository', + state: 'State', + author: 'Author', + assignees: 'Assignees', + assignee: 'Assignee', + labels: 'Labels', + label: 'Label', + milestone: 'Milestone', + created: 'Created', + status: 'Status', + rank: 'Board order', +} + +/** A view key's name: a built-in's, or a custom field's (`f`). */ +export function viewKeyLabel(spec: BoardSpec, key: string): string { + const k = key.startsWith('-') ? key.slice(1) : key + const builtin = BUILTIN_KEY_LABEL[k] + if (builtin !== undefined) return builtin + const m = /^f(\d+)$/.exec(k) + const field = m ? spec.fields.find((f) => f.id === Number(m[1])) : undefined + return field?.name ?? k +} + +/** A status column's name; "No status" for 0. */ +export function columnName(spec: BoardSpec, col: number): string { + return spec.columns.find((c) => c.id === col)?.name ?? 'No status' +} + +// --------------------------------------------------------------------------------------------- +// Small pictures +// --------------------------------------------------------------------------------------------- + +/** A column's or option's colour as a dot; a dashed ring where it has none. */ +export function ColorDot({ color, className }: { readonly color?: string | undefined; readonly className?: string }): JSX.Element { + return ( + + ) +} + +/** An issue's or PR's state icon, as the lists draw it, with its name for screen readers. */ +export function ItemStateIcon({ item, className }: { readonly item: Pick; readonly className?: string }): JSX.Element { + if (item.kind === 'pr') { + const v = pullStateView({ open: item.state === 'open', merged: item.state === 'merged' }) + return ( + <> + + {`${v.label} pull request`} + + ) + } + const open = item.state === 'open' + const Icon = open ? CircleDot : CheckCircle2 + return ( + <> + + {open ? 'Open issue' : 'Closed issue'} + + ) +} + +// --------------------------------------------------------------------------------------------- +// Editing one value +// --------------------------------------------------------------------------------------------- + +/** A compact select or input, as the lists' own selects. */ +export const controlClass = + 'rounded-md border border-anvil-300 bg-white px-2 py-1 text-dense text-anvil-900 dark:border-anvil-700 dark:bg-anvil-950 dark:text-anvil-100 coarse:min-h-11 ' + disabledField + +/** + * The iterations a picker offers: two before the current one to five after it (from the first + * when none has started), and `keep` (the item's own) wherever it is. + */ +export function iterationChoices(field: BoardField, now: number, keep?: number): IterationRange[] { + const cur = iterationAt(field, now) + const first = iterationRange(field, 0) + const at = cur ?? (first !== null && now < first.startMs ? 0 : null) + const ks = new Set() + if (at !== null) for (let k = Math.max(0, at - 2); k <= at + 5; k++) ks.add(k) + if (keep !== undefined) ks.add(keep) + return [...ks] + .sort((a, b) => a - b) + .map((k) => iterationRange(field, k)) + .filter((r): r is IterationRange => r !== null) +} + +/** What a typed value means for `field`: a value, null (cleared), or why it is refused. */ +export function parseFieldInput(field: BoardField, raw: string): { readonly value: FieldValue | null } | { readonly error: string } { + const t = raw.trim() + if (t === '') return { value: null } + let v: FieldValue + switch (field.type) { + case 'num': + v = Number(t) + if (!/^-?(\d+\.?\d*|\.\d+)$/.test(t)) return { error: 'Enter a number.' } + break + case 'sel': + case 'iter': + v = Number(t) + break + default: + v = t + } + if (fieldValueOk(field, v)) return { value: v === 0 ? 0 : v } + switch (field.type) { + case 'num': + return { error: 'Numbers go up to 10^15, and down to 0.000001 apart from 0.' } + case 'date': + return { error: 'Enter a date.' } + case 'text': + return { error: 'Text is at most 200 characters.' } + default: + return { error: `That isn't one of ${field.name}'s values.` } + } +} + +/** + * The editor of one field value: a select for a single-select or iteration field (a choice is + * written at once), an input for a number, date or text (written on Enter or when it loses + * focus; Escape cancels). An empty value clears it. `onCommit` gets the new value only when it + * differs. + */ +export function FieldInput({ + field, + value, + now, + onCommit, + onCancel, + id, + label, + autoFocus = false, + disabled = false, + className, +}: { + readonly field: BoardField + readonly value: FieldValue | undefined + readonly now: number + readonly onCommit: (value: FieldValue | null) => void + readonly onCancel?: () => void + readonly id?: string + /** The accessible name (the field's, by default). */ + readonly label?: string + readonly autoFocus?: boolean + readonly disabled?: boolean + readonly className?: string +}): JSX.Element { + const [draft, setDraft] = useState(value === undefined ? '' : String(value)) + const [error, setError] = useState(null) + const done = useRef(false) + useEffect(() => { + setDraft(value === undefined ? '' : String(value)) + setError(null) + }, [value]) + const name = label ?? field.name + const commit = (raw: string): void => { + const parsed = parseFieldInput(field, raw) + if ('error' in parsed) { + setError(parsed.error) + return + } + setError(null) + if ((parsed.value ?? undefined) !== value) onCommit(parsed.value) + else onCancel?.() + } + if (field.type === 'sel' || field.type === 'iter') { + const choices = field.type === 'sel' ? (field.options ?? []).map((o) => ({ v: String(o.id), name: o.name })) : iterationChoices(field, now, typeof value === 'number' ? value : undefined).map((r) => ({ v: String(r.index), name: `${r.name} (${dayRangeText(r.start, r.end)})` })) + return ( + + ) + } + return ( + + setDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault() + e.stopPropagation() + done.current = true + commit(draft) + } else if (e.key === 'Escape') { + e.preventDefault() + e.stopPropagation() + done.current = true + setDraft(value === undefined ? '' : String(value)) + setError(null) + onCancel?.() + } + }} + onBlur={() => { + // Enter and Escape already settled it; a click elsewhere writes what was typed. + if (done.current) { + done.current = false + return + } + commit(draft) + }} + className={cn(controlClass, 'w-full min-w-0', field.type === 'num' && 'font-mono tabular-nums', className)} + /> + {error !== null ? ( + + {error} + + ) : null} + + ) +} + +/** The Status select: every column, and "No status" while the item has none. */ +export function StatusSelect({ + spec, + value, + onChange, + onCancel, + id, + label = 'Status', + autoFocus = false, + disabled = false, + className, +}: { + readonly spec: BoardSpec + readonly value: number + readonly onChange: (col: number) => void + readonly onCancel?: () => void + readonly id?: string + readonly label?: string + readonly autoFocus?: boolean + readonly disabled?: boolean + readonly className?: string +}): JSX.Element { + return ( + + ) +} + +// --------------------------------------------------------------------------------------------- +// Groups (§4.1, §4.2) +// --------------------------------------------------------------------------------------------- + +/** + * A group's heading, for a view grouped by `by` (`groupRows`' keys): a column or option with its + * colour, an iteration with its dates, a person, a label, a milestone, a repository (named as + * `items` name it); "No " for the empty group. + */ +export function GroupHeading({ spec, by, groupKey, items }: { readonly spec: BoardSpec; readonly by: string; readonly groupKey: string | number | null; readonly items: readonly BoardItem[] }): JSX.Element { + const field = (() => { + const id = fieldKeyId(by) + return id === null ? undefined : spec.fields.find((f) => f.id === id) + })() + if (by === 'status') { + const col = spec.columns.find((c) => c.id === groupKey) + return ( + + + {col?.name ?? 'No status'} + + ) + } + if (groupKey === null) return {`No ${viewKeyLabel(spec, by).toLowerCase()}`} + if (field?.type === 'sel') { + const opt = field.options?.find((o) => o.id === groupKey) + return ( + + + {opt?.name ?? String(groupKey)} + + ) + } + if (field?.type === 'iter' && typeof groupKey === 'number') { + const r = iterationRange(field, groupKey) + return ( + + {iterationName(field, groupKey)} + {r !== null ? {dayRangeText(r.start, r.end)} : null} + + ) + } + switch (by) { + case 'assignee': + return + case 'label': + return + case 'repo': + return {items.find((i) => i.repoId === groupKey)?.repo ?? String(groupKey)} + default: + return {String(groupKey)} + } +} diff --git a/forge-web/components/repo/boards/board-roadmap.test.tsx b/forge-web/components/repo/boards/board-roadmap.test.tsx new file mode 100644 index 000000000..c4f32f39a --- /dev/null +++ b/forge-web/components/repo/boards/board-roadmap.test.tsx @@ -0,0 +1,146 @@ +// @vitest-environment jsdom +/** + * The board's roadmap layout (design `docs/design/boards.md` §4.3): which fields it plots, the + * bars and their text, unscheduled items, today and the iterations, zoom, dragging a date bar + * (one card write), and the list for screen readers. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/components/author', () => ({ Author: ({ identityId }: { identityId: string }) => {identityId.slice(0, 4)} })) + +import { BoardRoadmap, barOf, roadmapDates, timelineSpan } from './board-roadmap' +import { HOME, NOW, SPEC, dayNo, fold, hookState, id, layoutProps, ITEMS } from './layout-fixture' +import type { BoardLayoutProps } from './layout-props' +import type { BoardSpec } from '@/lib/rules/boards' + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let root: Root +let el: HTMLDivElement +beforeEach(() => { + el = document.createElement('div') + document.body.append(el) + root = createRoot(el) +}) +afterEach(() => { + act(() => root.unmount()) + el.remove() +}) + +const render = (props: BoardLayoutProps): void => act(() => root.render()) +const bars = (): HTMLButtonElement[] => [...el.querySelectorAll('[data-testid="roadmap-bar"]')] +const rowOf = (c: string): HTMLElement => el.querySelector(`[data-item="${id(c)}"]`) as HTMLElement +const pointer = (target: Element, type: string, clientX: number): void => act(() => void target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, clientX, button: 0 }))) + +describe('roadmapDates and barOf', () => { + it('plots the first iteration field by default, else the first two date fields', () => { + const view = { id: 1, name: 'R', layout: 'roadmap' as const, q: '' } + expect(roadmapDates(SPEC, view)).toMatchObject({ kind: 'iter', field: { id: 3 } }) + expect(roadmapDates(SPEC, { ...view, date: [4, 5] })).toMatchObject({ kind: 'range', start: { id: 4 }, end: { id: 5 } }) + const noIter: BoardSpec = { ...SPEC, fields: SPEC.fields.filter((f) => f.type !== 'iter') } + expect(roadmapDates(noIter, view)).toMatchObject({ kind: 'range', start: { id: 4 }, end: { id: 5 } }) + expect(roadmapDates({ ...SPEC, fields: [] }, view)).toBeNull() + }) + + it('runs a bar across its iteration, or between its dates', () => { + const placements = fold() + const rowOf = (c: string) => ({ item: ITEMS.find((i) => i.id === id(c))!, placement: placements.get(id(c))! }) + const iter = roadmapDates(SPEC, { id: 1, name: 'R', layout: 'roadmap', q: '' })! + // Iteration 2 (index 1) of a 14-day cadence from Monday 2026-10-26 + expect(barOf(rowOf('b'), iter)).toEqual({ start: dayNo('2026-11-09'), end: dayNo('2026-11-22'), single: false }) + expect(barOf(rowOf('d'), iter)).toBeNull() + const range = roadmapDates(SPEC, { id: 1, name: 'R', layout: 'roadmap', q: '', date: [4, 5] })! + expect(barOf(rowOf('a'), range)).toEqual({ start: dayNo('2026-10-26'), end: dayNo('2026-11-06'), single: false }) + // only a start: a one-day mark + expect(barOf(rowOf('c'), range)).toEqual({ start: dayNo('2026-11-02'), end: dayNo('2026-11-02'), single: true }) + }) + + it('spans whole periods around every bar and today', () => { + const today = Math.floor(NOW / 86_400_000) + const s = timelineSpan([{ start: today + 100, end: today + 120, single: false }], today, 'months') + expect(s.from).toBeLessThanOrEqual(today) + expect(s.to).toBeGreaterThan(today + 120) + // months start on the 1st + expect(new Date(s.from * 86_400_000).toISOString().slice(8, 10)).toBe('01') + const w = timelineSpan([], today, 'weeks') + // weeks start on a Monday + expect(new Date(w.from * 86_400_000).getUTCDay()).toBe(1) + }) +}) + +describe('BoardRoadmap', () => { + it('draws a named bar per scheduled item, lists the rest beside it and for screen readers', () => { + const props = layoutProps({ layout: 'roadmap' }) + render(props) + // by iteration: a (Iteration 1) and b (Iteration 2) have one + expect(bars()).toHaveLength(2) + expect(bars()[0]?.getAttribute('aria-label')).toBe('#1 Write the parser: Oct 26 – Nov 8, 2026, Todo') + expect(bars()[1]?.getAttribute('aria-label')).toBe('#2 Ship the table: Nov 9 – Nov 22, 2026, In progress') + const unscheduled = el.querySelector('[data-testid="roadmap-unscheduled"]') as HTMLElement + expect(unscheduled.textContent).toContain('Unscheduled 3') + expect(unscheduled.textContent).toContain('Fix the roadmap') + expect(unscheduled.textContent).toContain('A private item') + expect(unscheduled.textContent).not.toContain('Secret') + expect(el.querySelector('[data-testid="roadmap-list"]')?.querySelectorAll('li')).toHaveLength(2) + expect(el.querySelector('[data-testid="roadmap-today"]')).not.toBeNull() + // the iteration bands are named in the header + expect(el.textContent).toContain('Iteration 1') + }) + + it('opens the item from its bar and from the unscheduled list', () => { + const props = layoutProps({ layout: 'roadmap' }, { state: hookState({ can: { place: false, edit: false } }) }) + render(props) + act(() => bars()[1]?.click()) + expect(props.onOpenItem).toHaveBeenCalledWith(id('b')) + const listed = [...el.querySelectorAll('[data-testid="roadmap-unscheduled"] button')] + act(() => listed[0]?.click()) + expect(props.onOpenItem).toHaveBeenCalledTimes(2) + }) + + it('switches zoom', () => { + render(layoutProps({ layout: 'roadmap' })) + const zoom = (name: string) => [...el.querySelectorAll('[aria-label="Zoom"] button')].find((b) => b.textContent === name) as HTMLButtonElement + expect(zoom('Months').getAttribute('aria-pressed')).toBe('true') + const before = bars()[0]?.style.width + act(() => zoom('Weeks').click()) + expect(zoom('Weeks').getAttribute('aria-pressed')).toBe('true') + expect(bars()[0]?.style.width).not.toBe(before) + }) + + it('moves a date bar by dragging it: one card write with both dates', async () => { + const props = layoutProps({ layout: 'roadmap', date: [4, 5] }) + render(props) + const bar = rowOf('a').querySelector('[data-testid="roadmap-bar"]') as HTMLElement + expect(bar.getAttribute('aria-label')).toBe('#1 Write the parser: Oct 26 – Nov 6, 2026, Todo') + // months zoom: 6 px a day, so 42 px is a week + pointer(bar, 'pointerdown', 100) + pointer(bar, 'pointermove', 142) + await act(async () => void bar.dispatchEvent(new MouseEvent('pointerup', { bubbles: true, clientX: 142 }))) + expect(props.state.write).toHaveBeenCalledTimes(1) + expect(props.state.write).toHaveBeenCalledWith({ id: id('a'), repoId: HOME }, { fields: { 4: '2026-11-02', 5: '2026-11-13' } }) + expect(props.onOpenItem).not.toHaveBeenCalled() + }) + + it('stretches a bar by its end, and a press without a move opens the item', async () => { + const props = layoutProps({ layout: 'roadmap', date: [4, 5] }) + render(props) + const bar = rowOf('a').querySelector('[data-testid="roadmap-bar"]') as HTMLElement + const end = bar.lastElementChild as HTMLElement + pointer(end, 'pointerdown', 100) + pointer(end, 'pointermove', 112) + await act(async () => void end.dispatchEvent(new MouseEvent('pointerup', { bubbles: true, clientX: 112 }))) + expect(props.state.write).toHaveBeenCalledWith({ id: id('a'), repoId: HOME }, { fields: { 5: '2026-11-08' } }) + pointer(bar, 'pointerdown', 50) + await act(async () => void bar.dispatchEvent(new MouseEvent('pointerup', { bubbles: true, clientX: 51 }))) + expect(props.onOpenItem).toHaveBeenCalledWith(id('a')) + expect(props.state.write).toHaveBeenCalledTimes(1) + }) + + it('explains itself when the board has no date to plot', () => { + render(layoutProps({ layout: 'roadmap' }, { spec: { ...SPEC, fields: SPEC.fields.filter((f) => f.type === 'sel') } })) + expect(el.textContent).toContain('Nothing to plot yet') + }) +}) diff --git a/forge-web/components/repo/boards/board-roadmap.tsx b/forge-web/components/repo/boards/board-roadmap.tsx index 89a2b029b..f6d6b62f3 100644 --- a/forge-web/components/repo/boards/board-roadmap.tsx +++ b/forge-web/components/repo/boards/board-roadmap.tsx @@ -1,9 +1,481 @@ 'use client' -/** The roadmap layout of a board (design `docs/design/boards.md` §4.3). Skeleton: fleshed out next. */ +/** + * The roadmap layout of a board (design `docs/design/boards.md` §4.3): a timeline with one row + * per scheduled item, its bar from its start date to its target date (`view.date` = two `date` + * field ids) or across its iteration (`view.date` = one `iter` field id). Without `view.date` it + * plots the board's first iteration field, else its first two date fields. Items with no date + * are listed beside the timeline ("Unscheduled"). + * + * - **Zoom**: weeks, months or quarters (this page's choice: a view does not save it). + * - **Marks**: today's line, and the iteration bands of the plotted (or first) iteration field, + * the current one shaded. + * - **Editing**: a bar opens the item panel, where its dates are edited. Members who place cards + * may also drag a date bar's ends (or the bar, to move both dates): one card write on release. + * - **Access**: every bar is a button named by its item, dates and status; the timeline is also + * given as a plain list for screen readers. Rendered with plain DOM, no chart library. + */ +import { useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react' +import { CalendarRange, Lock } from 'lucide-react' +import { labelTextColor } from '@/lib/repo' +import { byRank, dateDays, dateOf, fieldById, groupRows, iterationAt, iterationRange, sortRows, type BoardField, type BoardItem, type BoardRow, type BoardSpec, type BoardView as SavedView } from '@/lib/rules/boards' +import { EmptyState } from '@/components/ui/states' +import { ScrollRegion } from '@/components/ui/scroll-region' +import { cn } from '@/lib/utils' +import { GroupHeading, ItemStateIcon, columnName, dayRangeText } from './board-fields' import type { BoardLayoutProps } from './layout-props' -export function BoardRoadmap(props: BoardLayoutProps): JSX.Element { - return
{props.items.length} items
+const DAY_MS = 86_400_000 + +export type Zoom = 'weeks' | 'months' | 'quarters' +export const ZOOMS: readonly { readonly key: Zoom; readonly label: string }[] = [ + { key: 'weeks', label: 'Weeks' }, + { key: 'months', label: 'Months' }, + { key: 'quarters', label: 'Quarters' }, +] +/** Pixels per day at each zoom. */ +const PX: Readonly> = { weeks: 28, months: 6, quarters: 2 } +/** Days of margin around what is plotted, and the least span shown. */ +const PAD: Readonly> = { weeks: 7, months: 21, quarters: 45 } +const MIN_SPAN: Readonly> = { weeks: 56, months: 150, quarters: 450 } +/** The label column's width. */ +const LABEL_W = 256 + +/** What a roadmap plots: one iteration field, or a start and an end date field. */ +export type RoadmapDates = { readonly kind: 'iter'; readonly field: BoardField } | { readonly kind: 'range'; readonly start: BoardField; readonly end: BoardField } + +/** The fields a view's roadmap plots (§4.3): `view.date`, else the first iteration field, else the first two date fields; null for none. */ +export function roadmapDates(spec: BoardSpec, view: SavedView): RoadmapDates | null { + const ids = view.date ?? (() => { + const iter = spec.fields.find((f) => f.type === 'iter') + if (iter !== undefined) return [iter.id] + const dates = spec.fields.filter((f) => f.type === 'date') + return dates.length >= 2 ? [(dates[0] as BoardField).id, (dates[1] as BoardField).id] : [] + })() + const fields = ids.map((id) => fieldById(spec, id)) + const [a, b] = fields + if (fields.length === 1 && a?.type === 'iter') return { kind: 'iter', field: a } + if (fields.length === 2 && a?.type === 'date' && b?.type === 'date') return { kind: 'range', start: a, end: b } + return null +} + +/** An item's bar: its first and last day (day numbers, inclusive); `single` when only one date is set. */ +export interface Bar { + readonly start: number + readonly end: number + readonly single: boolean +} + +/** Where `row`'s bar runs, or null when it has no date to plot. */ +export function barOf(row: BoardRow, dates: RoadmapDates): Bar | null { + const f = row.placement.fields + if (dates.kind === 'iter') { + const k = f[String(dates.field.id)] + const r = typeof k === 'number' ? iterationRange(dates.field, k) : null + return r === null ? null : { start: r.startMs / DAY_MS, end: r.endMs / DAY_MS - 1, single: false } + } + const s = dateDays(f[String(dates.start.id)]) + const e = dateDays(f[String(dates.end.id)]) + if (s === null && e === null) return null + if (s === null || e === null) { + const d = (s ?? e) as number + return { start: d, end: d, single: true } + } + return { start: Math.min(s, e), end: Math.max(s, e), single: false } +} + +/** A day number as `YYYY-MM-DD`. */ +const dayOf = (d: number): string => dateOf(d * DAY_MS) + +/** The day number of the first day of the month `months` after the one holding day `d`. */ +function monthStart(d: number, months = 0): number { + const [y, m] = dayOf(d).split('-').map(Number) as [number, number] + const t = y * 12 + (m - 1) + months + return dateDays(`${String(Math.floor(t / 12)).padStart(4, '0')}-${String((t % 12) + 1).padStart(2, '0')}-01`) as number +} + +/** The first day of the period (week, month, quarter) holding day `d`. */ +function periodStart(d: number, zoom: Zoom): number { + if (zoom === 'weeks') return d - ((((d + 3) % 7) + 7) % 7) + const m = monthStart(d) + if (zoom === 'months') return m + const month = Number(dayOf(m).slice(5, 7)) + return monthStart(m, -((month - 1) % 3)) +} + +/** The first day of the period after the one starting at `d`. */ +function nextPeriod(d: number, zoom: Zoom): number { + return zoom === 'weeks' ? d + 7 : monthStart(d, zoom === 'months' ? 1 : 3) +} + +/** The plotted span: whole periods covering every bar, today and the current iteration, with a margin. */ +export function timelineSpan(bars: readonly Bar[], today: number, zoom: Zoom): { readonly from: number; readonly to: number } { + let lo = today + let hi = today + for (const b of bars) { + lo = Math.min(lo, b.start) + hi = Math.max(hi, b.end) + } + lo -= PAD[zoom] + hi += PAD[zoom] + if (hi - lo < MIN_SPAN[zoom]) hi = lo + MIN_SPAN[zoom] + const from = periodStart(lo, zoom) + let to = from + while (to <= hi) to = nextPeriod(to, zoom) + return { from, to } +} + +/** The header's ticks: each period's start and label, and the coarser band above it (month or year). */ +function ticks(from: number, to: number, zoom: Zoom): { readonly major: { day: number; label: string }[]; readonly minor: { day: number; label: string }[] } { + const minor: { day: number; label: string }[] = [] + for (let d = from; d < to; d = nextPeriod(d, zoom)) { + const date = dayOf(d) + const label = + zoom === 'weeks' + ? String(Number(date.slice(8, 10))) + : zoom === 'months' + ? new Date(d * DAY_MS).toLocaleDateString(undefined, { month: 'short', timeZone: 'UTC' }) + : `Q${Math.floor((Number(date.slice(5, 7)) - 1) / 3) + 1}` + minor.push({ day: d, label }) + } + const major: { day: number; label: string }[] = [] + for (let d = zoom === 'weeks' ? monthStart(from) : dateDays(`${dayOf(from).slice(0, 4)}-01-01`) as number; d < to; ) { + const label = zoom === 'weeks' ? new Date(d * DAY_MS).toLocaleDateString(undefined, { month: 'long', year: 'numeric', timeZone: 'UTC' }) : dayOf(d).slice(0, 4) + major.push({ day: Math.max(d, from), label }) + d = zoom === 'weeks' ? monthStart(d, 1) : monthStart(d, 12) + } + return { major, minor } +} + +/** A bar's words: the item, its dates and its status (a bar's name, and the list fallback's line). */ +function barText(item: BoardItem, bar: Bar, status: string, priv: boolean): string { + const who = priv ? 'A private item' : `#${item.number} ${item.title}` + return `${who}: ${dayRangeText(dayOf(bar.start), dayOf(bar.end))}, ${status}` +} + +/** A drag in progress: which bar, which part, where it started, and the days it has moved. */ +interface Drag { + readonly item: string + readonly part: 'start' | 'end' | 'move' + readonly x: number + readonly bar: Bar + readonly delta: number + readonly moved: boolean +} + +export function BoardRoadmap({ state, spec, view, items, placements, onOpenItem }: BoardLayoutProps): JSX.Element { + const [zoom, setZoom] = useState('months') + const [drag, setDrag] = useState(null) + const dragRef = useRef(null) + dragRef.current = drag + const scrollRef = useRef(null) + const dates = roadmapDates(spec, view) + const hidden = state.items?.hidden + const today = Math.floor(state.now / DAY_MS) + const px = PX[zoom] + + const { scheduled, unscheduled } = useMemo(() => { + const rows = items.flatMap((item): BoardRow[] => { + const placement = placements.get(item.id) + return placement === undefined ? [] : [{ item, placement }] + }) + if (dates === null) return { scheduled: [] as { row: BoardRow; bar: Bar }[], unscheduled: rows } + const withBars = rows.map((row) => ({ row, bar: barOf(row, dates) })) + const on = withBars.filter((x): x is { row: BoardRow; bar: Bar } => x.bar !== null) + // A view's sort orders the rows; otherwise they run by start date. + const order = view.sort !== undefined ? sortRows(on.map((x) => x.row), view.sort, spec).map((r) => r.item.id) : null + const sorted = order !== null ? order.map((id) => on.find((x) => x.row.item.id === id) as { row: BoardRow; bar: Bar }) : [...on].sort((a, b) => a.bar.start - b.bar.start || a.bar.end - b.bar.end || byRank(a.row.placement, b.row.placement)) + return { scheduled: sorted, unscheduled: withBars.filter((x) => x.bar === null).map((x) => x.row) } + }, [items, placements, dates, view.sort, spec]) + + const groups = useMemo(() => { + if (view.group === undefined) return [{ key: 'all', group: null as string | number | null, rows: scheduled }] + const byId = new Map(scheduled.map((x) => [x.row.item.id, x])) + return groupRows( + scheduled.map((x) => x.row), + view.group, + spec, + state.now, + ) + .filter((g) => g.items.length > 0) + .map((g) => ({ key: `g:${String(g.key)}`, group: g.key, rows: g.items.map((id) => byId.get(id) as { row: BoardRow; bar: Bar }) })) + }, [scheduled, view.group, spec, state.now]) + + const span = useMemo(() => timelineSpan(scheduled.map((x) => x.bar), today, zoom), [scheduled, today, zoom]) + const width = (span.to - span.from) * px + const xOf = (day: number): number => (day - span.from) * px + const { major, minor } = useMemo(() => ticks(span.from, span.to, zoom), [span, zoom]) + + // The iteration bands: the plotted iteration field's, else the board's first. + const iterField = dates?.kind === 'iter' ? dates.field : spec.fields.find((f) => f.type === 'iter') + const bands = useMemo(() => { + if (iterField === undefined) return [] + const first = iterationAt(iterField, span.from * DAY_MS) ?? 0 + const out = [] + for (let k = first; k <= 65535; k++) { + const r = iterationRange(iterField, k) + if (r === null || r.startMs / DAY_MS >= span.to) break + if (r.endMs / DAY_MS > span.from) out.push(r) + } + return out + }, [iterField, span]) + const currentIter = iterField === undefined ? null : iterationAt(iterField, state.now) + + // Open on today, a quarter of the way in: the first time and on a zoom, never on a poll (which + // must not scroll the page under the viewer). + const todayX = useRef(0) + todayX.current = xOf(today) + useEffect(() => { + const el = scrollRef.current?.parentElement + if (el != null) el.scrollLeft = Math.max(0, todayX.current - (el.clientWidth - LABEL_W) / 4) + }, [zoom]) + + const canDrag = state.can.place && dates?.kind === 'range' + + const onPointerDown = (e: ReactPointerEvent, item: string, part: Drag['part'], bar: Bar): void => { + if (!canDrag || e.button !== 0) return + e.stopPropagation() + e.currentTarget.setPointerCapture?.(e.pointerId) + setDrag({ item, part, x: e.clientX, bar, delta: 0, moved: false }) + } + const onPointerMove = (e: ReactPointerEvent): void => { + const d = dragRef.current + if (d === null) return + const dx = e.clientX - d.x + setDrag({ ...d, delta: Math.round(dx / px), moved: d.moved || Math.abs(dx) > 4 }) + } + const onPointerUp = (row: BoardRow): void => { + const d = dragRef.current + setDrag(null) + if (d === null || dates?.kind !== 'range') return + if (!d.moved) { + onOpenItem(row.item.id) + return + } + const next = moved(d) + if (next.start === d.bar.start && next.end === d.bar.end) return + const has = (f: BoardField): boolean => row.placement.fields[String(f.id)] !== undefined + const fields: Record = {} + if (next.start !== d.bar.start || (d.part === 'start' && !has(dates.start))) fields[dates.start.id] = dayOf(next.start) + if (next.end !== d.bar.end || (d.part === 'end' && !has(dates.end))) fields[dates.end.id] = dayOf(next.end) + // a single-date bar moved keeps to its one date + if (d.bar.single && d.part === 'move') { + for (const f of [dates.start, dates.end]) if (!has(f)) delete fields[f.id] + } + void state.write({ id: row.item.id, repoId: row.item.repoId }, { fields }).catch(() => undefined) + } + + if (dates === null) { + return ( +
+ +
+ ) + } + + const rowCount = groups.reduce((n, g) => n + g.rows.length + (view.group !== undefined ? 1 : 0), 0) + return ( +
+
+

+ {dates.kind === 'iter' ? `By ${dates.field.name}` : `From ${dates.start.name} to ${dates.end.name}`} +

+
+ {ZOOMS.map((z) => ( + + ))} +
+
+ +
+
+ {/* The visual timeline; the list below says the same for screen readers. */} + +
+ {/* Header: the coarse band, the periods, the iterations. */} +
+
+ Item +
+
0 ? 60 : 42 }}> + {major.map((t) => ( + + {t.label} + + ))} + {minor.map((t) => ( + + {t.label} + + ))} + {bands.map((b) => ( + + {b.name} + + ))} + +
+
+ + {/* Body: bands, period lines and today behind the rows. */} +
+
+ {bands.map((b) => ( + + ))} + {minor.map((t) => ( + + ))} + +
+ + {scheduled.length === 0 ? ( +

+ No item has a date yet. Items get one in the item panel. +

+ ) : null} + + {groups.map((g) => ( +
+ {view.group !== undefined ? ( +
+ + {g.rows.length} +
+ ) : null} + {g.rows.map(({ row, bar }) => { + const { item, placement } = row + const priv = hidden?.has(item.id) === true + const col = spec.columns.find((c) => c.id === placement.col) + const d = drag?.item === item.id ? drag : null + const shown = d !== null ? moved(d) : bar + const left = xOf(shown.start) + const w = Math.max(px, (shown.end - shown.start + 1) * px) + const fill = col?.color + const ink = fill === undefined ? null : labelTextColor(fill) + const text = barText(item, shown, columnName(spec, placement.col), priv) + const narrow = w < 96 + return ( +
+
+ {priv ? : } + + {!priv ? #{item.number} : null} +
+
+ + {narrow && !priv ? ( + + {item.title} + + ) : null} +
+
+ ) + })} +
+ ))} + {rowCount === 0 ? null :
} +
+
+ +
+ + +
+ + {/* The timeline as a list, for screen readers. */} +
+
    + {scheduled.map(({ row, bar }) => ( +
  • {barText(row.item, bar, columnName(spec, row.placement.col), hidden?.has(row.item.id) === true)}
  • + ))} +
+
+
+ ) +} + +/** A dragged bar's days: its start, its end or both moved by the drag's days. */ +function moved(d: Drag): Bar { + const { bar, delta, part } = d + if (part === 'move') return { ...bar, start: bar.start + delta, end: bar.end + delta } + if (part === 'start') return { ...bar, start: Math.min(bar.start + delta, bar.end) } + return { ...bar, end: Math.max(bar.end + delta, bar.start) } } diff --git a/forge-web/components/repo/boards/board-table.test.tsx b/forge-web/components/repo/boards/board-table.test.tsx new file mode 100644 index 000000000..61c44affb --- /dev/null +++ b/forge-web/components/repo/boards/board-table.test.tsx @@ -0,0 +1,184 @@ +// @vitest-environment jsdom +/** + * The board's table layout (design `docs/design/boards.md` §4.2): its columns, sort requests, + * groups with totals, in-place edits (one card write each), the keyboard grid, and what a + * visitor gets. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/components/author', () => ({ Author: ({ identityId }: { identityId: string }) => {identityId.slice(0, 4)} })) + +import { BoardTable, nextSort, tableColumns } from './board-table' +import { HOME, ITEMS, SPEC, hookState, id, layoutProps } from './layout-fixture' +import type { BoardLayoutProps } from './layout-props' + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let root: Root +let el: HTMLDivElement +beforeEach(() => { + el = document.createElement('div') + document.body.append(el) + root = createRoot(el) +}) +afterEach(() => { + act(() => root.unmount()) + el.remove() +}) + +const render = (props: BoardLayoutProps): void => act(() => root.render()) +const headers = (): string[] => [...el.querySelectorAll('thead th')].map((th) => th.textContent?.trim() ?? '') +const row = (c: string): HTMLTableRowElement => el.querySelector(`tr[data-item="${id(c)}"]`) as HTMLTableRowElement +const cell = (c: string, i: number): HTMLTableCellElement => row(c).querySelectorAll('td')[i] as HTMLTableCellElement +const key = (target: Element, k: string, init: KeyboardEventInit = {}): void => act(() => void target.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true, ...init }))) +const typeInto = (input: HTMLInputElement, value: string): void => { + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set! + act(() => { + setter.call(input, value) + input.dispatchEvent(new Event('input', { bubbles: true })) + }) +} + +describe('tableColumns and nextSort', () => { + it('defaults to Title, Status, Assignees, Labels and every field; Title always leads', () => { + expect(tableColumns(SPEC, { id: 1, name: 'T', layout: 'table', q: '' })).toEqual(['title', 'status', 'assignees', 'labels', 'f1', 'f2', 'f3', 'f4', 'f5']) + expect(tableColumns(SPEC, { id: 1, name: 'T', layout: 'table', q: '', cols: ['status', 'title', 'f2'] })).toEqual(['title', 'status', 'f2']) + expect(tableColumns(SPEC, { id: 1, name: 'T', layout: 'table', q: '', cols: ['number'] })).toEqual(['title', 'number']) + }) + it('cycles ascending, descending, board order', () => { + expect(nextSort(undefined, 'title')).toBe('title') + expect(nextSort('title', 'title')).toBe('-title') + expect(nextSort('-title', 'title')).toBeUndefined() + expect(nextSort('-number', 'title')).toBe('title') + }) +}) + +describe('BoardTable', () => { + it('shows a row per item with the view columns, a private item as such', () => { + render(layoutProps({ cols: ['title', 'status', 'f1', 'f2', 'labels'] })) + expect(headers()).toEqual(['Title', 'Status', 'Priority', 'Estimate', 'Labels']) + expect(el.querySelectorAll('tbody tr[data-item]')).toHaveLength(5) + expect(cell('a', 0).textContent).toContain('Write the parser') + expect(cell('a', 0).textContent).toContain('#1') + expect(cell('a', 1).textContent).toBe('Todo') + expect(cell('a', 2).textContent).toBe('P0') + expect(cell('a', 3).textContent).toBe('3') + expect(cell('a', 4).textContent).toBe('bug') + expect(cell('d', 1).textContent).toBe('Done') + // another repo's item this reader cannot open + expect(cell('e', 0).textContent).toContain('A private item') + expect(cell('e', 0).textContent).not.toContain('Secret') + }) + + it('sorts by the view and asks the shell for a header sort', () => { + const props = layoutProps({ cols: ['title', 'f2'], sort: '-f2' }) + render(props) + const order = [...el.querySelectorAll('tbody tr[data-item]')].map((r) => r.getAttribute('data-item')) + // estimates 5, 3, 2; the two without one last + expect(order.slice(0, 3)).toEqual([id('b'), id('a'), id('c')]) + const th = el.querySelectorAll('thead th')[1] as HTMLElement + expect(th.getAttribute('aria-sort')).toBe('descending') + act(() => (el.querySelector('[data-testid="sort-f2"]') as HTMLButtonElement).click()) + expect(props.onViewChange).toHaveBeenCalledWith({ sort: undefined }) + act(() => (el.querySelector('[data-testid="sort-title"]') as HTMLButtonElement).click()) + expect(props.onViewChange).toHaveBeenLastCalledWith({ sort: 'title' }) + }) + + it('groups into sections with counts, WIP over its limit, and the number field sum', () => { + render(layoutProps({ group: 'status', cols: ['title', 'f2'] })) + const sections = [...el.querySelectorAll('[data-testid="board-table-section"]')] + expect(sections.map((s) => s.querySelector('th')?.textContent)).toEqual([ + expect.stringContaining('Todo'), + expect.stringContaining('In progress'), + expect.stringContaining('Done'), + ]) + const progress = sections[1] as HTMLElement + expect(progress.querySelector('[data-testid="section-count"]')?.textContent).toContain('2 / 1') + expect(progress.querySelector('[data-testid="section-count"]')?.className).toContain('danger') + expect(progress.querySelector('[data-testid="section-sum"]')?.textContent).toBe('Estimate: 7') + expect(sections[0]?.querySelector('[data-testid="section-sum"]')?.textContent).toBe('Estimate: 3') + }) + + it('edits Status in place with one card write of its column', async () => { + const props = layoutProps({ cols: ['title', 'status'] }) + render(props) + act(() => cell('a', 1).click()) + const select = cell('a', 1).querySelector('select') as HTMLSelectElement + expect(select).not.toBeNull() + expect(document.activeElement).toBe(select) + await act(async () => { + select.value = '2' + select.dispatchEvent(new Event('change', { bubbles: true })) + }) + expect(props.state.write).toHaveBeenCalledTimes(1) + expect(props.state.write).toHaveBeenCalledWith({ id: id('a'), repoId: HOME }, { col: 2 }, undefined) + expect(cell('a', 1).querySelector('select')).toBeNull() + }) + + it('moves through the grid with the keyboard, edits with Enter, cancels with Escape', async () => { + const props = layoutProps({ cols: ['title', 'status', 'f2'] }) + render(props) + const first = cell('a', 0) + expect(first.tabIndex).toBe(0) + expect(cell('a', 1).tabIndex).toBe(-1) + act(() => first.focus()) + key(first, 'ArrowRight') + key(document.activeElement as Element, 'ArrowRight') + expect(document.activeElement).toBe(cell('a', 2)) + expect(cell('a', 2).tabIndex).toBe(0) + expect(first.tabIndex).toBe(-1) + // Escape leaves the value alone + key(cell('a', 2), 'Enter') + let input = cell('a', 2).querySelector('input') as HTMLInputElement + typeInto(input, '9') + key(input, 'Escape') + expect(props.state.write).not.toHaveBeenCalled() + expect(document.activeElement).toBe(cell('a', 2)) + // Enter writes it + key(cell('a', 2), 'Enter') + input = cell('a', 2).querySelector('input') as HTMLInputElement + typeInto(input, '8') + await act(async () => void input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))) + expect(props.state.write).toHaveBeenCalledWith({ id: id('a'), repoId: HOME }, { fields: { 2: 8 } }, undefined) + // a bad number is refused before any write + key(cell('a', 2), 'Enter') + input = cell('a', 2).querySelector('input') as HTMLInputElement + typeInto(input, 'lots') + key(input, 'Enter') + expect(cell('a', 2).querySelector('[role="alert"]')?.textContent).toBe('Enter a number.') + expect(props.state.write).toHaveBeenCalledTimes(1) + // down a row, and Enter on the title opens the item + key(input, 'Escape') + key(cell('a', 2), 'ArrowDown') + key(document.activeElement as Element, 'Home') + key(document.activeElement as Element, 'Enter') + expect(props.onOpenItem).toHaveBeenCalledWith(id('b')) + }) + + it('opens the item from a row; a visitor edits nothing', () => { + const props = layoutProps({ cols: ['title', 'status'] }, { state: hookState({ can: { place: false, edit: false } }) }) + render(props) + act(() => cell('b', 1).click()) + expect(cell('b', 1).querySelector('select')).toBeNull() + expect(props.onOpenItem).toHaveBeenCalledWith(id('b')) + expect(cell('b', 1).getAttribute('aria-readonly')).toBe('true') + }) + + it('marks archived and pending rows', () => { + const base = layoutProps({ cols: ['title'] }) + const placements = new Map(base.placements) + placements.set(id('d'), { ...(placements.get(id('d')) as NonNullable>), archived: 'auto' }) + render({ ...base, placements, items: ITEMS, state: hookState({ pending: new Set([id('b')]) }) }) + expect(cell('d', 0).querySelector('[data-testid="archived-badge"]')).not.toBeNull() + expect(row('b').getAttribute('aria-busy')).toBe('true') + expect(cell('b', 0).textContent).toContain('Saving') + }) + + it('says so when nothing matches', () => { + render(layoutProps({}, { items: [] })) + expect(el.textContent).toContain('No items match') + }) +}) diff --git a/forge-web/components/repo/boards/board-table.tsx b/forge-web/components/repo/boards/board-table.tsx index 70c1e835c..630a3b668 100644 --- a/forge-web/components/repo/boards/board-table.tsx +++ b/forge-web/components/repo/boards/board-table.tsx @@ -1,9 +1,412 @@ 'use client' -/** The table layout of a board (design `docs/design/boards.md` §4.2). Skeleton: fleshed out next. */ +/** + * The table layout of a board (design `docs/design/boards.md` §4.2): one row per shown item, + * one column per view key (`view.cols`, §2.7; without them Title, Status, Assignees, Labels and + * every custom field), as GitHub's project table. + * + * - **Sort**: a header click asks the shell for `sort` (ascending, then descending, then the + * board order) through `onViewChange`; rows are ordered by the rules' `sortRows`. + * - **Groups**: `view.group` makes sections (`groupRows`), each with its count, its WIP limit + * (Status) and the sum of the view's first number field (`sumFieldOf`, `totals`, §4.5). + * - **Editing**: members who place cards (`state.can.place`) edit Status and the custom fields in + * place; each change is one card write (`state.write`, Status writes `col`), shown at once and + * taken back by the hook if refused. A private home's card for another repository's item asks + * first (§3.3). + * - **Keyboard**: the body is a grid with one tab stop (roving tabindex): arrows, Home / End, + * Ctrl+Home / Ctrl+End and Page Up / Down move; Enter edits an editable cell or opens the item + * from any other; Escape cancels an edit. + * + * Archived items (a view with `is:archived`), items with a write in flight and private items + * ("a private item", `BoardItemSet.hidden`) are marked on their row. Not virtualized: a board + * reads at most a few hundred open items per source, which a plain table renders. + */ +import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react' +import { Archive, ArrowDown, ArrowUp, ArrowUpDown, Loader2, Lock, Table2 } from 'lucide-react' +import { crossRepoCardNeedsConfirm, type CardPatch, type LabelDef } from '@/lib/repo' +import { groupRows, sortRows, sumFieldOf, totals, type BoardItem, type BoardRow, type BoardSpec, type BoardView as SavedView, type FieldValue } from '@/lib/rules/boards' +import { AssigneeAvatars, LabelChip } from '@/components/repo/issue-bits' +import { Author } from '@/components/author' +import { EmptyState } from '@/components/ui/states' +import { ScrollRegion } from '@/components/ui/scroll-region' +import { useConfirmAction } from '@/components/ui/confirm-action' +import { cn, shortId } from '@/lib/utils' +import { ColorDot, FieldInput, GroupHeading, ItemStateIcon, StatusSelect, dayText, fieldValueText, viewKeyLabel } from './board-fields' import type { BoardLayoutProps } from './layout-props' -export function BoardTable(props: BoardLayoutProps): JSX.Element { - return
{props.items.length} items
+/** The table's columns: the view's `cols` with Title first, or Title, Status, Assignees, Labels and every custom field. */ +export function tableColumns(spec: BoardSpec, view: SavedView): string[] { + const cols = view.cols ?? ['title', 'status', 'assignees', 'labels', ...spec.fields.map((f) => `f${f.id}`)] + return ['title', ...cols.filter((c) => c !== 'title')] +} + +/** The `sort` a header click asks for: ascending, then descending, then none (the board order). */ +export function nextSort(current: string | undefined, key: string): string | undefined { + if (current === key) return `-${key}` + if (current === `-${key}`) return undefined + return key +} + +/** The custom field a view key names, or undefined. */ +function fieldOf(spec: BoardSpec, key: string) { + const m = /^f(\d+)$/.exec(key) + return m ? spec.fields.find((f) => f.id === Number(m[1])) : undefined +} + +/** Whether a column's cells are edited in place (Status and the custom fields). */ +function editableKey(spec: BoardSpec, key: string): boolean { + return key === 'status' || fieldOf(spec, key) !== undefined +} + +const STATE_WORD = { open: 'Open', closed: 'Closed', merged: 'Merged' } as const + +/** A number as both clients print it (§2.7). */ +function numText(n: number): string { + return String(n) +} + +interface Section { + readonly key: string + readonly group: string | number | null + readonly rows: readonly BoardRow[] +} + +export function BoardTable({ state, spec, view, items, placements, onOpenItem, onViewChange, home, labels }: BoardLayoutProps): JSX.Element { + const cols = useMemo(() => tableColumns(spec, view), [spec, view]) + const hidden = state.items?.hidden + const sumField = sumFieldOf(spec, view) + const sumName = sumField === null ? null : (spec.fields.find((f) => f.id === sumField)?.name ?? null) + const multiRepo = useMemo(() => new Set(items.map((i) => i.repoId)).size > 1, [items]) + const sections: Section[] = useMemo(() => { + const rows = items.flatMap((item): BoardRow[] => { + const placement = placements.get(item.id) + return placement === undefined ? [] : [{ item, placement }] + }) + const sorted = sortRows(rows, view.sort, spec) + if (view.group === undefined) return [{ key: 'all', group: null, rows: sorted }] + const byId = new Map(sorted.map((r) => [r.item.id, r])) + return groupRows(sorted, view.group, spec, state.now).map((g) => ({ key: `g:${String(g.key)}`, group: g.key, rows: g.items.map((id) => byId.get(id) as BoardRow) })) + }, [items, placements, view.sort, view.group, spec, state.now]) + // The grid's rows in order (an item in two groups, by assignee or label, is a row in each). + const flat = useMemo(() => sections.flatMap((s) => s.rows.map((r) => ({ section: s.key, row: r }))), [sections]) + + const [active, setActive] = useState({ r: 0, c: 0 }) + const [editing, setEditing] = useState<{ r: number; c: number } | null>(null) + const refocus = useRef(false) + const gridRef = useRef(null) + const [confirm, confirmElement] = useConfirmAction() + const r = Math.min(active.r, Math.max(0, flat.length - 1)) + const c = Math.min(active.c, cols.length - 1) + + const cellEl = (row: number, col: number): HTMLElement | null => gridRef.current?.querySelector(`[data-cell="${row}:${col}"]`) ?? null + useEffect(() => { + if (!refocus.current) return + refocus.current = false + cellEl(r, c)?.focus() + }) + + const move = (row: number, col: number): void => { + const nr = Math.max(0, Math.min(flat.length - 1, row)) + const nc = Math.max(0, Math.min(cols.length - 1, col)) + setActive({ r: nr, c: nc }) + cellEl(nr, nc)?.focus() + } + + const canEdit = (item: BoardItem, key: string): boolean => state.can.place && hidden?.has(item.id) !== true && editableKey(spec, key) + + const write = async (item: BoardItem, patch: CardPatch): Promise => { + const board = state.board + let confirmCrossRepo = false + const homeRepo = home ?? (board === null ? null : { repoId: board.repoId, visibility: board.sealed ? 'private' : 'public' }) + if (homeRepo !== null && crossRepoCardNeedsConfirm(homeRepo, item.repoId)) { + const ok = await confirm({ + title: 'Place an item of another repo', + body: 'This board is in a private repo. Placing this item on it shows everyone that this repo tracks it.', + confirmLabel: 'Place it', + tone: 'primary', + }) + if (!ok) return + confirmCrossRepo = true + } + // A refusal is taken back and reported by the board (`state.refusal`). + await state.write({ id: item.id, repoId: item.repoId }, patch, confirmCrossRepo ? { confirmCrossRepo } : undefined).catch(() => undefined) + } + + const endEdit = (): void => { + refocus.current = true + setEditing(null) + } + + const commit = (item: BoardItem, key: string, value: FieldValue | null | number): void => { + endEdit() + if (key === 'status') void write(item, { col: value as number }) + else { + const field = fieldOf(spec, key) + if (field !== undefined) void write(item, { fields: { [field.id]: value } }) + } + } + + const onKeyDown = (e: KeyboardEvent): void => { + if (editing !== null) return + const target = e.target as HTMLElement + if (target.dataset['cell'] === undefined) return + const item = flat[r]?.row.item + switch (e.key) { + case 'ArrowDown': + move(r + 1, c) + break + case 'ArrowUp': + move(r - 1, c) + break + case 'ArrowRight': + move(r, c + 1) + break + case 'ArrowLeft': + move(r, c - 1) + break + case 'Home': + move(e.ctrlKey || e.metaKey ? 0 : r, 0) + break + case 'End': + move(e.ctrlKey || e.metaKey ? flat.length - 1 : r, cols.length - 1) + break + case 'PageDown': + move(r + 10, c) + break + case 'PageUp': + move(r - 10, c) + break + case 'Enter': + case 'F2': { + const key = cols[c] as string + if (item !== undefined && canEdit(item, key)) setEditing({ r, c }) + else if (item !== undefined && e.key === 'Enter') onOpenItem(item.id) + break + } + default: + return + } + e.preventDefault() + } + + const sortKey = view.sort?.replace(/^-/, '') + const desc = view.sort?.startsWith('-') === true + + if (flat.length === 0) { + return + } + + let rowIndex = -1 + return ( +
+ + + + + {cols.map((key, ci) => { + const sorted = sortKey === key + const label = viewKeyLabel(spec, key) + const sortable = key !== 'labels' && key !== 'assignees' && key !== 'state' + const Icon = sorted ? (desc ? ArrowDown : ArrowUp) : ArrowUpDown + return ( + + ) + })} + + + {sections.map((s) => { + const t = totals(s.rows, sumField) + const wip = view.group === 'status' ? (spec.columns.find((col) => col.id === s.group)?.wip ?? null) : null + const over = wip !== null && t.count > wip + return ( + + {view.group !== undefined ? ( + + + + ) : null} + {s.rows.map(({ item, placement }) => { + rowIndex++ + const ri = rowIndex + const priv = hidden?.has(item.id) === true + const pending = state.pending.has(item.id) + return ( + + {cols.map((key, ci) => { + const isActive = ri === r && ci === c + const isEditing = editing !== null && editing.r === ri && editing.c === ci + const editable = canEdit(item, key) + return ( + + ) + })} + + ) + })} + + ) + })} +
+ {sortable && onViewChange !== undefined ? ( + + ) : ( + label + )} +
+ + + + {wip !== null ? `${t.count} / ${wip}` : t.count} + {over ? (over its limit) : null} + + {t.sum !== null && sumName !== null ? ( + + {sumName}: {numText(t.sum)} + + ) : null} + +
{ + if (!isActive) setActive({ r: ri, c: ci }) + }} + onClick={() => { + setActive({ r: ri, c: ci }) + if (editable) setEditing({ r: ri, c: ci }) + else onOpenItem(item.id) + }} + className={cn( + 'h-9 max-w-[20rem] cursor-pointer border-b border-anvil-100 px-3 align-middle outline-none group-hover/row:bg-anvil-50 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-offset-0 focus-visible:ring-focus dark:border-anvil-850 dark:group-hover/row:bg-anvil-900', + ci === 0 && 'sticky left-0 z-10 border-r border-r-anvil-200 bg-white dark:border-r-anvil-800 dark:bg-anvil-950', + isEditing && 'px-1.5', + )} + > + {isEditing ? ( + commit(item, key, v)} onCancel={endEdit} /> + ) : ( + + )} +
+
+ {confirmElement} +
+ ) +} + +/** The editor of one cell: the Status select, or the field's input. */ +function EditCell({ spec, item, keyName, value, now, onCommit, onCancel }: { spec: BoardSpec; item: BoardItem; keyName: string; value: FieldValue | number | undefined; now: number; onCommit: (v: FieldValue | null) => void; onCancel: () => void }): JSX.Element | null { + const label = `${viewKeyLabel(spec, keyName)} of #${item.number}` + if (keyName === 'status') return + const field = fieldOf(spec, keyName) + if (field === undefined) return null + return +} + +/** One cell as read. */ +function Cell({ spec, item, keyName, placement, priv, pending, multiRepo, labels }: { spec: BoardSpec; item: BoardItem; keyName: string; placement: BoardRow['placement']; priv: boolean; pending: boolean; multiRepo: boolean; labels: ReadonlyMap | undefined }): JSX.Element | null { + const muted = 'text-anvil-500 dark:text-anvil-400' + switch (keyName) { + case 'title': + return ( + + {priv ? : } + + {priv ? 'A private item' : item.title} + + {!priv ? ( + + {multiRepo && item.repo !== undefined ? `${item.repo}#${item.number}` : `#${item.number}`} + + ) : null} + {placement.archived !== null ? ( + + Archived + + ) : null} + {pending ? ( + <> + + Saving + + ) : null} + + ) + case 'number': + return #{item.number} + case 'repo': + return {item.repo ?? shortId(item.repoId)} + case 'state': + return {priv ? '' : STATE_WORD[item.state]} + case 'author': + return priv || item.author === '' ? null : + case 'assignees': + return + case 'labels': + return ( + + {item.labels.map((l) => ( + + ))} + + ) + case 'milestone': + return {item.milestone ?? ''} + case 'created': + return {priv ? '' : dayText(new Date(item.createdAt).toISOString().slice(0, 10))} + case 'status': { + const col = spec.columns.find((x) => x.id === placement.col) + return ( + + + {col?.name ?? 'No status'} + + ) + } + default: { + const field = fieldOf(spec, keyName) + if (field === undefined) return null + const v = placement.fields[String(field.id)] + const text = fieldValueText(field, v) + if (field.type === 'sel' && v !== undefined) { + const opt = field.options?.find((o) => o.id === v) + return ( + + + {text} + + ) + } + return {text} + } + } } diff --git a/forge-web/components/repo/boards/layout-fixture.ts b/forge-web/components/repo/boards/layout-fixture.ts new file mode 100644 index 000000000..d5cf912f7 --- /dev/null +++ b/forge-web/components/repo/boards/layout-fixture.ts @@ -0,0 +1,145 @@ +// copy-lint-ignore-file: a test fixture, never shown to anyone +/** + * A board for the layout tests (`board-table.test.tsx`, `board-roadmap.test.tsx`): the + * new-board template with colours and WIP limits, five items folded at a fixed time, and a stand-in + * for `useBoard`'s state whose writes are recorded. + */ + +import { vi } from 'vitest' + +import type { BoardHookState } from '@/hooks/use-board' +import type { BoardCard, BoardView } from '@/lib/repo' +import { dateDays, defaultSpec, foldBoard, type BoardItem, type BoardSpec, type BoardView as SavedView, type Placement } from '@/lib/rules/boards' +import type { BoardLayoutProps } from './layout-props' + +export const HOME = 'Home1111111111111111111111111111111111111111' +export const OTHER_REPO = 'Repo2222222222222222222222222222222222222222' +export const ME = 'MeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMe' +/** 2026-10-27 12:00 UTC (a Tuesday): Iteration 1 runs from Monday 2026-10-26. */ +export const NOW = Date.UTC(2026, 9, 27, 12) +const DAY = 86_400_000 + +const base = defaultSpec(HOME, NOW) +export const SPEC: BoardSpec = { + ...base, + columns: [ + { id: 1, name: 'Todo', color: '#1d76db' }, + { id: 2, name: 'In progress', color: '#fbca04', wip: 1 }, + { id: 3, name: 'Done', color: '#0e8a16' }, + ], + fields: [...base.fields, { id: 4, name: 'Start', type: 'date' }, { id: 5, name: 'Target', type: 'date' }], +} + +/** Item ids are 44 base58 characters. */ +export const id = (c: string): string => c.repeat(44).slice(0, 44) + +const item = (c: string, n: number, extra: Partial = {}): BoardItem => ({ + id: id(c), + number: n, + repoId: HOME, + repo: 'project', + kind: 'issue', + state: 'open', + createdAt: NOW - (10 - n) * DAY, + closedAt: null, + title: `Item ${n}`, + labels: [], + assignees: [], + milestone: null, + author: ME, + ...extra, +}) + +export const ITEMS: BoardItem[] = [ + item('a', 1, { title: 'Write the parser', labels: ['bug'] }), + item('b', 2, { title: 'Ship the table', assignees: [ME] }), + item('c', 3, { title: 'Fix the roadmap', kind: 'pr' }), + item('d', 4, { title: 'Old done work', state: 'closed', closedAt: NOW - DAY }), + item('e', 5, { title: 'Secret', repoId: OTHER_REPO }), +] + +const card = (c: string, col: number, f: Record = {}, at = NOW - DAY): BoardCard => ({ + id: id(c.toUpperCase()), + ownerId: ME, + updatedAt: at, + item: id(c), + col, + rank: null, + f: Object.keys(f).length === 0 ? null : JSON.stringify(f), + state: 0, +}) + +export const CARDS: BoardCard[] = [ + card('a', 1, { 1: 1, 2: 3, 3: 0, 4: '2026-10-26', 5: '2026-11-06' }), + card('b', 2, { 1: 2, 2: 5, 3: 1 }), + card('c', 2, { 2: 2, 4: '2026-11-02' }), + card('e', 1), +] + +export function fold(spec: BoardSpec = SPEC, cards: readonly BoardCard[] = CARDS): Map { + return new Map(foldBoard({ spec, home: HOME, items: ITEMS, cards, now: NOW }).items.map((p) => [p.id, p])) +} + +const BOARD: BoardView = { + key: 7, + repoId: HOME, + state: 'open', + name: 'Roadmap', + spec: SPEC, + specError: null, + sealed: false, + newest: { id: 'b1', ownerId: ME, updatedAt: NOW - DAY }, + revisions: [{ id: 'b1', ownerId: ME, updatedAt: NOW - DAY }], +} + +/** A stand-in for `useBoard`'s state: `write` records its calls and resolves. */ +export function hookState(over: Partial = {}): BoardHookState { + const done = vi.fn(async () => ({ written: [], failed: null, skipped: [] })) + return { + board: BOARD, + cards: CARDS, + items: { items: ITEMS, hidden: new Set([id('e')]), missing: new Set(), partial: false, hasOlderClosed: false, walks: new Map() }, + fold: null, + now: NOW, + loading: false, + error: null, + notFound: false, + role: 'maintainer', + can: { place: true, edit: true }, + pending: new Set(), + refusal: null, + dismissRefusal: vi.fn(), + refresh: vi.fn(), + loadOlderClosed: vi.fn(async () => undefined), + write: vi.fn(async () => ({}) as never), + move: vi.fn(async () => ({}) as never), + add: done, + archive: done, + unarchive: done, + remove: done, + rerank: done, + moveOpenToNextIteration: done, + quickAdd: vi.fn(async () => ({}) as never), + save: vi.fn(async () => ({}) as never), + setState: vi.fn(async () => ({}) as never), + ...over, + } +} + +/** Layout props over the fixture: every item on the board, the view given. */ +export function layoutProps(view: Partial = {}, over: Partial = {}): BoardLayoutProps { + const placements = fold() + return { + state: hookState(), + spec: SPEC, + view: { id: 1, name: 'View', layout: 'table', q: '', ...view }, + items: ITEMS.filter((i) => placements.get(i.id)?.on === true && placements.get(i.id)?.archived === null), + placements, + onOpenItem: vi.fn(), + onViewChange: vi.fn(), + ...over, + } +} + +/** A day number of `YYYY-MM-DD`. */ +export const dayNo = (s: string): number => dateDays(s) as number diff --git a/forge-web/components/repo/boards/layout-props.ts b/forge-web/components/repo/boards/layout-props.ts index 6c50a20dd..021d24159 100644 --- a/forge-web/components/repo/boards/layout-props.ts +++ b/forge-web/components/repo/boards/layout-props.ts @@ -6,6 +6,8 @@ */ import type { BoardHookState } from '@/hooks/use-board' +import type { RepoAddress } from '@/hooks/use-query-param' +import type { LabelDef, RepoRef } from '@/lib/repo' import type { BoardItem, BoardSpec, BoardView as SavedView, Placement } from '@/lib/rules/boards' export interface BoardLayoutProps { @@ -27,4 +29,13 @@ export interface BoardLayoutProps { * controls that would change the view are read-only. */ onViewChange?(change: Partial): void + /** + * The board's home repository (as the page holds it, with its session when private): quick add + * creates issues and resolves `#12` here. Absent: the layout offers no quick add. + */ + readonly home?: RepoRef + /** The page's repo address, for links to an item's own page (`repoHref`). */ + readonly addr?: RepoAddress + /** The home repository's label definitions by name (chip colours); absent or unknown: the neutral chip. */ + readonly labels?: ReadonlyMap } From 4dbc82ef9140a77cb0a6d4b149dfbf6649ad5bce Mon Sep 17 00:00:00 2001 From: pasta Date: Tue, 27 Oct 2026 21:40:56 +0000 Subject: [PATCH 06/26] feat(web): boards list, settings and issue sidebar - /repo/boards: open and closed boards (name, description, column count, last change) and New board for maintainers and writers, with four templates (Kanban, Sprint board, Bug triage, Empty) priced before signing; the new board opens - /repo/board/settings: the definition as a draft saved in one priced write: columns (colour, WIP, drag or up/down reorder, delete, Default and Done), fields (select options with colours, iteration cadence with a preview), sources (owner's repos or any owner/name, filter checked as typed), auto-archive, views, close/reopen/delete; precise name problems and a 4096-byte size meter; deleting a field cleans the views that point at it; read-only for others - issue and PR sidebar Boards section (boards.md 5.6): status and fields per board, Add to board; reads only once scrolled into view - a top-level Boards tab beside Pull requests on networks with forge-meta, as GitHub places Projects; page titles Co-Authored-By: Claude Opus 5.5 --- forge-web/app/repo/board/settings/client.tsx | 15 + forge-web/app/repo/board/settings/page.tsx | 11 + forge-web/app/repo/boards/client.tsx | 14 + forge-web/app/repo/boards/page.tsx | 11 + .../repo/boards/board-settings-model.test.ts | 100 ++ .../repo/boards/board-settings-model.ts | 127 +++ .../repo/boards/board-settings.test.tsx | 179 ++++ .../components/repo/boards/board-settings.tsx | 857 ++++++++++++++++++ .../components/repo/boards/board-templates.ts | 109 +++ .../repo/boards/boards-list.test.tsx | 127 +++ .../components/repo/boards/boards-list.tsx | 243 +++++ .../repo/boards/item-boards.test.tsx | 138 +++ .../components/repo/boards/item-boards.tsx | 227 +++++ forge-web/components/repo/issue-content.tsx | 7 + forge-web/components/repo/pull-content.tsx | 7 + forge-web/components/repo/repo-header.test.ts | 13 +- forge-web/components/repo/repo-header.tsx | 18 +- .../components/repo/repo-shell-header.tsx | 7 +- forge-web/lib/page-title.ts | 4 + 19 files changed, 2206 insertions(+), 8 deletions(-) create mode 100644 forge-web/app/repo/board/settings/client.tsx create mode 100644 forge-web/app/repo/board/settings/page.tsx create mode 100644 forge-web/app/repo/boards/client.tsx create mode 100644 forge-web/app/repo/boards/page.tsx create mode 100644 forge-web/components/repo/boards/board-settings-model.test.ts create mode 100644 forge-web/components/repo/boards/board-settings-model.ts create mode 100644 forge-web/components/repo/boards/board-settings.test.tsx create mode 100644 forge-web/components/repo/boards/board-settings.tsx create mode 100644 forge-web/components/repo/boards/board-templates.ts create mode 100644 forge-web/components/repo/boards/boards-list.test.tsx create mode 100644 forge-web/components/repo/boards/boards-list.tsx create mode 100644 forge-web/components/repo/boards/item-boards.test.tsx create mode 100644 forge-web/components/repo/boards/item-boards.tsx diff --git a/forge-web/app/repo/board/settings/client.tsx b/forge-web/app/repo/board/settings/client.tsx new file mode 100644 index 000000000..b44ed510b --- /dev/null +++ b/forge-web/app/repo/board/settings/client.tsx @@ -0,0 +1,15 @@ +'use client' + +import { RepoScaffold } from '@/components/repo/repo-scaffold' +import { BoardSettings } from '@/components/repo/boards/board-settings' +import { useParam, useRepoAddress } from '@/hooks/use-query-param' + +export function BoardSettingsClient(): JSX.Element { + const addr = useRepoAddress() + const key = Number(useParam('b')) + return ( + + {(home) => } + + ) +} diff --git a/forge-web/app/repo/board/settings/page.tsx b/forge-web/app/repo/board/settings/page.tsx new file mode 100644 index 000000000..9f7a86147 --- /dev/null +++ b/forge-web/app/repo/board/settings/page.tsx @@ -0,0 +1,11 @@ +import { QueryPage } from '@/components/route-loading' +import { BoardSettingsClient } from './client' + +/** `/repo/board/settings?owner=&name=&b=` — a board's settings: columns, fields, sources, views, close and delete (`docs/design/boards.md`). */ +export default function BoardSettingsPage(): JSX.Element { + return ( + + + + ) +} diff --git a/forge-web/app/repo/boards/client.tsx b/forge-web/app/repo/boards/client.tsx new file mode 100644 index 000000000..0d7418944 --- /dev/null +++ b/forge-web/app/repo/boards/client.tsx @@ -0,0 +1,14 @@ +'use client' + +import { RepoScaffold } from '@/components/repo/repo-scaffold' +import { BoardsList } from '@/components/repo/boards/boards-list' +import { useRepoAddress } from '@/hooks/use-query-param' + +export function BoardsClient(): JSX.Element { + const addr = useRepoAddress() + return ( + + {(home) => } + + ) +} diff --git a/forge-web/app/repo/boards/page.tsx b/forge-web/app/repo/boards/page.tsx new file mode 100644 index 000000000..b8cba5f4f --- /dev/null +++ b/forge-web/app/repo/boards/page.tsx @@ -0,0 +1,11 @@ +import { QueryPage } from '@/components/route-loading' +import { BoardsClient } from './client' + +/** `/repo/boards?owner=&name=` — the repo's boards: open / closed, and New board for maintainers and writers (`docs/design/boards.md`). */ +export default function BoardsPage(): JSX.Element { + return ( + + + + ) +} diff --git a/forge-web/components/repo/boards/board-settings-model.test.ts b/forge-web/components/repo/boards/board-settings-model.test.ts new file mode 100644 index 000000000..1856dfc61 --- /dev/null +++ b/forge-web/components/repo/boards/board-settings-model.test.ts @@ -0,0 +1,100 @@ +/** + * The board settings editor's pure half and the new-board templates (design + * `docs/design/boards.md` §2.7, §8): ids, name checks, deleting what views point at, the size, + * and that every template is a definition the rules accept. + */ + +import { describe, expect, it } from 'vitest' + +import { defaultSpec, parseSpec, serializeSpec, SPEC_MAX_BYTES, type BoardSpec } from '@/lib/rules/boards' +import { BOARD_TEMPLATES, boardTemplate } from './board-templates' +import { cleanView, moved, nameProblem, nextId, sameSpec, specBytes, trimNames, withoutColumn, withoutField } from './board-settings-model' + +const HOME = 'Home1111111111111111111111111111111111111111' +const NOW = Date.UTC(2026, 9, 27, 12) +const SPEC = defaultSpec(HOME, NOW) + +describe('board templates', () => { + it.each(BOARD_TEMPLATES.map((t) => [t.key, t] as const))('%s is a definition the rules write and read back', (_key, t) => { + const spec = t.spec(HOME, NOW) + const out = serializeSpec(spec) + expect('json' in out ? parseSpec(out.json) : out).toEqual({ spec }) + }) + it('Kanban is the rules template; Bug triage sources issues labelled bug; Empty sources nothing', () => { + expect(boardTemplate('kanban').spec(HOME, NOW)).toEqual(defaultSpec(HOME, NOW)) + expect(boardTemplate('triage').spec(HOME, NOW).sources).toEqual([{ r: HOME, k: 'i', q: 'label:bug' }]) + expect(boardTemplate('sprint').spec(HOME, NOW).columns.map((c) => c.name)).toEqual(['Backlog', 'Todo', 'In progress', 'In review', 'Done']) + expect(boardTemplate('sprint').spec(HOME, NOW).fields.map((f) => f.type)).toEqual(['iter', 'num']) + const empty = boardTemplate('empty').spec(HOME, NOW) + expect(empty.columns).toHaveLength(1) + expect(empty.sources).toEqual([]) + expect(boardTemplate('nonsense').key).toBe('kanban') + }) +}) + +describe('nextId and moved', () => { + it('takes one past the highest id, else the lowest free one', () => { + expect(nextId([])).toBe(1) + expect(nextId([{ id: 1 }, { id: 5 }])).toBe(6) + expect(nextId([{ id: 255 }, { id: 1 }])).toBe(2) + expect(nextId(Array.from({ length: 255 }, (_, i) => ({ id: i + 1 })))).toBeNull() + }) + it('moves an entry and leaves bad moves alone', () => { + expect(moved(['a', 'b', 'c'], 0, 2)).toEqual(['b', 'c', 'a']) + expect(moved(['a', 'b', 'c'], 2, 0)).toEqual(['c', 'a', 'b']) + expect(moved(['a', 'b'], 0, 5)).toEqual(['a', 'b']) + }) +}) + +describe('nameProblem', () => { + it('says what is wrong with a name', () => { + expect(nameProblem('Todo', ['Done'], 'column')).toBeNull() + expect(nameProblem('', [], 'column')).toBe('Give it a name.') + expect(nameProblem('x'.repeat(64), [], 'column')).toBe('Names are at most 63 characters.') + expect(nameProblem(' Todo', [], 'column')).toBe('Names don’t start or end with a space.') + expect(nameProblem('say "hi"', [], 'view')).toBe('Names can’t hold quotes or control characters.') + expect(nameProblem('done', ['Done'], 'column')).toBe('Another column has this name.') + expect(nameProblem('Due: soon', [], 'field')).toBe('Field names can’t hold a colon or start with a dash.') + expect(nameProblem('-x', [], 'field')).toBe('Field names can’t hold a colon or start with a dash.') + expect(nameProblem('Status', [], 'field')).toBe('“Status” is a built-in field.') + // a column may be called Status + expect(nameProblem('Status', [], 'column')).toBeNull() + }) +}) + +describe('deleting what views point at', () => { + it('drops a deleted field from every view, so the definition still saves', () => { + const spec: BoardSpec = { ...SPEC, views: [...SPEC.views, { id: 4, name: 'By priority', layout: 'board', q: '', group: 'f1', lane: 'f3', sort: '-f2' }] } + const out = withoutField(withoutField(spec, 3), 1) + expect(out.fields.map((f) => f.id)).toEqual([2]) + expect(out.views.find((v) => v.id === 3)).toEqual({ id: 3, name: 'Roadmap', layout: 'roadmap', q: '' }) + expect(out.views.find((v) => v.id === 2)?.cols).toEqual(['title', 'status', 'assignees', 'f2']) + expect(out.views.find((v) => v.id === 4)).toEqual({ id: 4, name: 'By priority', layout: 'board', q: '', sort: '-f2' }) + expect('json' in serializeSpec(out)).toBe(true) + }) + it('drops a grouping the board layout does not take', () => { + expect(cleanView({ id: 1, name: 'V', layout: 'board', q: '', group: 'assignee' }, SPEC.fields)).toEqual({ id: 1, name: 'V', layout: 'board', q: '' }) + expect(cleanView({ id: 1, name: 'V', layout: 'table', q: '', group: 'assignee', lane: 'assignee' }, SPEC.fields)).toEqual({ id: 1, name: 'V', layout: 'table', q: '', group: 'assignee' }) + }) + it('a deleted Default or Done column becomes none', () => { + const out = withoutColumn(SPEC, 3) + expect(out.done).toBe(0) + expect(out.def).toBe(1) + expect(withoutColumn(SPEC, 1).def).toBe(0) + }) +}) + +describe('size and sameness', () => { + it('measures the canonical bytes, and says when it is over', () => { + expect(specBytes(SPEC)).toBe(new TextEncoder().encode((serializeSpec(SPEC) as { json: string }).json).length) + const big: BoardSpec = { ...SPEC, desc: 'é'.repeat(1000), sources: Array.from({ length: 5 }, () => ({ r: HOME, k: 'a' as const, q: 'x'.repeat(500) })) } + expect(specBytes(big)).toBeGreaterThan(SPEC_MAX_BYTES) + expect(specBytes({ ...SPEC, columns: [] })).toBeNull() + }) + it('compares by the written bytes, and trims names', () => { + expect(sameSpec(SPEC, { ...SPEC, desc: undefined })).toBe(true) + expect(sameSpec(SPEC, { ...SPEC, arch: 0 })).toBe(false) + const padded = trimNames({ ...SPEC, columns: [{ id: 1, name: ' Todo ' }] }) + expect(padded.columns[0]?.name).toBe('Todo') + }) +}) diff --git a/forge-web/components/repo/boards/board-settings-model.ts b/forge-web/components/repo/boards/board-settings-model.ts new file mode 100644 index 000000000..940b18f88 --- /dev/null +++ b/forge-web/components/repo/boards/board-settings-model.ts @@ -0,0 +1,127 @@ +/** + * The board settings editor's pure half (design `docs/design/boards.md` §2, §2.7, §8): new ids, + * the checks a name must pass (with the precise reason), deleting a column or a field without + * leaving a view pointing at it, reordering, and the definition's size against its 4096 bytes. + * What the rules (`parseSpec` / `serializeSpec`) refuse is still the last word; these say why + * earlier and next to the entry at fault. + */ + +import { NAME_MAX, SPEC_MAX_BYTES, serializeSpec, type BoardField, type BoardSpec, type BoardView as SavedView } from '@/lib/rules/boards' + +/** A new entry's id: one more than the highest (1-255), else the lowest one free; null when all 255 are taken. */ +export function nextId(entries: readonly { readonly id: number }[]): number | null { + const max = entries.reduce((m, e) => Math.max(m, e.id), 0) + if (max < 255) return max + 1 + const used = new Set(entries.map((e) => e.id)) + for (let i = 1; i <= 255; i++) if (!used.has(i)) return i + return null +} + +/** `arr` with the entry at `from` moved to `to`. */ +export function moved(arr: readonly T[], from: number, to: number): T[] { + if (from === to || from < 0 || from >= arr.length || to < 0 || to >= arr.length) return [...arr] + const out = [...arr] + const [x] = out.splice(from, 1) + out.splice(to, 0, x as T) + return out +} + +/** C0, DEL and C1 control characters. */ +const isControl = (cp: number): boolean => cp < 0x20 || (cp >= 0x7f && cp <= 0x9f) + +/** The names a field may not have, in any letter case (the query's keys and the built-in fields, §2.7). */ +const RESERVED = new Set(['is', 'state', 'label', 'labels', 'assignee', 'assignees', 'author', 'milestone', 'no', 'status', 'repo', 'repository', 'title', 'number', 'created']) + +/** + * Why `name` is not a good column, field, option or view name (§2.7), or null: 1-63 characters, + * no control character or `"`, no white space at either end, unique in any letter case among + * `others`; a field's also no `:`, no leading `-`, and not a query key or built-in field. + */ +export function nameProblem(name: string, others: readonly string[], kind: 'column' | 'field' | 'option' | 'view'): string | null { + if (name === '') return 'Give it a name.' + if ([...name].length > NAME_MAX) return `Names are at most ${NAME_MAX} characters.` + if (name.trim() !== name) return 'Names don’t start or end with a space.' + if ([...name].some((ch) => ch === '"' || isControl(ch.codePointAt(0) as number))) return 'Names can’t hold quotes or control characters.' + if (kind === 'field') { + if (name.includes(':') || name.startsWith('-')) return 'Field names can’t hold a colon or start with a dash.' + if (RESERVED.has(name.toLowerCase())) return `“${name}” is a built-in field.` + } + const low = name.toLowerCase() + if (others.some((o) => o.toLowerCase() === low)) return `Another ${kind} has this name.` + return null +} + +/** Whether a view key names a field of `fields` of one of `types` (`f`). */ +function fieldKey(fields: readonly BoardField[], key: string, types?: readonly BoardField['type'][]): boolean { + const m = /^f([1-9]\d{0,2})$/.exec(key) + const f = m ? fields.find((x) => x.id === Number(m[1])) : undefined + return f !== undefined && (types === undefined || types.includes(f.type)) +} + +const GROUP_BUILTINS = ['assignee', 'label', 'milestone', 'repo'] +const SORT_BUILTINS = ['rank', 'title', 'number', 'created', 'status', 'repo', 'author', 'milestone'] +const COL_BUILTINS = ['title', 'number', 'repo', 'state', 'author', 'assignees', 'labels', 'milestone', 'created', 'status'] + +/** + * `view` less every reference the spec's `fields` no longer back, or its layout does not take + * (§2.7): a grouping by a deleted field (or, on the board layout, by anything but Status or a + * single-select or iteration field), swimlanes likewise or equal to the grouping, a sort or table + * column of a deleted field, roadmap dates that are no longer one iteration or two date fields. + */ +export function cleanView(view: SavedView, fields: readonly BoardField[]): SavedView { + const groupOk = (k: string, board: boolean): boolean => k === 'status' || (!board && GROUP_BUILTINS.includes(k)) || fieldKey(fields, k, ['sel', 'iter']) + const out: { -readonly [K in keyof SavedView]: SavedView[K] } = { ...view } + if (out.group !== undefined && !groupOk(out.group, out.layout === 'board')) delete out.group + if (out.lane !== undefined && (out.lane === 'status' || out.lane === (out.group ?? 'status') || !groupOk(out.lane, false))) delete out.lane + if (out.sort !== undefined) { + const k = out.sort.replace(/^-/, '') + if (!SORT_BUILTINS.includes(k) && !fieldKey(fields, k)) delete out.sort + } + if (out.cols !== undefined) out.cols = out.cols.filter((c) => COL_BUILTINS.includes(c) || fieldKey(fields, c)) + if (out.date !== undefined) { + const types = out.date.map((d) => fields.find((f) => f.id === d)?.type) + const ok = (types.length === 1 && types[0] === 'iter') || (types.length === 2 && types[0] === 'date' && types[1] === 'date' && out.date[0] !== out.date[1]) + if (!ok) delete out.date + } + return out +} + +/** `spec` with its views cleaned against its fields ({@link cleanView}). */ +export function withCleanViews(spec: BoardSpec): BoardSpec { + return { ...spec, views: spec.views.map((v) => cleanView(v, spec.fields)) } +} + +/** `spec` less column `id`: a Default or Done that named it becomes none (its items go to the default column, or No status). */ +export function withoutColumn(spec: BoardSpec, id: number): BoardSpec { + return { ...spec, columns: spec.columns.filter((c) => c.id !== id), def: spec.def === id ? 0 : spec.def, done: spec.done === id ? 0 : spec.done } +} + +/** `spec` less field `id`, and every view reference to it. Cards keep the value, which no reader shows. */ +export function withoutField(spec: BoardSpec, id: number): BoardSpec { + return withCleanViews({ ...spec, fields: spec.fields.filter((f) => f.id !== id) }) +} + +/** `spec` with every column, field, option and view name trimmed (what a save writes: a typed space at either end is not an error). */ +export function trimNames(spec: BoardSpec): BoardSpec { + return { + ...spec, + columns: spec.columns.map((c) => ({ ...c, name: c.name.trim() })), + fields: spec.fields.map((f) => ({ ...f, name: f.name.trim(), ...(f.options !== undefined ? { options: f.options.map((o) => ({ ...o, name: o.name.trim() })) } : {}) })), + views: spec.views.map((v) => ({ ...v, name: v.name.trim() })), + } +} + +/** The definition's canonical JSON size in UTF-8 bytes, or null when the rules refuse it. */ +export function specBytes(spec: BoardSpec): number | null { + const out = serializeSpec(spec) + // over the limit: the rules give no bytes back, so measure the uncanonical JSON (a little more) + if ('error' in out) return out.error === 'size' ? Math.max(SPEC_MAX_BYTES + 1, new TextEncoder().encode(JSON.stringify(spec)).length) : null + return new TextEncoder().encode(out.json).length +} + +/** Whether two definitions write the same bytes. */ +export function sameSpec(a: BoardSpec, b: BoardSpec): boolean { + const x = serializeSpec(a) + const y = serializeSpec(b) + return 'json' in x && 'json' in y && x.json === y.json +} diff --git a/forge-web/components/repo/boards/board-settings.test.tsx b/forge-web/components/repo/boards/board-settings.test.tsx new file mode 100644 index 000000000..48ebf5ba4 --- /dev/null +++ b/forge-web/components/repo/boards/board-settings.test.tsx @@ -0,0 +1,179 @@ +// @vitest-environment jsdom +/** + * A board's settings (design `docs/design/boards.md` §2, §5.1, §8): the draft saved as one + * priced write, precise problems before it, deleting a field without breaking a view, the + * source filter checked as typed, close and delete, and what a reader sees. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type { RepoHome } from '@/lib/view' +import type { BoardView } from '@/lib/repo' +import { defaultSpec, type BoardSpec } from '@/lib/rules/boards' + +const ME = 'MeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMeMe' +const HOME_ID = 'Home1111111111111111111111111111111111111111' +const NOW = Date.UTC(2026, 9, 27, 12) +let role: 'maintainer' | 'writer' | 'triage' | null = 'writer' +let board: BoardView +const push = vi.fn() +const saveBoard = vi.fn(async () => ({ key: 9, documentId: 'd', created: false, result: {} })) +const setBoardState = vi.fn(async () => ({ key: 9, documentId: 'd', created: false, result: {} })) + +vi.mock('next/navigation', () => ({ usePathname: () => '/repo/board/settings/', useSearchParams: () => new URLSearchParams(), useRouter: () => ({ replace: () => undefined, push }) })) +vi.mock('next/link', () => ({ default: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => {children} })) +vi.mock('@/hooks/use-sdk', () => ({ useSdk: () => ({ sdk: {}, ready: true, network: 'devnet', status: { phase: 'ready' } }) })) +vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ signer: { identityId: ME }, identity: ME, balance: '100000000000', keyLimits: null }) })) +vi.mock('@/hooks/use-write-guard', () => ({ useWriteGuard: () => ({ check: () => true, failed: (e: unknown) => String(e), disabledReason: null }) })) +vi.mock('@/hooks/use-repo-chrome', () => ({ useViewerRole: () => ({ role, known: true, failed: false, retry: () => undefined }) })) +vi.mock('@/lib/spend-toast', () => ({ spendAction: (_labels: unknown, run: (tag: (s: unknown) => unknown) => Promise) => run((s) => s) })) +vi.mock('@/lib/view/discovery', () => ({ listReposByOwner: async () => ({ owned: [{ key: HOME_ID, slug: 'project', name: 'project', ownerId: ME }, { key: 'Other222222222222222222222222222222222222222', slug: 'docs', name: 'docs', ownerId: ME }], member: [] }) })) +vi.mock('@/lib/repo', async (orig) => ({ + ...(await orig()), + readBoardDefinition: async () => board, + readRepoById: async () => null, + saveBoard, + setBoardState, +})) + +const { BoardSettings } = await import('./board-settings') + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const HOME = { repo: { repoId: HOME_ID, forge: { core: 'C', collab: 'L', community: 'M', meta: 'X', group: 'G' }, ownerId: ME, name: 'project', visibility: 'public' }, description: '', config: null } as unknown as RepoHome +const addr = { owner: 'o', name: 'project' } +const boardOf = (spec: BoardSpec, state: BoardView['state'] = 'open'): BoardView => ({ + key: 9, + repoId: HOME_ID, + state, + name: 'Roadmap', + spec, + specError: null, + sealed: false, + newest: { id: 'b9', ownerId: ME, updatedAt: NOW }, + revisions: [{ id: 'b9', ownerId: ME, updatedAt: NOW }], +}) + +let root: Root +let el: HTMLDivElement +beforeEach(() => { + role = 'writer' + board = boardOf(defaultSpec(HOME_ID, NOW)) + saveBoard.mockClear() + setBoardState.mockClear() + push.mockReset() + el = document.createElement('div') + document.body.append(el) + root = createRoot(el) +}) +afterEach(() => { + vi.useRealTimers() + act(() => root.unmount()) + el.remove() +}) +const settle = () => act(async () => { await new Promise((r) => setTimeout(r, 0)) }) +const button = (text: RegExp): HTMLButtonElement | undefined => [...document.querySelectorAll('button')].find((b) => text.test(b.textContent ?? '') || text.test(b.getAttribute('aria-label') ?? '')) +const labelled = (label: string): T => document.querySelector(`[aria-label="${label}"]`) as T +const type = (input: HTMLInputElement, value: string): void => { + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set! + act(() => { + setter.call(input, value) + input.dispatchEvent(new Event('input', { bubbles: true })) + }) +} +const open = async (): Promise => { + await act(async () => root.render()) + await settle() +} +const savedSpec = (): BoardSpec => (saveBoard.mock.calls[0] as unknown as [unknown, unknown, unknown, number, { spec: BoardSpec; name: string }])[4].spec + +describe('Board settings', () => { + it('saves the draft as one priced write: renamed and added columns, names trimmed', async () => { + await open() + expect(el.querySelectorAll('[data-testid="column-row"]')).toHaveLength(3) + expect((el.querySelector('[data-testid="settings-save"]') as HTMLButtonElement).disabled).toBe(true) + type(labelled('Name of column 2'), 'Doing ') + act(() => button(/Add column/)?.click()) + expect(el.querySelectorAll('[data-testid="column-row"]')).toHaveLength(4) + expect(el.textContent).toContain('Unsaved changes') + expect(el.querySelector('[data-testid="size-meter"]')?.textContent).toMatch(/\/ 4,096 bytes/) + act(() => (el.querySelector('[data-testid="settings-save"]') as HTMLButtonElement).click()) + expect(document.querySelector('[role="dialog"] [data-testid="cost-preview"]')).not.toBeNull() + await act(async () => button(/Sign & save/)?.click()) + await settle() + expect(saveBoard).toHaveBeenCalledTimes(1) + expect(savedSpec().columns.map((c) => c.name)).toEqual(['Todo', 'Doing', 'Done', 'Column 4']) + }) + + it('names a problem precisely and holds the save', async () => { + await open() + type(labelled('Name of column 2'), 'todo') + expect(el.textContent).toContain('Another column has this name.') + expect(el.querySelector('[data-testid="settings-problem"]')).not.toBeNull() + expect((el.querySelector('[data-testid="settings-save"]') as HTMLButtonElement).disabled).toBe(true) + }) + + it('deletes a field and the views pointing at it', async () => { + await open() + act(() => button(/Delete field Iteration/)?.click()) + act(() => (el.querySelector('[data-testid="settings-save"]') as HTMLButtonElement).click()) + await act(async () => button(/Sign & save/)?.click()) + await settle() + const spec = savedSpec() + expect(spec.fields.map((f) => f.name)).toEqual(['Priority', 'Estimate']) + expect(spec.views.find((v) => v.name === 'Roadmap')).toEqual({ id: 3, name: 'Roadmap', layout: 'roadmap', q: '' }) + expect(spec.views.find((v) => v.name === 'Table')?.cols).toEqual(['title', 'status', 'assignees', 'f1', 'f2']) + }) + + it('edits a select field’s options and previews an iteration cadence', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(NOW) + await open() + act(() => button(/Add option/)?.click()) + expect(labelled('Option 5 of Priority').value).toBe('Option 5') + expect(el.querySelector('[data-testid="iteration-preview"]')?.textContent).toContain('Iteration 1: Oct 26 – Nov 8, 2026') + type(labelled('Days in each Iteration'), '7') + expect(el.querySelector('[data-testid="iteration-preview"]')?.textContent).toContain('Iteration 2: Nov 2 – Nov 8, 2026') + }) + + it('checks a source filter as it is typed', async () => { + await open() + type(labelled('Filter of source 1'), 'label:bug status:Todo') + expect(el.querySelector('[data-testid="source-unresolved"]')?.textContent).toContain('Not applied: status:Todo') + expect(labelled('Repo of source 1').textContent).toContain('project (this repo)') + expect(labelled('Repo of source 1').textContent).toContain('docs') + }) + + it('closes and deletes the board, each its own write', async () => { + await open() + act(() => button(/Close board/)?.click()) + await act(async () => button(/Sign & close/)?.click()) + await settle() + expect(setBoardState).toHaveBeenCalledWith(expect.anything(), expect.anything(), expect.anything(), 9, 'closed', expect.anything()) + await act(async () => new Promise((r) => setTimeout(r, 950))) + act(() => (el.querySelector('[data-testid="delete-board"]') as HTMLButtonElement).click()) + await act(async () => button(/Sign & delete/)?.click()) + await settle() + expect(setBoardState).toHaveBeenLastCalledWith(expect.anything(), expect.anything(), expect.anything(), 9, 'deleted', expect.anything()) + expect(push).toHaveBeenCalledWith('/repo/boards/?owner=o&name=project') + }) + + it('is read-only for a triage member, and for a closed board until reopened', async () => { + role = 'triage' + await open() + expect(el.querySelector('[data-testid="settings-read-only"]')?.textContent).toContain('Only maintainers and members with Write') + expect((el.querySelector('fieldset') as HTMLFieldSetElement).disabled).toBe(true) + expect(el.querySelector('[data-testid="settings-save-bar"]')).toBeNull() + expect(el.querySelector('[data-testid="delete-board"]')).toBeNull() + act(() => root.unmount()) + root = createRoot(el) + role = 'maintainer' + board = boardOf(defaultSpec(HOME_ID, NOW), 'closed') + await open() + expect(el.textContent).toContain('This board is closed. Reopen it to change it.') + expect((el.querySelector('fieldset') as HTMLFieldSetElement).disabled).toBe(true) + expect(button(/Reopen board/)).toBeDefined() + }) +}) diff --git a/forge-web/components/repo/boards/board-settings.tsx b/forge-web/components/repo/boards/board-settings.tsx new file mode 100644 index 000000000..69fc1a45c --- /dev/null +++ b/forge-web/components/repo/boards/board-settings.tsx @@ -0,0 +1,857 @@ +'use client' + +/** + * BoardSettings — `/repo/board/settings?b=` (design `docs/design/boards.md` §2, §4, §5.1, §8): + * a board's definition, edited as a draft and saved as one priced write (`saveBoard`, which + * re-reads the newest revision and replaces the signer's own). + * + * - **General**: name and description. + * - **Columns** (1-20): add, rename, colour (the label palette), WIP limit, reorder (drag, or the + * up / down buttons), delete (its items go to the default column), and the Default and Done + * columns. + * - **Fields** (up to 12): add, rename, delete; a single select's options with colours; an + * iteration's start and length, with the next iterations previewed. A field's type is fixed. + * - **Sources** (up to 5): a repository (the owner's, or any `owner/name`), issues / PRs / both, + * and a filter checked as it is typed (what a source cannot apply is named, `parseSourceQuery`). + * - **Auto-archive**, **Views** (rename, reorder, delete, layout, default query), and closing, + * reopening or deleting the board (each its own priced write). + * + * The draft is checked as the rules check it (`checkBoardInput`: names, references, the 4096 + * byte limit, with a size meter); a deleted field takes the views' references to it along, so a + * save never fails on them. Maintainers and members with Write edit; everyone else reads. + */ + +import { useMemo, useRef, useState, useSyncExternalStore, type DragEvent, type ReactNode } from 'react' +import Link from 'next/link' +import { useRouter } from 'next/navigation' +import { AlertTriangle, ArrowDown, ArrowUp, CheckCircle2, ChevronRight, GripVertical, KanbanSquare, Plus, RotateCcw, Trash2, X } from 'lucide-react' +import type { RepoHome } from '@/lib/view' +import { + LABEL_COLORS, + boardWriteGeneration, + canEditBoards, + checkBoardInput, + ownRevision, + readBoardDefinition, + readRepoById, + repoContractIds, + repoKey, + resolveAnyRepo, + saveBoard, + setBoardState, + subscribeBoardWrites, + type BoardState, + type BoardView, + type RepoRef, +} from '@/lib/repo' +import { + ARCH_MAX, + DESC_MAX, + ITER_DAYS_MAX, + MAX_COLUMNS, + MAX_FIELDS, + MAX_OPTIONS, + MAX_SOURCES, + MAX_VIEWS, + NAME_MAX, + QUERY_MAX, + SPEC_MAX_BYTES, + WIP_MAX, + dateDays, + iterationAt, + iterationRange, + mondayOf, + parseBoardQuery, + parseSourceQuery, + type BoardColumn, + type BoardField, + type BoardSource, + type BoardSpec, + type FieldOption, + type FieldType, + type SourceKind, + type ViewLayout, +} from '@/lib/rules/boards' +import type { EvoSDK } from '@dashevo/evo-sdk' +import { priceBoardWrites } from '@/lib/sdk' +import { listReposByOwner } from '@/lib/view/discovery' +import { useAsync } from '@/hooks/use-async' +import { useSdk } from '@/hooks/use-sdk' +import { useAuth } from '@/contexts/auth-context' +import { useViewerRole } from '@/hooks/use-repo-chrome' +import type { RepoAddress } from '@/hooks/use-query-param' +import { Button } from '@/components/ui/button' +import { Field, Input, Textarea } from '@/components/ui/input' +import { ConfirmDialog } from '@/components/confirm-dialog' +import { EmptyState, ErrorState, LoadingBlock } from '@/components/ui/states' +import { useDismiss } from '@/components/repo/target-rail' +import { cn, inputProblem, shortId } from '@/lib/utils' +import { boardHref, boardsHref, controlClass, ColorDot, dayRangeText, columnName } from './board-fields' +import { boardsAvailable } from './boards-list' +import { cleanView, moved, nameProblem, nextId, sameSpec, specBytes, trimNames, withCleanViews, withoutColumn, withoutField } from './board-settings-model' + +type SpecEdit = (f: (s: BoardSpec) => BoardSpec) => void + +const FIELD_TYPE_LABEL: Readonly> = { sel: 'Single select', num: 'Number', date: 'Date', iter: 'Iteration', text: 'Text' } +const KIND_LABEL: Readonly> = { a: 'Issues and pull requests', i: 'Issues', p: 'Pull requests' } +const LAYOUT_LABEL: Readonly> = { board: 'Board', table: 'Table', roadmap: 'Roadmap' } + +export function BoardSettings({ home, addr, boardKey }: { home: RepoHome; addr: RepoAddress; boardKey: number }): JSX.Element { + if (!boardsAvailable(home)) return + if (!Number.isInteger(boardKey) || boardKey < 1 || boardKey > 0xffffffff) return + return +} + +function BoardSettingsLoaded({ home, addr, boardKey }: { home: RepoHome; addr: RepoAddress; boardKey: number }): JSX.Element { + const repo = home.repo + const { sdk, ready, network } = useSdk(repoContractIds(repo)) + const { signer } = useAuth() + const { role } = useViewerRole(repo) + const generation = useSyncExternalStore(subscribeBoardWrites, () => boardWriteGeneration(repo), () => 0) + const read = useAsync(() => readBoardDefinition(sdk!, repo, boardKey), [ready, repoKey(repo), network, boardKey, generation], { enabled: ready && sdk !== null }) + const board = read.data + if (read.loading && board === null) return + if (read.error) return + if (board === null) return All boards} /> + if (board.state === 'deleted') return All boards} /> + if (board.spec === null || board.name === null) { + return + } + const editor = signer !== null && canEditBoards(role) && home.config?.archived !== true + return ( +
+ + {!editor ? ( +

+ {home.config?.archived === true ? 'This repo is archived, so its boards are read-only.' : signer === null ? 'Sign in as a maintainer or a member with Write to change this board.' : 'Only maintainers and members with Write change a board’s settings.'} +

+ ) : null} + {/* A new revision (this page's save, or another member's) starts a fresh draft. */} + +
+ ) +} + +function Section({ title, hint, children, id }: { title: string; hint?: ReactNode; children: ReactNode; id: string }): JSX.Element { + return ( +
+
+

+ {title} +

+ {hint ?

{hint}

: null} +
+ {children} +
+ ) +} + +const card = 'rounded-lg border border-anvil-200 dark:border-anvil-800' +const rowClass = 'flex flex-wrap items-center gap-2 border-b border-anvil-100 px-3 py-2 last:border-b-0 dark:border-anvil-850' +const iconButton = 'inline-flex h-7 w-7 shrink-0 items-center justify-center rounded text-anvil-500 hover:bg-anvil-100 hover:text-anvil-900 disabled:pointer-events-none disabled:opacity-40 dark:text-anvil-400 dark:hover:bg-anvil-800 dark:hover:text-anvil-50 coarse:h-11 coarse:w-11' + +function Problem({ text }: { text: string | null }): JSX.Element | null { + return text === null ? null : ( +

+ {text} +

+ ) +} + +/** Up / down / delete buttons of a list entry. */ +function EntryButtons({ index, count, what, onMove, onDelete }: { index: number; count: number; what: string; onMove: (to: number) => void; onDelete?: () => void }): JSX.Element { + return ( + + + + {onDelete !== undefined ? ( + + ) : null} + + ) +} + +/** A colour from the label palette, or none, in a small popover. */ +function ColorPicker({ color, onChange, what }: { color: string | undefined; onChange: (c: string | undefined) => void; what: string }): JSX.Element { + const [open, setOpen] = useState(false) + const ref = useRef(null) + useDismiss(open, ref, () => setOpen(false)) + return ( + + + {open ? ( + + {LABEL_COLORS.map((c) => ( + + + ) : null} + + ) +} + +/** The draft editor; `board` is the revision it started from. */ +function SettingsEditor({ home, addr, board, sdk, editor, reload }: { home: RepoHome; addr: RepoAddress; board: BoardView & { spec: BoardSpec; name: string }; sdk: EvoSDK | null; editor: boolean; reload: () => void }): JSX.Element { + const repo = home.repo + const router = useRouter() + const { signer } = useAuth() + const [name, setName] = useState(board.name) + const [spec, setSpec] = useState(board.spec) + const [action, setAction] = useState<'save' | BoardState | null>(null) + const edit: SpecEdit = (f) => setSpec((s) => f(s)) + const open = board.state === 'open' + const readOnly = !editor || !open + // What a save writes: names trimmed, as the board name is. + const clean = useMemo(() => trimNames(spec), [spec]) + const changed = name.trim() !== board.name || !sameSpec(clean, board.spec) + const problem = inputProblem(() => checkBoardInput({ name, spec: clean })) + const bytes = specBytes(clean) + const own = signer !== null && ownRevision(board, signer.identityId) !== null + const cost = priceBoardWrites(own ? 0 : 1, own ? 1 : 0, { type: 'board', sealed: board.sealed }) + + const run = async (intent: string): Promise => { + if (sdk === null || signer === null || action === null) throw new Error('Sign in to change this board.') + if (action === 'save') await saveBoard(sdk, signer, repo, board.key, { name: name.trim(), spec: clean }, { intent }) + else await setBoardState(sdk, signer, repo, board.key, action, { intent }) + if (action === 'deleted') router.push(boardsHref(addr)) + else reload() + } + const confirm = + action === 'save' + ? { title: `Save “${name.trim()}”`, description: 'Everyone who opens the board sees the new settings.', label: 'Sign & save' } + : action === 'closed' + ? { title: `Close “${board.name}”`, description: 'A closed board is read-only and listed under Closed. You can reopen it.', label: 'Sign & close' } + : action === 'open' + ? { title: `Reopen “${board.name}”`, description: 'Members can move its items and edit it again.', label: 'Sign & reopen' } + : { title: `Delete “${board.name}”`, description: 'The board leaves the list for everyone. Its issues and pull requests are not touched.', label: 'Sign & delete' } + + return ( +
+ {!open ? ( +
+ This board is closed. Reopen it to change it. + {editor ? ( + + ) : null} +
+ ) : null} + +
+
+
+ + setName(e.target.value)} maxLength={NAME_MAX} /> + + +