Fork card: transport (list, read, answer; desk.read and desk.answer), note limit in UTF-8 bytes, unavailable
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled

Adds the Transport section: three routes, request and response documents
(list_request, list, read_request, entry), the stamp and cursor, auth in order
(bearer, audience bifrost-desk, scope), the MAS token and votes.* tokens
refused, Huginn's outcome returned unchanged, a stale refusal carrying the
current card; every part marked as owed by Bifrost or Huginn. Note limit is
4000 UTF-8 bytes (a rule beside the looser maxLength) with ASCII, multibyte,
astral and combining vectors. unavailable (503) is a document of its own,
outside the refusal set, stores nothing, and is raised after body shape and
before the door. Vectors regenerated; both judges replay lists, auth, notes and
the unavailable scenarios.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-10 15:26:50 +00:00
commit ad16c26e21
6 changed files with 4008 additions and 171 deletions

File diff suppressed because one or more lines are too long

View file

@ -18,6 +18,11 @@ All documents are CultNet map-mode: every key written, nil where absent, closed
| `gamecult.fork.refusal.v0` | a body refused at the door; nothing stored | Bifrost |
| `gamecult.fork.record.v0` | a fork's answers plus the derived counted answer | a projection of the stored `desk_answer`s |
| `gamecult.fork.ruling_cite.v0` | the citation a ruling carries | the Mind admitting the ruling |
| `gamecult.fork.list_request.v0` | list a Mind's forks (Transport) | the desk |
| `gamecult.fork.list.v0` | a page of entries, counts and a stamp | Bifrost, projected from Huginn |
| `gamecult.fork.read_request.v0` | read one fork (Transport) | the desk |
| `gamecult.fork.entry.v0` | one card with its record | Bifrost, projected from Huginn |
| `gamecult.fork.unavailable.v0` | the second door or Huginn is down; try again | Bifrost |
### card
@ -45,7 +50,7 @@ Vectors `optionsHash`: the seven of the binding file (`heimdall_A..G`), computed
### answer_request
`{schemaVersion, fork_id, options_hash, answer, retracted, retracts, answered_at}`. `answer` is `{choice, note}` (at least one non-nil) or nil on a retraction. `choice` is an option id; `note` is the person's words, verbatim, 1 to 4000 characters (code points, as JSON Schema counts them), not blank. `answered_at` is the client's claim. **A request never carries `answerer` or `authority`**: both are stamped by Huginn (`answerer` from the verified subject the receiver passes; `authority` from the door's configuration). A body that names either key at any depth is refused whole, never stripped (`body_forbidden_field`); any other unknown key is `body_unknown_field`. The request type Bifrost sends over the second door is this document; it has no field for either key, so a client cannot supply them by construction, and Bifrost's scan is the first line, not the only one. How Huginn receives the verified subject is the door's authenticated context, not a body field (open choice 3). In map-mode `retracted` is always written (the binding file's optional `retracted` becomes `false`).
`{schemaVersion, fork_id, options_hash, answer, retracted, retracts, answered_at}`. `answer` is `{choice, note}` (at least one non-nil) or nil on a retraction. `choice` is an option id; `note` is the person's words, verbatim, 1 to 4000 **UTF-8 bytes**, not blank. A schema counts characters, not bytes, so its `maxLength: 4000` (code points) is only the looser bound and both suites enforce the byte limit as a rule: 4000 ASCII bytes pass; 1000 astral characters (4000 bytes) pass and 1001 (4004) fail; `e` plus a combining acute is 3 bytes, so 1333 of them and an `x` pass and 1334 fail; 1999 two-byte characters plus three ASCII (4001 bytes) fail. A note over the limit is `body_invalid`. `answered_at` is the client's claim. **A request never carries `answerer` or `authority`**: both are stamped by Huginn (`answerer` from the verified subject the receiver passes; `authority` from the door's configuration). A body that names either key at any depth is refused whole, never stripped (`body_forbidden_field`); any other unknown key is `body_unknown_field`. The request type Bifrost sends over the second door is this document; it has no field for either key, so a client cannot supply them by construction, and Bifrost's scan is the first line, not the only one. How Huginn receives the verified subject is the door's authenticated context, not a body field (open choice 3). In map-mode `retracted` is always written (the binding file's optional `retracted` becomes `false`).
### desk_answer (the stored kind)
@ -58,7 +63,7 @@ The stamped `authority` field of a stored answer is an **attribution**: the role
- `Retraction`: the stored form of `retracted: true` plus `retracts`. `retracts` names the answer retracted; `choice` and `note` nil. The illegal pair (a retraction with no target, or a target with no retraction) cannot be written.
- `Refused`: any refusal from steps 4 to 7 or R1 and R2, with its `code`, stored too. `choice` and `note` keep what the body carried.
`received_at` is Huginn's admission time; "first" means first by admission order (the `n<seq>` ordinal), never by `answered_at`. `claim_in_future` is true when `answered_at` is more than five minutes after `received_at`: accepted but flagged. **Not stored, and no answer id:** a body refused at step 1 or 2 (Bifrost; it never reaches Huginn), and a body naming an unknown fork (step 3; Huginn answers it from its stored forks, but with no question there is nothing to key a record under). Each gets a `refusal` and is dropped. A malformed body is therefore never stored, and neither is an unknown fork. Every refusal from step 4 on is stored.
`received_at` is Huginn's admission time; "first" means first by admission order (the `n<seq>` ordinal), never by `answered_at`. `claim_in_future` is true when `answered_at` is more than five minutes after `received_at`: accepted but flagged. **Not stored, and no answer id:** a body refused at step 1 or 2 (Bifrost; it never reaches Huginn), and a body naming an unknown fork (step 3; Huginn answers it from its stored forks, but with no question there is nothing to key a record under). Each gets a `refusal` and is dropped. A malformed body is therefore never stored, and neither is an unknown fork. Every refusal from step 4 on is stored. **`unavailable`** (503) is not a refusal and not in the refusal set: Bifrost answers it when the second door or Huginn cannot be reached after steps 1 and 2 passed (a bad body is still refused first). It carries no answer id, stores nothing, and tells the desk to try the same request again (`retryAfterSeconds`, nil when Bifrost has no hint).
### Counting rules (in order; the first failure refuses with that code)
@ -87,6 +92,32 @@ The stamped `authority` field of a stored answer is an **attribution**: the role
A ruling may carry `authority: Operator` only if it cites (`ruling_cite.answer_id`) a stored `desk_answer` whose outcome is `Counted` and whose stamped attribution (the answer's `authority` field) is `Operator` (or a stamped relay of her words from a mapped door, which this contract does not model). The citation is what gives a ruling authority: an attribution on an answer is a fact about the account, and authority exists only where a ruling cites a counted answer. The cited answer id is what `ruled_from` lists on the closed card. Negative vectors (`rulingCites`): no citation, a `Revision`, a `Refused` answer, a Counted answer by a non-operator, an answer that does not exist. Other authorities need no citation.
## Transport
Source: the desk's client needs (Ratatoskr PR #24 section 12, `ratatoskr-desk-spec-20261110.md`) and Heimdall's binding file, `/opt/commons/handoff/fork-desk-answer-binding-20261110.md`, section 1.3c, which is the source for the second door. **Everything in this section is spec text for Bifrost to build; no route, scope or audience below exists in Bifrost today.** Heimdall is writing the same routes and scopes into his file; his file named none when this was written, so the paths and the audience name `bifrost-desk` are this page's proposal and any difference is his to rule. The scope names `desk.read` and `desk.answer` are his.
**Authorities.** Cards are projected **read-only from Huginn**: Bifrost never authors a card, a ruling or a status, and the desk never writes one. Bifrost verifies the bearer, resolves the actor from its `sub` (a `UserAccount.Id`), and for an answer forwards a typed `DeskAnswer` on the peer-checked second door to Huginn, then returns **Huginn's outcome unchanged**: the stored `desk_answer` in an `answer_result`, or its refusal. The wire of the second door is **pending**: Eureka's cut spec follows her record PR, so this page defines the documents the desk sees and not the bytes between Bifrost and Huginn (open choice 3).
| call | route (proposal) | request | response | token |
|---|---|---|---|---|
| 1 list | `GET /api/desk/forks?mind=&status=&cursor=&limit=` | `list_request` as the query string | `list` | audience `bifrost-desk`, scope `desk.read` |
| 2 read | `GET /api/desk/forks/{fork_id}` (the id percent-encoded) | `read_request`, its `fork_id` from the path | `entry`, or `refusal` `fork_unknown` (404) | `desk.read` |
| 3 answer | `POST /api/desk/answers` | `answer_request` as the body | `answer_result` (200 for a stored outcome of any kind, `Refused` included; the desk reads `outcome` and `code`, not the status), or a `refusal`, or `unavailable` | audience `bifrost-desk`, scope `desk.answer` |
Calls 1 and 2 are enough for a read-only desk. Every response is the pinned MessagePack document or its JSON form with the same keys (open choice 1 of `vote-api.md`: the media type is unsettled).
**Auth, in order, per route.** (1) A bearer, else `unauthenticated` (401). (2) The token's audience is `bifrost-desk`: **the Matrix Authentication Service token chat holds today is refused, and so is any `votes.*` token** (audience `bifrost-votes`), both as `unauthenticated`. (3) The scope the route needs, else `insufficient_scope` (403): `desk.read` for calls 1 and 2, `desk.answer` for call 3, and neither implies the other. A `votes.*` token therefore touches none of the three. For call 3 the body is then shaped (steps 1 and 2 above) and a body naming `answerer` or `authority` at any depth is `body_forbidden_field`. Heimdall's file leaves the audience and the claims check open; `insufficient_scope` and `request_invalid` (400, a list or read request that fails its document) are added to the door refusals.
**List.** `list_request`: `{mind, status, cursor, limit}`. `mind` is the Mind's instance slug. `status` is `open`, `recorded` or nil for both; `recorded` means a closed card. Cards come **newest first by `order`** (the admission ordinal). `limit` is 0 to 50; **`limit` 0 returns no entries, only the counts and the stamp**, which is what "N open" on the Mind's header needs. `cursor` is nil or `c<N>`: the cards whose `order` is below N; a client treats it as opaque and sends back the `next_cursor` it was given. `list`: `{mind, stamp, open_count, recorded_count, forks[entry], next_cursor}`. The counts cover every card the viewer may see, whatever `status` and `cursor` asked for. `stamp` is `s<N>`, N the receiver's last-seen Huginn admission ordinal for the Mind's desk documents: the same stamp means the same state, so a desk polls `limit` 0 and fetches bodies only when the stamp moves. `next_cursor` is nil on the last page. An `entry` is `{card, record}`: the card and its `record` (the answers with their outcomes and the derived `counted_answer_id`).
**Read.** `entry` for one fork. Its `card.options_hash` is **computed by the server** from the five shown members as in "Options hash" and the client recomputes it from what it rendered; a card whose hash is not the hash of its members is no card (negative vector `card_hash_wrong`). The record's `fork_id` and `options_hash` are the card's, and `counted_answer_id` is derived, not copied (negative vectors for each). Which cards and answers a viewer may see follows the card's audience (PR #24 section 5); a fork the viewer may not see is `fork_unknown`, not a different refusal.
**Answer.** The body is the `answer_request` and nothing else a client may set: `fork_id`, `options_hash`, `answer`, `answered_at` (plus `retracted` and `retracts`, written `false` and nil unless the call retracts). The response is the stored outcome: `Counted`, `Revision`, `Retraction`, or `Refused` with its code. **A `stale_fork` refusal carries the current card** in `answer_result.card`, so the desk can show the new fork without another read. Nothing is stored for a step 1 or 2 refusal or an unknown fork, and nothing for `unavailable`.
**Vectors (`transport` in `fork-card-vectors.json`).** `listRequest`, `readRequest` and `entry` (valid and invalid, with bytes); `listInvalid`; `listScenarios` (five scenarios over one Mind's five cards: paged open-only, recorded-only, all, `limit` 0, an empty Mind, each response with its bytes, the cursor of page two being page one's `next_cursor`); `authCases` (thirteen token and route pairs, among them the MAS token, three `votes.*` tokens, a desk token with the other route's scope). Both suites replay the list requests through a reference judge and the auth cases through another. Top-level `unavailable` pins the 503 document, and two scenarios pin that an unreachable door stores nothing and that a bad body is refused before the door is asked.
**Bifrost must still build:** all three routes; the `bifrost-desk` audience and the `desk.read` and `desk.answer` scopes on the OIDC token it issues to chat; the projection of cards and records from Huginn, the stamp, the cursor and the counts; the `DeskAnswer` call on the second door and the pass-through of its outcome; the `unavailable` answer. **Huginn must still build** the second door's wire and the read side the projection uses (Eureka's cut spec, after her record PR). **The desk may build today** against the vectors: nothing in them needs a live service.
## Old format, the mind's record, and what maps to what
The old desk (`index.html`) read `questions/<id>` and wrote `answers/<id>` in a shared store. The mind's `question` record is the source in the new design; the card is its projection.
@ -131,6 +162,7 @@ Option B, **Bifrost receives the answer and Huginn stores it** (the design in th
- `Refused` stores every refusal from steps 4 to 7 and R1 and R2 (his section 1.3b); only steps 1 and 2 and `fork_unknown` are not stored. The binding file does not say whether `fork_unknown` is stored; it cannot be keyed without a question, so it is not (open choice 4).
- The binding file's `choice_valid` has no named refusal code; this page names it `choice_invalid`. `fork_known` is `fork_unknown`. A type-invalid body is `body_invalid`.
- `ruled` (his R3 and V10) is dropped: a ruling that answers a fork closes it, so the case is `fork_closed` (V4, V10a). His file drops it too.
- Transport (routes, scopes, list, read, `unavailable`) is this page's; his file has none yet. The note limit is 4000 UTF-8 bytes here, as his 1.1 leaves the unit unsaid.
- The recommendation is never nil. The binding file's earlier vectors D and E used a nil recommendation; its updated D and E use `"a"`, as here.
- Hash vectors: A, B, C, D, E, F and G of the binding file are reproduced digest for digest by the Python generator, the C# suite and the TypeScript suite (the generator prints `same` for each; none differs).
@ -144,4 +176,5 @@ Option B, **Bifrost receives the answer and Huginn stores it** (the design in th
6. What the person sees of a retracted counted answer when the next answer counts: this contract only says the count moves.
7. `received_at` is not in the binding file's stored fields; it is kept for `claim_in_future` and could be dropped if the ordinal alone decides order.
8. The stamped `authority` field is an attribution, not an authority (above); renaming it `attribution` would say so, at the price of a new key the door must also refuse in a body.
9. Which scope and audience a fork answer needs from Bifrost PR #37: its scopes (`votes.read`, `votes.cast`) and audience (`bifrost-votes`) name votes, and this page says only "verified session or bearer".
9. The audience name `bifrost-desk` and the three routes are this page's proposal beside Heimdall's scope names; his file will rule them. The claims Bifrost verifies are PR #24's open item 5.
10. The second door's wire between Bifrost and Huginn (pending Eureka's cut spec). `unavailable` is a document of its own, outside the refusal set, so a desk can retry it; whether the same document also covers calls 1 and 2 when Huginn is down is assumed here and is Bifrost's to confirm.

View file

@ -185,7 +185,8 @@
"type": "string",
"minLength": 1,
"maxLength": 4000,
"pattern": "^(?![\\t-\\r \\u0085   - 

   ]+$)[\\s\\S]+$"
"pattern": "^(?![\\t-\\r \\u0085   - 

   ]+$)[\\s\\S]+$",
"description": "At most 4000 UTF-8 bytes, which a schema cannot say: maxLength here counts code points and is only the looser bound (a code point is at least one byte). The byte limit is a rule both suites enforce (fork-card.md, answer_request)."
},
"answerObject": {
"oneOf": [
@ -671,7 +672,9 @@
"body_forbidden_field",
"body_unknown_field",
"body_invalid",
"fork_unknown"
"fork_unknown",
"insufficient_scope",
"request_invalid"
]
},
"error": {
@ -750,6 +753,181 @@
]
}
}
},
"cursor": {
"type": "string",
"pattern": "^c[1-9][0-9]*$",
"description": "Opaque to a client. c<N> means: the cards whose order is below N."
},
"stamp": {
"type": "string",
"pattern": "^s[0-9]+$",
"description": "s<N>, N the receiver's last-seen Huginn admission ordinal for the Mind's desk documents. Two lists with the same stamp are the same state."
},
"listRequest": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"mind",
"status",
"cursor",
"limit"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.list_request.v0"
},
"mind": {
"$ref": "#/$defs/id"
},
"status": {
"oneOf": [
{
"enum": [
"open",
"recorded"
]
},
{
"type": "null"
}
]
},
"cursor": {
"oneOf": [
{
"$ref": "#/$defs/cursor"
},
{
"type": "null"
}
]
},
"limit": {
"type": "integer",
"minimum": 0,
"maximum": 50
}
}
},
"readRequest": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"fork_id"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.read_request.v0"
},
"fork_id": {
"$ref": "#/$defs/id"
}
}
},
"entry": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"card",
"record"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.entry.v0"
},
"card": {
"$ref": "#/$defs/card"
},
"record": {
"$ref": "#/$defs/record"
}
}
},
"list": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"mind",
"stamp",
"open_count",
"recorded_count",
"forks",
"next_cursor"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.list.v0"
},
"mind": {
"$ref": "#/$defs/id"
},
"stamp": {
"$ref": "#/$defs/stamp"
},
"open_count": {
"type": "integer",
"minimum": 0
},
"recorded_count": {
"type": "integer",
"minimum": 0
},
"forks": {
"type": "array",
"maxItems": 50,
"items": {
"$ref": "#/$defs/entry"
}
},
"next_cursor": {
"oneOf": [
{
"$ref": "#/$defs/cursor"
},
{
"type": "null"
}
]
}
}
},
"unavailable": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"code",
"error",
"retryAfterSeconds"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.unavailable.v0"
},
"code": {
"const": "unavailable"
},
"error": {
"type": "string",
"minLength": 1
},
"retryAfterSeconds": {
"oneOf": [
{
"type": "integer",
"minimum": 1
},
{
"type": "null"
}
]
}
}
}
}
}

View file

@ -152,6 +152,7 @@ test("fork card: documents validate and encode to the vector bytes", () => {
for (const [section, def] of [["request", "answerRequest"], ["deskAnswer", "deskAnswer"]] as const) {
for (const v of fork[section].valid) {
assert.ok(check(forkSchema, def, v.message), v.name);
assert.deepEqual(noteRuleErrors(def, v.message), [], v.name);
assert.equal(hexOf(v.message), v.messagePackHex, v.name);
assert.deepEqual(decode(Buffer.from(v.messagePackHex, "hex")), v.message, v.name);
}
@ -163,7 +164,13 @@ test("fork card: documents validate and encode to the vector bytes", () => {
assert.equal(hexOf(v.message), v.messagePackHex, v.name);
assert.equal(v.message.card !== null, v.name === "stale_fork", "only a stale refusal shows the new fork");
}
for (const v of fork.unavailable) {
assert.ok(check(forkSchema, "unavailable", v.message), v.name);
assert.equal(hexOf(v.message), v.messagePackHex, v.name);
assert.equal(v.httpStatus, 503, v.name);
}
const doorCodes = (forkSchema.$defs.refusal.properties.code as { enum: string[] }).enum;
assert.ok(!doorCodes.includes("unavailable"), "unavailable is kept apart from the refusal set");
assert.deepEqual(fork.doorRefusals.map((r: { name: string }) => r.name).sort(), [...doorCodes].sort());
for (const v of fork.doorRefusals) {
assert.ok(check(forkSchema, "refusal", v.message), v.name);
@ -177,12 +184,18 @@ test("fork card: every negative is refused by the schema or a stated rule", () =
}
for (const [section, def] of [["request", "answerRequest"], ["deskAnswer", "deskAnswer"]] as const) {
for (const v of fork[section].invalid) {
assert.equal(check(forkSchema, def, v.message), false, `${v.name}: ${v.why}`);
assert.ok(!check(forkSchema, def, v.message) || noteRuleErrors(def, v.message).length > 0, `${v.name}: ${v.why}`);
assert.equal(hexOf(v.message), v.messagePackHex, v.name);
}
}
});
// Rules a JSON Schema cannot say: a note is at most 4000 UTF-8 bytes (maxLength counts code points and is only the looser bound).
const noteRuleErrors = (def: string, message: any): string[] => {
const note = def === "answerRequest" ? message?.answer?.note : def === "deskAnswer" ? message?.note : null;
return note != null && Buffer.byteLength(note, "utf8") > 4000 ? ["note is over 4000 UTF-8 bytes"] : [];
};
const TAILS: Record<string, string> = {
unauthenticated: "a verified session is required",
body_forbidden_field: "answerer and authority are set by the receiver",
@ -225,7 +238,8 @@ function judge(start: Card, steps: { kind: string; body: Record<string, any> | n
if (s.answerer === null) response = door("unauthenticated");
else if (hasKey(b, ["answerer", "authority"])) response = door("body_forbidden_field");
else if (Object.keys(b).some((k) => !REQUEST_KEYS.includes(k)) || (b.answer && Object.keys(b.answer).some((k) => k !== "choice" && k !== "note"))) response = door("body_unknown_field");
else if (!check(forkSchema, "answerRequest", b) || (!b.retracted && b.answer === null)) response = door("body_invalid");
else if (!check(forkSchema, "answerRequest", b) || noteRuleErrors("answerRequest", b).length > 0 || (!b.retracted && b.answer === null)) response = door("body_invalid");
else if (s.door_down) response = { schemaVersion: "gamecult.fork.unavailable.v0", code: "unavailable", error: "unavailable: the answer path is down, try again", retryAfterSeconds: s.retry_after_seconds };
else if (b.fork_id !== card.fork_id) response = door("fork_unknown");
else if (b.options_hash !== optionsHash(card)) response = refuse("stale_fork");
else if (!card.deciders.includes(s.answerer)) response = refuse("not_a_decider");
@ -254,12 +268,12 @@ test("fork card: every scenario replays to the vector's responses and record, by
assert.deepEqual(record, sc.record, sc.name);
assert.ok(check(forkSchema, "record", record), sc.name);
assert.equal(hexOf(record), sc.recordHex, sc.name);
for (const s of sc.steps) if (s.response) assert.ok(check(forkSchema, "answerResult", s.response) || check(forkSchema, "refusal", s.response), sc.name);
for (const s of sc.steps) if (s.response) assert.ok(check(forkSchema, "answerResult", s.response) || check(forkSchema, "refusal", s.response) || check(forkSchema, "unavailable", s.response), sc.name);
}
});
test("fork card: a body refused at the door or naming an unknown fork is never stored", () => {
const door = new Set(["unauthenticated", "body_forbidden_field", "body_unknown_field", "body_invalid", "fork_unknown"]);
const door = new Set(["unauthenticated", "body_forbidden_field", "body_unknown_field", "body_invalid", "fork_unknown", "unavailable"]);
let doorRefusals = 0;
for (const sc of fork.scenarios) {
for (const s of sc.steps) {
@ -278,7 +292,7 @@ test("fork card: the scenarios cover every outcome and every refusal code", () =
for (const s of sc.steps) if (s.response) seen.add(s.response.code ?? s.response.answer.code ?? s.response.answer.outcome);
for (const a of sc.record.answers) seen.add(a.outcome);
}
for (const want of ["Counted", "Revision", "Retraction", "Refused", "unauthenticated", "body_forbidden_field", "body_unknown_field", "body_invalid", "fork_unknown", "stale_fork", "not_a_decider",
for (const want of ["Counted", "Revision", "Retraction", "Refused", "unauthenticated", "body_forbidden_field", "body_unknown_field", "body_invalid", "fork_unknown", "unavailable", "stale_fork", "not_a_decider",
"fork_closed", "choice_invalid", "bad_retraction", "already_retracted"]) {
assert.ok(seen.has(want), want);
}
@ -298,3 +312,79 @@ test("fork card: operator authority needs a cited Counted answer record", () =>
assert.equal(admitRuling(c.message, c.answers), c.admit, c.name);
}
});
// ---- transport: list, read, auth (fork-card.md "Transport") ----
const entryRuleErrors = (e: { card: Card; record: { fork_id: string; options_hash: string; counted_answer_id: string | null; answers: Record<string, any>[] } }): string[] => {
const errors = cardRuleErrors(e.card);
if (e.record.fork_id !== e.card.fork_id) errors.push("record of another fork");
if (e.record.options_hash !== e.card.options_hash) errors.push("record under another hash");
const counted = e.record.answers.find((a) => (a.outcome === "Counted" || a.outcome === "Revision") && a.options_hash === e.card.options_hash
&& !e.record.answers.some((r) => r.outcome === "Retraction" && r.retracts === a.answer_id));
if ((counted?.answer_id ?? null) !== e.record.counted_answer_id) errors.push("counted_answer_id is not derived");
return errors;
};
// The reference list judge: newest first by card order, status filter, cursor c<N> = cards below order N, a page of limit, counts over the whole set.
const judgeList = (entries: { card: Card }[], ordinal: number, rq: { mind: string; status: string | null; cursor: string | null; limit: number }) => {
const rows = [...entries].sort((a, b) => (b.card as any).order - (a.card as any).order);
let want = rows.filter((e) => rq.status === null || (e.card.status === "open") === (rq.status === "open"));
if (rq.cursor !== null) want = want.filter((e) => (e.card as any).order < Number(rq.cursor!.slice(1)));
const page = want.slice(0, rq.limit);
const more = want.length > page.length && page.length > 0;
return { schemaVersion: "gamecult.fork.list.v0", mind: rq.mind, stamp: `s${ordinal}`, open_count: rows.filter((e) => e.card.status === "open").length,
recorded_count: rows.filter((e) => e.card.status === "closed").length, forks: page, next_cursor: more ? `c${(page[page.length - 1].card as any).order}` : null };
};
// Bearer, audience, scope, in that order: a votes.* token fails at the audience and a desk token without the route's scope fails at the scope.
const authJudge = (route: string, token: { audience: string; scopes: string[] } | null): string => {
if (token === null || token.audience !== "bifrost-desk") return "unauthenticated";
return token.scopes.includes(route === "answer" ? "desk.answer" : "desk.read") ? "ok" : "insufficient_scope";
};
test("fork transport: requests and entries validate and encode to the vector bytes, and every negative is refused", () => {
const t = fork.transport;
for (const [section, def] of [["listRequest", "listRequest"], ["readRequest", "readRequest"], ["entry", "entry"]] as const) {
for (const v of t[section].valid) {
assert.ok(check(forkSchema, def, v.message), v.name);
if (def === "entry") assert.deepEqual(entryRuleErrors(v.message), [], v.name);
assert.equal(hexOf(v.message), v.messagePackHex, v.name);
}
for (const v of t[section].invalid) {
assert.ok(!check(forkSchema, def, v.message) || (def === "entry" && entryRuleErrors(v.message).length > 0), `${v.name}: ${v.why}`);
assert.equal(hexOf(v.message), v.messagePackHex, v.name);
}
}
for (const v of t.listInvalid) {
assert.equal(check(forkSchema, "list", v.message), false, `${v.name}: ${v.why}`);
assert.equal(hexOf(v.message), v.messagePackHex, v.name);
}
});
test("fork transport: every list request replays to the vector's response, newest first, paged by the cursor", () => {
for (const sc of fork.transport.listScenarios) {
for (const e of sc.entries) assert.deepEqual(entryRuleErrors(e), [], sc.name);
let previous: { next_cursor: string | null } | null = null;
for (const step of sc.steps) {
const response = judgeList(sc.entries, sc.ordinal, step.request);
assert.deepEqual(response, step.response, sc.name);
assert.ok(check(forkSchema, "list", response), sc.name);
assert.equal(hexOf(response), step.responseHex, sc.name);
const orders = response.forks.map((f: any) => f.card.order);
assert.deepEqual(orders, [...orders].sort((a: number, b: number) => b - a), sc.name);
if (previous !== null) assert.equal(step.request.cursor, previous.next_cursor, `${sc.name}: the second request follows the first page's cursor`);
previous = response;
}
}
});
test("fork transport: auth is bearer, then audience, then scope, and a votes token touches nothing", () => {
const codes = (forkSchema.$defs.refusal.properties.code as { enum: string[] }).enum;
const seen = new Set<string>();
for (const c of fork.transport.authCases) {
const got = authJudge(c.route, c.token);
assert.equal(got, c.expect, c.name);
if (got !== "ok") assert.ok(codes.includes(got), c.name);
seen.add(`${c.route}:${got}`);
}
for (const want of ["list:insufficient_scope", "answer:insufficient_scope", "read:unauthenticated", "answer:ok"]) assert.ok(seen.has(want), want);
});

View file

@ -217,9 +217,11 @@ def retraction(target, **kw): return body(retracts=target, **kw)
NOTE = "Keep it local: a slot mark is the author's call, and sharing it is a separate act."
def srv(aid, who, at, auth="Operator"): return {"answer_id": aid, "answerer": who, "authority": auth, "received_at": at}
TAIL = {"unauthenticated": "a verified session is required", "body_forbidden_field": "answerer and authority are set by the receiver", "body_unknown_field": "the body is a closed shape",
"body_invalid": "the body does not satisfy gamecult.fork.answer_request.v0", "fork_unknown": "no such fork"}
"body_invalid": "the body does not satisfy gamecult.fork.answer_request.v0", "fork_unknown": "no such fork",
"insufficient_scope": "the token lacks the scope this route needs", "request_invalid": "the request does not satisfy its document"}
DOOR = set(TAIL)
def refusal_doc(code): return {"schemaVersion": "gamecult.fork.refusal.v0", "code": code, "error": f"{code}: {TAIL[code]}"}
def unavailable_doc(retry=30): return {"schemaVersion": "gamecult.fork.unavailable.v0", "code": "unavailable", "error": "unavailable: the answer path is down, try again", "retryAfterSeconds": retry}
def future(a, r):
import datetime as dt
p = lambda x: dt.datetime.strptime(x, "%Y-%m-%dT%H:%M:%SZ")
@ -270,6 +272,8 @@ scen = [
sc("an_unknown_key_is_refused_the_body_is_closed", CARD, [door(dict(x1, mood="happy"), sx1, "body_unknown_field")], None),
sc("an_answer_with_neither_choice_nor_note_is_invalid", CARD, [door(body(answer={"choice": None, "note": None}), sx1, "body_invalid")], None),
sc("a_non_retraction_without_an_answer_is_invalid", CARD, [door(body(answer=None), sx1, "body_invalid")], None),
sc("the_second_door_down_is_unavailable_and_stores_nothing", CARD, [step("answer", x1, dict(sx1, door_down=True, retry_after_seconds=30), unavailable_doc(30)), ok(x1, sx2, "Counted", None)], "n2"),
sc("a_bad_body_is_refused_before_the_door_is_asked", CARD, [door(dict(x1, answerer="x"), dict(sx1, door_down=True, retry_after_seconds=30), "body_forbidden_field")], None),
sc("no_session_is_unauthenticated", CARD, [door(x1, srv("n1", None, T(2), None), "unauthenticated")], None),
sc("an_unknown_fork_is_refused_at_the_door", CARD, [door(body("no", NOTE, fork="gamecult-chat:question:nope"), sx1, "fork_unknown")], None),
sc("V2_stale_hash_is_refused_not_counted_and_stored_as_Refused", CARD, [rf(stale_body(), sx1, "stale_fork", c=CARD)], None),
@ -302,7 +306,7 @@ scen = [
sc("after_every_answer_is_retracted_a_fresh_answer_is_Counted_again", CARD, [X1, ok(RET("n1"), sr("n8"), "Retraction", "n1"), ok(x2, sx2, "Counted", None)], "n2"),
]
REASON_CODES = ["stale_fork", "not_a_decider", "fork_closed", "choice_invalid", "bad_retraction", "already_retracted"]
HTTP = {"unauthenticated": 401, "body_forbidden_field": 400, "body_unknown_field": 400, "body_invalid": 400, "fork_unknown": 404,
HTTP = {"unauthenticated": 401, "body_forbidden_field": 400, "body_unknown_field": 400, "body_invalid": 400, "fork_unknown": 404, "insufficient_scope": 403, "request_invalid": 400,
"stale_fork": 409, "not_a_decider": 403, "fork_closed": 409, "choice_invalid": 400, "bad_retraction": 400, "already_retracted": 409}
STORED_REFUSALS = []
for reason in REASON_CODES:
@ -323,6 +327,51 @@ cites = [
{"name": "steward_needs_no_citation", "answers": [], "message": cite("Steward", None), "admit": True},
]
for cz in cites: cz["messagePackHex"] = hx(cz["message"])
# ---------- transport: list, read, auth ----------
def fcard(n, status="open", **kw):
c = card(fork_id=f"gamecult-chat:question:q{n}", title=f"Fork {n}", order=n, status=status, **kw)
return c
def fbody(c, choice, aid_note):
return body(choice, aid_note, h=c["options_hash"], fork=c["fork_id"])
def fentry(c, answers=(), counted=None):
return {"schemaVersion": "gamecult.fork.entry.v0", "card": c, "record": record(counted, list(answers), c["options_hash"], c["fork_id"])}
q5 = fcard(5); q4 = fcard(4); q2 = fcard(2)
q3 = fcard(3, "closed", ruling="cultlib-gaps:resolution:question.q3.n1", ruled_from=["n1"]); q1 = fcard(1, "closed", ruling="cultlib-gaps:resolution:question.q1.n1")
a5 = da("Counted", None, None, fbody(q5, "no", NOTE), srv("n1", OP, T(2)))
a3 = da("Counted", None, None, fbody(q3, "yes", NOTE), srv("n1", OP, T(2)))
r3 = da("Refused", None, "fork_closed", fbody(q3, "no", NOTE), srv("n2", HM, T(4), "Steward"))
ENTRIES = [fentry(q5, [a5], "n1"), fentry(q4), fentry(q3, [a3, r3], "n1"), fentry(q2), fentry(q1)]
def lreq(mind="gamecult-chat", status=None, cursor=None, limit=10): return {"schemaVersion": "gamecult.fork.list_request.v0", "mind": mind, "status": status, "cursor": cursor, "limit": limit}
def judge_list(entries, ordinal, rq):
rows = sorted(entries, key=lambda e: -e["card"]["order"])
want = [e for e in rows if rq["status"] is None or (e["card"]["status"] == "open") == (rq["status"] == "open")]
if rq["cursor"] is not None: want = [e for e in want if e["card"]["order"] < int(rq["cursor"][1:])]
page = want[:rq["limit"]]
more = len(want) > len(page) and len(page) > 0
return {"schemaVersion": "gamecult.fork.list.v0", "mind": rq["mind"], "stamp": f"s{ordinal}",
"open_count": sum(e["card"]["status"] == "open" for e in rows), "recorded_count": sum(e["card"]["status"] == "closed" for e in rows),
"forks": page, "next_cursor": f"c{page[-1]['card']['order']}" if more else None}
def lstep(entries, ordinal, rq): r = judge_list(entries, ordinal, rq); return {"request": rq, "response": r, "responseHex": hx(r)}
LISTS = [
{"name": "newest_first_paged_open_only", "ordinal": 412, "entries": ENTRIES, "steps": [lstep(ENTRIES, 412, lreq(status="open", limit=2)), lstep(ENTRIES, 412, lreq(status="open", cursor="c4", limit=2))]},
{"name": "all_forks_one_page", "ordinal": 412, "entries": ENTRIES, "steps": [lstep(ENTRIES, 412, lreq(limit=50))]},
{"name": "recorded_only_paged", "ordinal": 412, "entries": ENTRIES, "steps": [lstep(ENTRIES, 412, lreq(status="recorded", limit=1)), lstep(ENTRIES, 412, lreq(status="recorded", cursor="c3", limit=1))]},
{"name": "limit_zero_is_the_count_and_stamp_only", "ordinal": 412, "entries": ENTRIES, "steps": [lstep(ENTRIES, 412, lreq(limit=0))]},
{"name": "a_mind_with_no_forks", "ordinal": 7, "entries": [], "steps": [lstep([], 7, lreq(mind="nibu", limit=10))]},
]
TOK = lambda aud, *sc: {"audience": aud, "scopes": list(sc)}
AUTH = [
("list_with_desk_read", "list", TOK("bifrost-desk", "desk.read"), "ok"), ("read_with_desk_read", "read", TOK("bifrost-desk", "desk.read"), "ok"),
("answer_with_desk_answer", "answer", TOK("bifrost-desk", "desk.answer"), "ok"), ("answer_with_both_scopes", "answer", TOK("bifrost-desk", "desk.read", "desk.answer"), "ok"),
("no_bearer_list", "list", None, "unauthenticated"), ("no_bearer_answer", "answer", None, "unauthenticated"),
("the_MAS_token_is_refused", "list", TOK("matrix-authentication-service", "openid", "profile"), "unauthenticated"),
("a_votes_token_cannot_list", "list", TOK("bifrost-votes", "votes.read"), "unauthenticated"),
("a_votes_token_cannot_read", "read", TOK("bifrost-votes", "votes.read"), "unauthenticated"),
("a_votes_token_cannot_answer", "answer", TOK("bifrost-votes", "votes.cast"), "unauthenticated"),
("desk_audience_with_a_votes_scope_only", "answer", TOK("bifrost-desk", "votes.cast"), "insufficient_scope"),
("desk_read_cannot_answer", "answer", TOK("bifrost-desk", "desk.read"), "insufficient_scope"),
("desk_answer_cannot_list", "list", TOK("bifrost-desk", "desk.answer"), "insufficient_scope"),
]
def bad(name, why, m, **kw): return dict({"name": name, "why": why, "message": m}, **kw)
fork = {
"provenance": "Rule source: /opt/commons/handoff/fork-desk-answer-binding-20261110.md (Heimdall), amended by the Persona briefs of 2026-11-10 (Eureka's fit check). Bytes spec-authored with msgpack-python (scripts/gen-governance-vectors.py); every runtime re-encodes `message` and must match messagePackHex. options_hash follows fork-card.md 'Options hash'; the vectors named heimdall_* are that file's, with its digests.",
@ -347,11 +396,16 @@ fork = {
("options_hash_of_another_card", "rule: options_hash equals the hash of the shown members (not expressible in the schema)", dict(card(), options_hash=STALE_H)),
]]},
"request": {"valid": [{"name": n, "message": m, "messagePackHex": hx(m)} for n, m in
[("choice_and_note", x1), ("choice_alone", pick), ("note_alone_clear_pick", words), ("retraction", retraction("n1"))]],
[("choice_and_note", x1), ("choice_alone", pick), ("note_alone_clear_pick", words), ("retraction", retraction("n1")),
("note_4000_ascii_bytes", body(None, "x" * 4000)), ("note_astral_4000_bytes", body(None, "\U0001F600" * 1000)),
("note_combining_4000_bytes", body(None, "e\u0301" * 1333 + "x"))]],
"invalid": [dict(bad(n, w, m), messagePackHex=hx(m)) for n, w, m in [
("answer_with_neither", "an answer object holds a choice, a note, or both", body(answer={"choice": None, "note": None})),
("blank_note", "a blank note is no answer", body(None, " \u00a0 ")),
("note_over_4000", "notes are at most 4000 characters", body(None, "x" * 4001)),
("note_over_4000", "notes are at most 4000 UTF-8 bytes", body(None, "x" * 4001)),
("note_multibyte_4001_bytes", "a note is counted in UTF-8 bytes: 1999 e-acute is 3998 bytes, plus three ASCII is 4001 (rule: not expressible in the schema, 2002 characters)", body(None, "\u00e9" * 1999 + "abc")),
("note_astral_4004_bytes", "1001 astral characters are 4004 bytes though only 1001 code points (rule: not expressible in the schema)", body(None, "\U0001F600" * 1001)),
("note_combining_4002_bytes", "e plus a combining acute is 3 bytes: 1334 of them are 4002 (rule: not expressible in the schema)", body(None, "e\u0301" * 1334)),
("options_hash_uppercase", "hash is lowercase hex", body("no", None, h=H.upper())),
("answerer_key", "answerer is server-set; the door answers body_forbidden_field", dict(x1, answerer=OP)),
("authority_key", "authority is server-set; the door answers body_forbidden_field", dict(x1, authority="Operator")),
@ -379,7 +433,35 @@ fork = {
]]},
"results": [{"name": r["name"], "httpStatus": r["httpStatus"], "message": r["message"], "messagePackHex": hx(r["message"])} for r in STORED_REFUSALS],
"doorRefusals": [{"name": c, "httpStatus": HTTP[c], "message": refusal_doc(c), "messagePackHex": hx(refusal_doc(c))} for c in TAIL],
"unavailable": [{"name": "second_door_down", "httpStatus": 503, "message": unavailable_doc(30), "messagePackHex": hx(unavailable_doc(30))},
{"name": "second_door_down_no_hint", "httpStatus": 503, "message": unavailable_doc(None), "messagePackHex": hx(unavailable_doc(None))}],
"rulingCites": cites,
"transport": {
"listRequest": {"valid": [{"name": "list_open_page", "message": lreq(status="open", limit=2), "messagePackHex": hx(lreq(status="open", limit=2))},
{"name": "list_next_page", "message": lreq(status="open", cursor="c4", limit=2), "messagePackHex": hx(lreq(status="open", cursor="c4", limit=2))},
{"name": "list_count_only", "message": lreq(limit=0), "messagePackHex": hx(lreq(limit=0))}],
"invalid": [dict(bad(n, w, m), messagePackHex=hx(m)) for n, w, m in [
("limit_51", "a page is at most 50 forks", lreq(limit=51)), ("limit_negative", "limit is 0 to 50", lreq(limit=-1)),
("status_all", "status is open, recorded or nil", lreq(status="all")), ("cursor_malformed", "a cursor is c<N>", lreq(cursor="next")),
("cursor_zero", "a cursor names a positive order", lreq(cursor="c0")), ("mind_empty", "a list names a Mind", lreq(mind="")),
("unknown_key", "closed document", dict(lreq(), sort="oldest"))]]},
"readRequest": {"valid": [{"name": "read_one", "message": {"schemaVersion": "gamecult.fork.read_request.v0", "fork_id": FID}, "messagePackHex": hx({"schemaVersion": "gamecult.fork.read_request.v0", "fork_id": FID})}],
"invalid": [dict(bad(n, w, m), messagePackHex=hx(m)) for n, w, m in [
("fork_id_empty", "a read names a fork", {"schemaVersion": "gamecult.fork.read_request.v0", "fork_id": ""})]]},
"entry": {"valid": [{"name": n, "message": e, "messagePackHex": hx(e)} for n, e in [("open_no_answers", ENTRIES[1]), ("open_counted", ENTRIES[0]), ("closed_with_ruling_and_a_refusal", ENTRIES[2])]],
"invalid": [dict(bad(n, w, m), messagePackHex=hx(m)) for n, w, m in [
("entry_without_record", "an entry holds the card and its record", {k: v for k, v in ENTRIES[0].items() if k != "record"}),
("record_of_another_fork", "rule: the record names the card's fork (not expressible in the schema)", dict(ENTRIES[0], record=dict(ENTRIES[0]["record"], fork_id="gamecult-chat:question:q9"))),
("record_under_another_hash", "rule: the record is under the card's options_hash (not expressible in the schema)", dict(ENTRIES[0], record=dict(ENTRIES[0]["record"], options_hash=STALE_H))),
("counted_answer_not_derived", "rule: counted_answer_id is the first live Counted or Revision answer under the card's hash (not expressible in the schema)", dict(ENTRIES[0], record=dict(ENTRIES[0]["record"], counted_answer_id=None))),
("card_hash_wrong", "rule: the server computes options_hash and a client recomputes it; a card with another hash is no card", dict(ENTRIES[1], card=dict(ENTRIES[1]["card"], options_hash=STALE_H), record=dict(ENTRIES[1]["record"], options_hash=STALE_H)))]]},
"listInvalid": [dict(bad(n, w, m), messagePackHex=hx(m)) for n, w, m in [
("next_cursor_malformed", "a cursor is c<N>", dict(LISTS[0]["steps"][0]["response"], next_cursor="more")),
("stamp_malformed", "a stamp is s<N>", dict(LISTS[0]["steps"][0]["response"], stamp="412")),
("count_negative", "counts are not negative", dict(LISTS[0]["steps"][0]["response"], open_count=-1))]],
"listScenarios": [{"name": l["name"], "ordinal": l["ordinal"], "entries": l["entries"], "steps": l["steps"]} for l in LISTS],
"authCases": [{"name": n, "route": r, "token": t, "expect": x} for n, r, t, x in AUTH],
},
"scenarios": [{"name": n, "card": c, "optionsHash": c["options_hash"], "steps": steps, "record": r, "recordHex": hx(r)} for n, c, steps, r in scen],
}
(OUT / "fork-card-vectors.json").write_text(json.dumps(fork, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

View file

@ -56,6 +56,7 @@ namespace GameCult.Networking.Tests
foreach (var item in a) Write(ref w, item);
break;
case JsonValue v when v.TryGetValue<bool>(out var b): w.Write(b); break;
case JsonValue v when v.TryGetValue<int>(out var i): w.Write(i); break;
case JsonValue v when v.TryGetValue<long>(out var l): w.Write(l); break;
case JsonValue v: w.Write(v.GetValue<string>()); break;
}
@ -238,11 +239,13 @@ namespace GameCult.Networking.Tests
foreach (var v in Fork[section]!["valid"]!.AsArray())
{
Assert.That(Errors(ForkSchema, def, v!["message"]), Is.Empty, S(v["name"]));
Assert.That(NoteRuleErrors(def, v["message"]), Is.Empty, S(v["name"]));
Assert.That(HexOf(v["message"]), Is.EqualTo(S(v["messagePackHex"])), S(v["name"]));
var decoded = JsonNode.Parse(MessagePackSerializer.ConvertToJson(Convert.FromHexString(S(v["messagePackHex"]))))!;
Assert.That(JsonNode.DeepEquals(decoded, v["message"]), Is.True, S(v["name"]));
}
var schema = JsonNode.Parse(File.ReadAllText(Path.Combine(RepoRoot(), "contracts", "cultnet", ForkSchema)))!;
IEnumerable<string> codesOfRefusal() => schema["$defs"]!["refusal"]!["properties"]!["code"]!["enum"]!.AsArray().Select(S);
IEnumerable<string> Codes(string def) => schema["$defs"]![def]!["properties"]!["code"]!["enum"]!.AsArray().Select(S).OrderBy(x => x, StringComparer.Ordinal);
Assert.That(Fork["results"]!.AsArray().Select(r => S(r!["name"])).OrderBy(x => x, StringComparer.Ordinal), Is.EqualTo(Codes("deskAnswerRefused")));
foreach (var v in Fork["results"]!.AsArray())
@ -252,6 +255,13 @@ namespace GameCult.Networking.Tests
Assert.That(v["message"]!["card"] is not null, Is.EqualTo(S(v["name"]) == "stale_fork"), "only a stale refusal shows the new fork");
}
Assert.That(Fork["doorRefusals"]!.AsArray().Select(r => S(r!["name"])).OrderBy(x => x, StringComparer.Ordinal), Is.EqualTo(Codes("refusal")));
foreach (var v in Fork["unavailable"]!.AsArray())
{
Assert.That(Errors(ForkSchema, "unavailable", v!["message"]), Is.Empty, S(v["name"]));
Assert.That(HexOf(v["message"]), Is.EqualTo(S(v["messagePackHex"])), S(v["name"]));
Assert.That(v["httpStatus"]!.GetValue<int>(), Is.EqualTo(503));
Assert.That(codesOfRefusal(), Does.Not.Contain("unavailable"), "unavailable is kept apart from the refusal set");
}
foreach (var v in Fork["doorRefusals"]!.AsArray())
{
Assert.That(Errors(ForkSchema, "refusal", v!["message"]), Is.Empty, S(v["name"]));
@ -267,11 +277,18 @@ namespace GameCult.Networking.Tests
foreach (var (section, def) in new[] { ("request", "answerRequest"), ("deskAnswer", "deskAnswer") })
foreach (var v in Fork[section]!["invalid"]!.AsArray())
{
Assert.That(Errors(ForkSchema, def, v!["message"]), Is.Not.Empty, $"{S(v["name"])}: {S(v["why"])}");
Assert.That(Errors(ForkSchema, def, v!["message"]).Count > 0 || NoteRuleErrors(def, v["message"]).Any(), Is.True, $"{S(v["name"])}: {S(v["why"])}");
Assert.That(HexOf(v["message"]), Is.EqualTo(S(v["messagePackHex"])), S(v["name"]));
}
}
// Rules a JSON Schema cannot say: a note is at most 4000 UTF-8 bytes (maxLength counts code points and is only the looser bound).
private static IEnumerable<string> NoteRuleErrors(string def, JsonNode? message)
{
var note = def switch { "answerRequest" => message?["answer"]?["note"], "deskAnswer" => message?["note"], _ => null };
if (note is not null && Encoding.UTF8.GetByteCount(S(note)) > 4000) yield return "note is over 4000 UTF-8 bytes";
}
private static readonly Dictionary<string, string> Tails = new()
{
["unauthenticated"] = "a verified session is required",
@ -336,7 +353,8 @@ namespace GameCult.Networking.Tests
if (s["answerer"] is null) response = Door("unauthenticated");
else if (HasKey(b, "answerer", "authority")) response = Door("body_forbidden_field");
else if (b.Any(kv => !RequestKeys.Contains(kv.Key)) || (b["answer"] is JsonObject ao && ao.Any(kv => kv.Key is not ("choice" or "note")))) response = Door("body_unknown_field");
else if (Errors(ForkSchema, "answerRequest", b).Count > 0 || (!retracted && b["answer"] is null)) response = Door("body_invalid");
else if (Errors(ForkSchema, "answerRequest", b).Count > 0 || NoteRuleErrors("answerRequest", b).Any() || (!retracted && b["answer"] is null)) response = Door("body_invalid");
else if (s["door_down"] is not null) response = new JsonObject { ["schemaVersion"] = "gamecult.fork.unavailable.v0", ["code"] = "unavailable", ["error"] = "unavailable: the answer path is down, try again", ["retryAfterSeconds"] = Clone(s["retry_after_seconds"]) };
else if (S(b["fork_id"]) != S(card["fork_id"])) response = Door("fork_unknown");
else if (S(b["options_hash"]) != HashOf(card)) response = Refuse("stale_fork");
else if (!deciders.Contains(S(s["answerer"]))) response = Refuse("not_a_decider");
@ -369,7 +387,7 @@ namespace GameCult.Networking.Tests
{
var seen = new HashSet<string>();
var doorRefusals = 0;
var door = new HashSet<string> { "unauthenticated", "body_forbidden_field", "body_unknown_field", "body_invalid", "fork_unknown" };
var door = new HashSet<string> { "unauthenticated", "body_forbidden_field", "body_unknown_field", "body_invalid", "fork_unknown", "unavailable" };
foreach (var sc in Fork["scenarios"]!.AsArray())
{
var name = S(sc!["name"]);
@ -387,7 +405,7 @@ namespace GameCult.Networking.Tests
{
var r = step!["response"];
if (r is null) continue;
Assert.That(Errors(ForkSchema, "answerResult", r).Count == 0 || Errors(ForkSchema, "refusal", r).Count == 0, Is.True, name);
Assert.That(Errors(ForkSchema, "answerResult", r).Count == 0 || Errors(ForkSchema, "refusal", r).Count == 0 || Errors(ForkSchema, "unavailable", r).Count == 0, Is.True, name);
if (r["code"] is not null)
{
seen.Add(S(r["code"]));
@ -402,7 +420,7 @@ namespace GameCult.Networking.Tests
foreach (var a in sc["record"]!["answers"]!.AsArray()) seen.Add(S(a!["outcome"]));
}
Assert.That(doorRefusals, Is.GreaterThanOrEqualTo(8));
foreach (var want in new[] { "Counted", "Revision", "Retraction", "Refused", "unauthenticated", "body_forbidden_field", "body_unknown_field", "body_invalid", "fork_unknown", "stale_fork",
foreach (var want in new[] { "Counted", "Revision", "Retraction", "Refused", "unauthenticated", "body_forbidden_field", "body_unknown_field", "body_invalid", "fork_unknown", "unavailable", "stale_fork",
"not_a_decider", "fork_closed", "choice_invalid", "bad_retraction", "already_retracted" })
Assert.That(seen, Does.Contain(want));
}
@ -425,5 +443,107 @@ namespace GameCult.Networking.Tests
Assert.That(AdmitRuling(c["message"]!, c["answers"]!.AsArray()), Is.EqualTo(c["admit"]!.GetValue<bool>()), S(c["name"]));
}
}
// ---- transport: list, read, auth (fork-card.md "Transport") ----
private static IEnumerable<string> EntryRuleErrors(JsonNode e)
{
var card = e["card"]!; var record = e["record"]!;
foreach (var error in CardRuleErrors(card)) yield return error;
if (S(record["fork_id"]) != S(card["fork_id"])) yield return "record of another fork";
if (S(record["options_hash"]) != S(card["options_hash"])) yield return "record under another hash";
var answers = record["answers"]!.AsArray();
var counted = answers.Where(a => (S(a!["outcome"]) is "Counted" or "Revision") && S(a["options_hash"]) == S(card["options_hash"])
&& !answers.Any(r => S(r!["outcome"]) == "Retraction" && S(r["retracts"]) == S(a["answer_id"]))).Select(a => S(a!["answer_id"])).FirstOrDefault();
if ((record["counted_answer_id"] is null ? null : S(record["counted_answer_id"])) != counted) yield return "counted_answer_id is not derived";
}
// The reference list judge: newest first by card order, status filter, cursor c<N> = cards below order N, a page of limit, counts over the whole set.
private static JsonNode JudgeList(JsonArray entries, long ordinal, JsonNode request)
{
long Order(JsonNode? e) => e!["card"]!["order"]!.GetValue<long>();
var rows = entries.OrderByDescending(Order).ToList();
var want = rows.Where(e => request["status"] is null || (S(e!["card"]!["status"]) == "open") == (S(request["status"]) == "open")).ToList();
if (request["cursor"] is not null) { var below = long.Parse(S(request["cursor"])[1..]); want = want.Where(e => Order(e) < below).ToList(); }
var page = want.Take(request["limit"]!.GetValue<int>()).ToList();
var more = want.Count > page.Count && page.Count > 0;
return new JsonObject
{
["schemaVersion"] = "gamecult.fork.list.v0", ["mind"] = Clone(request["mind"]), ["stamp"] = $"s{ordinal}",
["open_count"] = rows.Count(e => S(e!["card"]!["status"]) == "open"), ["recorded_count"] = rows.Count(e => S(e!["card"]!["status"]) == "closed"),
["forks"] = new JsonArray(page.Select(Clone).ToArray()), ["next_cursor"] = more ? JsonValue.Create($"c{Order(page[^1])}") : null
};
}
// Bearer, audience, scope, in that order: a votes.* token fails at the audience and a desk token without the route's scope fails at the scope.
private static string AuthJudge(string route, JsonNode? token)
{
if (token is null || S(token["audience"]) != "bifrost-desk") return "unauthenticated";
var need = route == "answer" ? "desk.answer" : "desk.read";
return token["scopes"]!.AsArray().Any(x => S(x) == need) ? "ok" : "insufficient_scope";
}
[Test]
public void ForkTransport_RequestsAndEntriesValidateEncodeToTheVectorBytes_AndEveryNegativeIsRefused()
{
var t = Fork["transport"]!;
foreach (var (section, def) in new[] { ("listRequest", "listRequest"), ("readRequest", "readRequest"), ("entry", "entry") })
{
foreach (var v in t[section]!["valid"]!.AsArray())
{
Assert.That(Errors(ForkSchema, def, v!["message"]), Is.Empty, S(v["name"]));
if (def == "entry") Assert.That(EntryRuleErrors(v["message"]!), Is.Empty, S(v["name"]));
Assert.That(HexOf(v["message"]), Is.EqualTo(S(v["messagePackHex"])), S(v["name"]));
}
foreach (var v in t[section]!["invalid"]!.AsArray())
{
Assert.That(Errors(ForkSchema, def, v!["message"]).Count > 0 || (def == "entry" && EntryRuleErrors(v["message"]!).Any()), Is.True, $"{S(v["name"])}: {S(v["why"])}");
Assert.That(HexOf(v["message"]), Is.EqualTo(S(v["messagePackHex"])), S(v["name"]));
}
}
foreach (var v in t["listInvalid"]!.AsArray())
{
Assert.That(Errors(ForkSchema, "list", v!["message"]), Is.Not.Empty, $"{S(v["name"])}: {S(v["why"])}");
Assert.That(HexOf(v["message"]), Is.EqualTo(S(v["messagePackHex"])), S(v["name"]));
}
}
[Test]
public void ForkTransport_EveryListRequest_ReplaysToTheVectorsResponse_NewestFirst_PagedByTheCursor()
{
foreach (var sc in Fork["transport"]!["listScenarios"]!.AsArray())
{
var name = S(sc!["name"]);
var entries = sc["entries"]!.AsArray();
foreach (var e in entries) Assert.That(EntryRuleErrors(e!), Is.Empty, name);
JsonNode? previous = null;
foreach (var step in sc["steps"]!.AsArray())
{
var response = JudgeList(entries, sc["ordinal"]!.GetValue<long>(), step!["request"]!);
Assert.That(JsonNode.DeepEquals(response, step["response"]), Is.True, $"{name}: {response.ToJsonString()}");
Assert.That(Errors(ForkSchema, "list", response), Is.Empty, name);
Assert.That(HexOf(response), Is.EqualTo(S(step["responseHex"])), name);
var orders = response["forks"]!.AsArray().Select(f => f!["card"]!["order"]!.GetValue<long>()).ToList();
Assert.That(orders, Is.Ordered.Descending, name);
if (previous is not null) Assert.That(S(step["request"]!["cursor"]), Is.EqualTo(S(previous["next_cursor"])), $"{name}: the second request follows the first page's cursor");
previous = response;
}
}
}
[Test]
public void ForkTransport_Auth_BearerThenAudienceThenScope_AVotesTokenTouchesNothing()
{
var schema = JsonNode.Parse(File.ReadAllText(Path.Combine(RepoRoot(), "contracts", "cultnet", ForkSchema)))!;
var codes = schema["$defs"]!["refusal"]!["properties"]!["code"]!["enum"]!.AsArray().Select(S).ToList();
var seen = new HashSet<string>();
foreach (var c in Fork["transport"]!["authCases"]!.AsArray())
{
var got = AuthJudge(S(c!["route"]), c["token"]);
Assert.That(got, Is.EqualTo(S(c["expect"])), S(c["name"]));
if (got != "ok") Assert.That(codes, Does.Contain(got), S(c["name"]));
seen.Add(S(c["route"]) + ":" + got);
}
Assert.That(seen, Does.Contain("list:insufficient_scope").And.Contain("answer:insufficient_scope").And.Contain("read:unauthenticated").And.Contain("answer:ok"));
}
}
}