@cordfuse/politik 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/EXECUTION.md +766 -0
  2. package/LICENSE +21 -0
  3. package/POLITIK-ARCHITECTURE.md +676 -0
  4. package/PROTOCOLS.md +1106 -0
  5. package/README.md +193 -0
  6. package/RESEARCH.md +475 -0
  7. package/RUNTIME.md +1355 -0
  8. package/bin/politik.js +31 -0
  9. package/docs/adr/0001-chamber-transport.md +67 -0
  10. package/docs/adr/0002-charter-schema.md +142 -0
  11. package/docs/adr/0003-state-json-schema.md +134 -0
  12. package/docs/adr/0004-motion-enactment.md +215 -0
  13. package/docs/adr/0005-hansard-format.md +171 -0
  14. package/docs/adr/0006-protocol-behavioral-enforcement.md +89 -0
  15. package/docs/adr/0007-protocol-mechanics.md +100 -0
  16. package/docs/adr/0008-session-storage.md +108 -0
  17. package/docs/adr/0009-match-primitive.md +74 -0
  18. package/package.json +55 -0
  19. package/protocols/CONTRIBUTING.md +130 -0
  20. package/protocols/adversarial-collaboration.yml +28 -0
  21. package/protocols/corporate.yml +35 -0
  22. package/protocols/elimination-tournament.yml +41 -0
  23. package/protocols/emergency-response-ics.yml +27 -0
  24. package/protocols/jury-deliberation.yml +32 -0
  25. package/protocols/monarchy.yml +31 -0
  26. package/protocols/parliamentary.yml +66 -0
  27. package/protocols/peer-review.yml +44 -0
  28. package/protocols/republic.yml +36 -0
  29. package/protocols/socialism-collective.yml +31 -0
  30. package/protocols/solo.yml +32 -0
  31. package/src/actors.ts +742 -0
  32. package/src/agents.ts +318 -0
  33. package/src/canon.ts +173 -0
  34. package/src/capability.ts +336 -0
  35. package/src/charter.ts +545 -0
  36. package/src/cli.ts +2174 -0
  37. package/src/conflict.ts +211 -0
  38. package/src/containment.ts +155 -0
  39. package/src/crisis.ts +381 -0
  40. package/src/division.ts +609 -0
  41. package/src/doctor.ts +168 -0
  42. package/src/election.ts +233 -0
  43. package/src/envelope.ts +223 -0
  44. package/src/escalation.ts +320 -0
  45. package/src/fault.ts +241 -0
  46. package/src/federation.ts +299 -0
  47. package/src/git.ts +163 -0
  48. package/src/hansard.ts +201 -0
  49. package/src/heartbeat.ts +282 -0
  50. package/src/index.ts +43 -0
  51. package/src/init.ts +396 -0
  52. package/src/integrity.ts +153 -0
  53. package/src/ledger.ts +341 -0
  54. package/src/lockfs.ts +58 -0
  55. package/src/projection.ts +293 -0
  56. package/src/prorogation.ts +307 -0
  57. package/src/protocol-sdk.ts +248 -0
  58. package/src/protocol.ts +241 -0
  59. package/src/providers/github.ts +347 -0
  60. package/src/quorum.ts +137 -0
  61. package/src/runner.ts +534 -0
  62. package/src/scm.ts +142 -0
  63. package/src/spawn.ts +160 -0
  64. package/src/standings.ts +143 -0
  65. package/src/state.ts +179 -0
  66. package/src/templates/parliamentary.ts +359 -0
  67. package/src/tournament.ts +200 -0
  68. package/src/transport.ts +190 -0
  69. package/src/tree.ts +371 -0
@@ -0,0 +1,359 @@
1
+ /**
2
+ * Parliamentary protocol templates.
3
+ *
4
+ * Charter, role definitions, Standing Orders and the GitHub label taxonomy for
5
+ * protocol #1. These are what a Speaker starts from — editable prose, not
6
+ * engine configuration.
7
+ *
8
+ * Role files describe a *constituency* in Parliamentary vocabulary while naming
9
+ * the CANON role they map to. The engine reads the CANON role; the human reads
10
+ * the title. That separation is the whole point of the protocol layer.
11
+ *
12
+ * Attribution: Steve Krisjanovs, Cordfuse
13
+ */
14
+
15
+ import type { Role } from '../canon.ts';
16
+ import type { FileWrite } from '../scm.ts';
17
+
18
+ /* -------------------------------------------------------------------------- */
19
+ /* Charter */
20
+ /* -------------------------------------------------------------------------- */
21
+
22
+ export interface CharterTemplateOptions {
23
+ readonly quorum?: number;
24
+ readonly inherits_from?: string | null;
25
+ readonly speaker?: string;
26
+ /** Protocol override points (ADR-0007). Defaults reproduce Parliament. */
27
+ readonly resolution?: string;
28
+ readonly exit?: string;
29
+ readonly termination?: string;
30
+ readonly escalation?: string;
31
+ /** Protocol name for the frontmatter. Defaults to parliamentary. */
32
+ readonly protocol?: string;
33
+ }
34
+
35
+ /**
36
+ * A Parliamentary CHARTER.md a Speaker can edit and drop.
37
+ *
38
+ * `merge_strategy` is deliberately `merge_commit`: Parliamentary declares
39
+ * `record_mode: distributed`, and ADR-0002 rule 5 rejects squash under a
40
+ * distributed record mode because squash destroys the per-commit attribution
41
+ * that record mode guarantees.
42
+ */
43
+ export const charterTemplate = (options: CharterTemplateOptions = {}): string => {
44
+ const quorum = options.quorum ?? 2;
45
+ const inherits = options.inherits_from ?? null;
46
+ const resolution = options.resolution ?? 'majority';
47
+ const exit = options.exit ?? 'division';
48
+ const termination = options.termination ?? 'objective';
49
+ const escalation = options.escalation ?? 'enabled';
50
+ const protocol = options.protocol ?? 'parliamentary';
51
+
52
+ return `---
53
+ charter_version: 1.0.0
54
+ protocol: ${protocol}
55
+ inherits_from: ${inherits === null ? 'null' : inherits}
56
+
57
+ session:
58
+ quorum: ${quorum} # minimum actors for a valid Division
59
+ escalation: ${escalation} # 'disabled' = no Point of Order (ADR-0006)
60
+ heartbeat_timeout_hours: 4 # no Hansard commit in this window => STALE
61
+ deadline: null # ISO-8601 wall-clock ceiling, or null
62
+ merge_strategy: merge_commit # squash is invalid under record_mode: distributed
63
+ assent: AUTHORITY # only the Speaker enacts a carried Motion
64
+
65
+ endurance:
66
+ max_motions: null
67
+ max_cost_usd: null
68
+
69
+ ledger:
70
+ enabled: true
71
+ visibility: public
72
+ path: LEDGER.md
73
+
74
+ minimum_cast: # enforced at Writ Drop; hard fail
75
+ AUTHORITY: 1
76
+ OPERATOR: 1
77
+
78
+ domain_veto: []
79
+
80
+ mechanics: # protocol override points (ADR-0007)
81
+ resolution: ${resolution} # majority | supermajority | unanimity
82
+ exit: ${exit} # division | elimination | none
83
+ termination: ${termination} # objective | last-standing | verdict
84
+
85
+ fault_handling:
86
+ # PATH_A auto-recovery. A rate limit or a brief outage retries without waking
87
+ # the Speaker; anything a human must fix escalates immediately.
88
+ auto_retry_max: 3
89
+ auto_retry_delay_minutes: 5
90
+
91
+ governance:
92
+ # Constitutional-capture mitigations. A supermajority of OPERATOR actors can
93
+ # suspend the session against AUTHORITY; a designated witness can do it alone,
94
+ # which is what covers the case where the bench itself has been captured.
95
+ consensus_suspension:
96
+ enabled: true
97
+ threshold: 0.75 # fraction of OPERATOR actors who must concur
98
+ witness_council:
99
+ enabled: false # set true and name roles to seat constitutional witnesses
100
+ roles: []
101
+
102
+ constituencies:
103
+ - role: AUTHORITY # Speaker — human, always
104
+ slots: 1
105
+ auto_demotion: false
106
+
107
+ - role: OPERATOR # Ministers
108
+ slots: 2
109
+ auto_demotion: false
110
+ hard_skills:
111
+ required: []
112
+ excluded: []
113
+ model:
114
+ required: null
115
+ preferred: null
116
+ knowledge_cutoff_minimum: null
117
+ mandate_alignment: null
118
+
119
+ - role: MEMBER # Backbenchers
120
+ slots: 2
121
+ auto_demotion: false
122
+ ---
123
+
124
+ # Standing Orders
125
+
126
+ The prose below is read by actors, not parsed by the engine. Everything the
127
+ engine enforces is in the frontmatter above.
128
+
129
+ ## 1. The House
130
+
131
+ This Parliament sits to deliver the business set out in the Order Paper. The
132
+ Speaker is constitutionally present, not operationally present: they drop the
133
+ Writ, rule on Points of Order, and prorogue. They do not do the work.
134
+
135
+ ## 2. Motions
136
+
137
+ Any Minister may table a Motion. A Motion is a pull request; its body states
138
+ what is proposed and why. A Motion that changes the Charter must say so in its
139
+ first line.
140
+
141
+ ## 3. Divisions
142
+
143
+ A Motion carries when it satisfies quorum and no Veto stands. A Division is a
144
+ review. Abstention is not a vote and does not count toward quorum.
145
+
146
+ ## 4. Points of Order
147
+
148
+ Any actor may raise a Point of Order when the correct action requires a
149
+ judgement the Charter does not settle. The sitting suspends. The Speaker rules;
150
+ the ruling is committed and permanent.
151
+
152
+ Do not proceed on a question you cannot resolve. Raising a Point of Order is
153
+ always in order; guessing is not.
154
+
155
+ ## 5. The Hansard
156
+
157
+ The Hansard is append-only. No actor edits an entry once committed, including
158
+ their own. Work that is not committed did not happen.
159
+
160
+ ## 6. Conduct
161
+
162
+ Debate the Motion, not the Member. Bad-faith escalation — a Point of Order
163
+ citing a violation that does not appear in the record — is itself a Standing
164
+ Orders violation.
165
+ `;
166
+ };
167
+
168
+ /* -------------------------------------------------------------------------- */
169
+ /* Roles */
170
+ /* -------------------------------------------------------------------------- */
171
+
172
+ interface RoleTemplate {
173
+ readonly file: string;
174
+ readonly canon: Role;
175
+ readonly title: string;
176
+ readonly body: string;
177
+ }
178
+
179
+ const ROLE_TEMPLATES: readonly RoleTemplate[] = [
180
+ {
181
+ file: 'speaker.md',
182
+ canon: 'AUTHORITY',
183
+ title: 'Speaker',
184
+ body: `The constitutional authority of this Parliament. **Always human — the
185
+ Charter cannot declare a machine as Speaker, and a Charter that does fails Writ
186
+ Drop validation.**
187
+
188
+ The Speaker is present, not operational. They do not table Motions or write
189
+ code.
190
+
191
+ **Duties**
192
+
193
+ - Drop the Writ and define the Standing Orders
194
+ - Rule on Points of Order; the ruling is committed and permanent
195
+ - Grant Assent to carried Motions
196
+ - Prorogue the Parliament
197
+
198
+ **Verbs:** all, including ASSENT, VETO, PROMOTE, DEMOTE, HIRE, FIRE, EXPEL,
199
+ SUSPEND, DISSOLVE.
200
+
201
+ **Why human.** The failure mode of a corrupt authority requires accountability
202
+ that only a person can bear. A machine that captures a session cannot be held
203
+ responsible for it.`,
204
+ },
205
+ {
206
+ file: 'deputy-speaker.md',
207
+ canon: 'DELEGATE',
208
+ title: 'Deputy Speaker',
209
+ body: `Pre-delegated proxy for the Speaker. May be human or machine.
210
+
211
+ Acts with the Speaker's authority where the Charter grants it, and only there. A
212
+ Deputy Speaker may formally dispute an action of the Speaker before it takes
213
+ effect: the challenged action is logged and paused. The Speaker still prevails
214
+ after the window — but the challenge is on the permanent record, which is what
215
+ makes bad-faith authority visible.
216
+
217
+ **Verbs:** as granted by the Charter; typically all but DISSOLVE.`,
218
+ },
219
+ {
220
+ file: 'minister.md',
221
+ canon: 'OPERATOR',
222
+ title: 'Minister',
223
+ body: `Elevated trust, broad portfolio. Human or machine.
224
+
225
+ Ministers do the substantive work of the Parliament: they table Motions, carry
226
+ out the business on the Order Paper, and vote in Divisions.
227
+
228
+ **Duties**
229
+
230
+ - Table Motions and see them through Division
231
+ - Review Motions tabled by others in good faith
232
+ - Raise a Point of Order rather than act beyond your verbs
233
+
234
+ **Verbs:** READ, WRITE, VOTE, ESCALATE, SPAWN. Not ASSENT — the Division
235
+ decides, the Speaker enacts.`,
236
+ },
237
+ {
238
+ file: 'backbencher.md',
239
+ canon: 'MEMBER',
240
+ title: 'Backbencher',
241
+ body: `Standard trust, scoped verbs. Human or machine.
242
+
243
+ Backbenchers contribute to the business and vote in Divisions, but hold a
244
+ narrower mandate than Ministers. A Backbencher whose work consistently exceeds
245
+ their mandate is a candidate for promotion — recorded, with the Hansard as the
246
+ evidence.
247
+
248
+ **Verbs:** READ, VOTE, ESCALATE. WRITE where the Charter grants it.`,
249
+ },
250
+ {
251
+ file: 'gallery.md',
252
+ canon: 'OBSERVER',
253
+ title: 'Gallery',
254
+ body: `Read-only. No floor rights. Human or machine.
255
+
256
+ The Gallery sees everything and changes nothing. Useful for auditors, for
257
+ humans following a session they do not participate in, and for agents gathering
258
+ context for a later sitting.
259
+
260
+ A Charter may grant a specific Gallery member the right to file a
261
+ CONSTITUTIONAL_CRISIS escalation. That is the one exception to "no floor
262
+ rights", and it exists so that capture of the House can be reported by someone
263
+ outside it.
264
+
265
+ **Verbs:** READ.`,
266
+ },
267
+ ];
268
+
269
+ /** Role definition files for a Parliamentary session repo. */
270
+ export const roleTemplates = (): readonly FileWrite[] =>
271
+ ROLE_TEMPLATES.map((role) => ({
272
+ path: `roles/${role.file}`,
273
+ content: `# ${role.title}
274
+
275
+ **CANON role:** \`${role.canon}\`
276
+ **Protocol:** parliamentary
277
+
278
+ ${role.body}
279
+ `,
280
+ }));
281
+
282
+ /* -------------------------------------------------------------------------- */
283
+ /* Label taxonomy */
284
+ /* -------------------------------------------------------------------------- */
285
+
286
+ export interface LabelSpec {
287
+ readonly name: string;
288
+ readonly color: string;
289
+ readonly description: string;
290
+ }
291
+
292
+ /**
293
+ * GitHub label taxonomy for a Parliamentary session.
294
+ *
295
+ * Labels are protocol vocabulary — a human scanning the issue list should read
296
+ * Parliamentary terms. The CANON primitive each maps to is stated in the
297
+ * description so the mapping is never guesswork.
298
+ */
299
+ export const LABEL_TAXONOMY: readonly LabelSpec[] = Object.freeze([
300
+ { name: 'motion', color: '0E8A16', description: 'MOTION — tabled business' },
301
+ { name: 'division', color: '1D76DB', description: 'DIVISION — a vote is called' },
302
+ { name: 'point-of-order', color: 'B60205', description: 'ESCALATION — awaiting a Speaker ruling' },
303
+ { name: 'ruling', color: '5319E7', description: 'A Speaker ruling on a Point of Order' },
304
+ { name: 'constitutional-crisis', color: '000000', description: 'SUSPENSION — cause CONSTITUTIONAL_CRISIS; external review required' },
305
+ { name: 'fault', color: 'D93F0B', description: 'SESSION_FAULT — an action failed' },
306
+ { name: 'fault-critical', color: '990000', description: 'SESSION_FAULT_CRITICAL — irrecoverable' },
307
+ { name: 'committee', color: 'FBCA04', description: 'SPAWN — referred to a sub-session' },
308
+ { name: 'politik:notification', color: 'C5DEF5', description: 'Speaker notification — not business of the House' },
309
+ ]);
310
+
311
+ /* -------------------------------------------------------------------------- */
312
+ /* Order Paper */
313
+ /* -------------------------------------------------------------------------- */
314
+
315
+ /**
316
+ * Order Paper — the business before the House, as a GitHub Projects board.
317
+ *
318
+ * A Milestone is a sitting: the business intended for one continuous stretch of
319
+ * the proceeding. Closing the Milestone is part of prorogation.
320
+ */
321
+ export const orderPaperTemplate = (): string => `# ORDER PAPER
322
+
323
+ The business before this Parliament, in the order it is to be taken.
324
+
325
+ Mirrored as a GitHub Project board. Columns map to Motion state:
326
+
327
+ | Column | Meaning | CANON |
328
+ |---|---|---|
329
+ | Notice Paper | Proposed, not yet tabled | — |
330
+ | Tabled | Motion open | MOTION |
331
+ | In Division | Review requested | DIVISION |
332
+ | Awaiting Assent | Carried, not yet enacted | ASSENT pending |
333
+ | Enacted | Merged | ASSENT |
334
+ | Withdrawn | Closed without enactment | — |
335
+ | Point of Order | Suspended pending a ruling | ESCALATION |
336
+
337
+ A **Milestone** is a sitting. Its closure is part of prorogation, and the
338
+ prorogation workflow surfaces the milestone id for the caller to close.
339
+
340
+ ## Business
341
+
342
+ 1. _Add the first item of business here._
343
+ `;
344
+
345
+ /* -------------------------------------------------------------------------- */
346
+ /* Bundle */
347
+ /* -------------------------------------------------------------------------- */
348
+
349
+ /**
350
+ * The full Parliamentary template set, ready to commit into a session repo
351
+ * alongside the files the initializer already writes.
352
+ */
353
+ export const parliamentaryTemplates = (
354
+ options: CharterTemplateOptions = {},
355
+ ): readonly FileWrite[] => [
356
+ { path: 'CHARTER.md', content: charterTemplate(options) },
357
+ { path: 'ORDER-PAPER.md', content: orderPaperTemplate() },
358
+ ...roleTemplates(),
359
+ ];
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Tournament — the MATCH primitive and pairing (ADR-0009).
3
+ *
4
+ * A Politik Division is an N-actor vote on a Motion; it has no notion of a
5
+ * contest between two named parties, so the 1v1-match formats (Swiss,
6
+ * round-robin, single-elimination) had nothing to pair. MATCH is the additive
7
+ * primitive that supplies it: a contest between two contestants that resolves to
8
+ * a winner. Pairing generates a round of MATCHes from the field and the standings;
9
+ * reporting a result closes one; standings (scoring, `standings.ts`) reads the
10
+ * results the same way it reads Division outcomes.
11
+ *
12
+ * Pure, like the rest of the governance core: these functions produce entries
13
+ * and pairings; the caller commits them.
14
+ *
15
+ * Attribution: Steve Krisjanovs, Cordfuse
16
+ */
17
+
18
+ import { appendEntry, parseEntries, type HansardEntry } from './hansard.ts';
19
+ import { standings, type Standing } from './standings.ts';
20
+
21
+ export type PairingFormat = 'swiss' | 'round-robin' | 'single-elim';
22
+
23
+ export const isPairingFormat = (v: unknown): v is PairingFormat =>
24
+ v === 'swiss' || v === 'round-robin' || v === 'single-elim';
25
+
26
+ /** A proposed contest. `b` null is a bye — `a` advances unopposed. */
27
+ export interface Pairing {
28
+ readonly a: string;
29
+ readonly b: string | null;
30
+ }
31
+
32
+ export interface Match {
33
+ readonly id: string;
34
+ readonly round: number;
35
+ readonly a: string;
36
+ readonly b: string | null;
37
+ readonly winner: string | null;
38
+ }
39
+
40
+ class TournamentError extends Error {}
41
+ export { TournamentError };
42
+
43
+ const pairKey = (a: string, b: string): string => [a, b].sort().join('|');
44
+ const matchId = (round: number, a: string, b: string | null): string => `r${round}-${a}-${b ?? 'bye'}`;
45
+
46
+ /* -------------------------------------------------------------------------- */
47
+ /* Reading the record */
48
+ /* -------------------------------------------------------------------------- */
49
+
50
+ /** Every MATCH on the record, with its result if one has been reported. */
51
+ export const matches = (hansard: string): readonly Match[] => {
52
+ const created = new Map<string, { round: number; a: string; b: string | null }>();
53
+ const winners = new Map<string, string>();
54
+
55
+ for (const entry of parseEntries(hansard)) {
56
+ const id = entry.fields['Match'];
57
+ if (id === undefined) continue;
58
+ if (entry.type === 'MATCH_CREATED') {
59
+ const b = entry.fields['B'];
60
+ created.set(id, {
61
+ round: Number(entry.fields['Round'] ?? '0'),
62
+ a: entry.fields['A'] ?? '',
63
+ b: b === undefined || b === 'bye' ? null : b,
64
+ });
65
+ } else if (entry.type === 'MATCH_DECIDED') {
66
+ const w = entry.fields['Winner'];
67
+ if (w !== undefined) winners.set(id, w);
68
+ }
69
+ }
70
+
71
+ return [...created.entries()].map(([id, m]) => ({
72
+ id, round: m.round, a: m.a, b: m.b, winner: winners.get(id) ?? null,
73
+ }));
74
+ };
75
+
76
+ /** Pairs already contested, so a format never rematches them. */
77
+ const playedPairs = (played: readonly Match[]): Set<string> => {
78
+ const set = new Set<string>();
79
+ for (const m of played) if (m.b !== null) set.add(pairKey(m.a, m.b));
80
+ return set;
81
+ };
82
+
83
+ /* -------------------------------------------------------------------------- */
84
+ /* Pairing */
85
+ /* -------------------------------------------------------------------------- */
86
+
87
+ /**
88
+ * The field for the next round, by format:
89
+ * - single-elim: only the still-undefeated (losses === 0); the bracket narrows
90
+ * by loss, so no cull is needed — a defeated contestant is simply never paired
91
+ * again. One left undefeated is the champion (returns no pairings).
92
+ * - swiss: everyone, seeded by score, adjacent pairs, no rematches.
93
+ * - round-robin: everyone, greedily paired with an opponent not yet played.
94
+ */
95
+ export const pairRound = (
96
+ contestants: readonly string[],
97
+ table: readonly Standing[],
98
+ format: PairingFormat,
99
+ round: number,
100
+ played: readonly Match[],
101
+ ): readonly Pairing[] => {
102
+ const score = new Map(table.map((s) => [s.actor, s]));
103
+ const losses = (a: string): number => score.get(a)?.losses ?? 0;
104
+ const wins = (a: string): number => score.get(a)?.wins ?? 0;
105
+
106
+ let pool = [...contestants];
107
+ if (format === 'single-elim') pool = pool.filter((a) => losses(a) === 0);
108
+ if (pool.length < 2) return [];
109
+
110
+ // Seed the order: by score for swiss/single-elim, by name for round-robin.
111
+ pool.sort((a, b) => format === 'round-robin'
112
+ ? a.localeCompare(b)
113
+ : (wins(b) - wins(a)) || (losses(a) - losses(b)) || a.localeCompare(b));
114
+
115
+ const done = playedPairs(played);
116
+ const used = new Set<string>();
117
+ const pairings: Pairing[] = [];
118
+
119
+ for (let i = 0; i < pool.length; i += 1) {
120
+ const a = pool[i];
121
+ if (a === undefined || used.has(a)) continue;
122
+ let opponent: string | null = null;
123
+ for (let j = i + 1; j < pool.length; j += 1) {
124
+ const b = pool[j];
125
+ if (b === undefined || used.has(b) || done.has(pairKey(a, b))) continue;
126
+ opponent = b;
127
+ break;
128
+ }
129
+ used.add(a);
130
+ if (opponent !== null) { used.add(opponent); pairings.push({ a, b: opponent }); }
131
+ else pairings.push({ a, b: null }); // no un-played opponent left — a bye
132
+ void round;
133
+ }
134
+
135
+ return pairings;
136
+ };
137
+
138
+ /** Record a created MATCH. A bye is created already decided in the caller. */
139
+ export const matchCreatedEntry = (pairing: Pairing, round: number, at: string): HansardEntry => ({
140
+ type: 'MATCH_CREATED',
141
+ at,
142
+ actor: 'RECORD',
143
+ role: 'OPERATOR',
144
+ fields: {
145
+ Match: matchId(round, pairing.a, pairing.b),
146
+ Round: String(round),
147
+ A: pairing.a,
148
+ B: pairing.b ?? 'bye',
149
+ },
150
+ });
151
+
152
+ /** Decide a MATCH: name the winner; the loser is the other contestant. */
153
+ export const matchDecidedEntry = (
154
+ id: string,
155
+ round: number,
156
+ winner: string,
157
+ loser: string | null,
158
+ at: string,
159
+ by: string,
160
+ ): HansardEntry => ({
161
+ type: 'MATCH_DECIDED',
162
+ at,
163
+ actor: by,
164
+ role: 'AUTHORITY',
165
+ fields: {
166
+ Match: id,
167
+ Round: String(round),
168
+ Winner: winner,
169
+ Loser: loser ?? 'bye',
170
+ },
171
+ });
172
+
173
+ /**
174
+ * Report a result. Validates the match exists, is undecided, and the winner is
175
+ * one of its contestants — a referee cannot crown a party that never played.
176
+ */
177
+ export const reportMatch = (
178
+ matchRef: string,
179
+ winner: string,
180
+ at: string,
181
+ referee: string,
182
+ hansard: string,
183
+ ): { readonly entry: HansardEntry; readonly hansard: string } => {
184
+ const match = matches(hansard).find((m) => m.id === matchRef);
185
+ if (match === undefined) throw new TournamentError(`no match ${matchRef} on the record`);
186
+ if (match.winner !== null) throw new TournamentError(`match ${matchRef} is already decided — ${match.winner} won`);
187
+ if (winner !== match.a && winner !== match.b) {
188
+ throw new TournamentError(`${winner} is not in match ${matchRef} (${match.a} vs ${match.b ?? 'bye'})`);
189
+ }
190
+ const loser = winner === match.a ? match.b : match.a;
191
+ const entry = matchDecidedEntry(match.id, match.round, winner, loser, at, referee);
192
+ return { entry, hansard: appendEntry(hansard, entry) };
193
+ };
194
+
195
+ /** The undefeated contestants — for single-elim, the ones still in the bracket. */
196
+ export const undefeated = (contestants: readonly string[], hansard: string): readonly string[] => {
197
+ const table = standings(hansard);
198
+ const losses = new Map(table.map((s) => [s.actor, s.losses]));
199
+ return contestants.filter((a) => (losses.get(a) ?? 0) === 0);
200
+ };