@cordfuse/politik 0.4.0 → 0.6.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 (81) hide show
  1. package/EXECUTION.md +90 -85
  2. package/POLITIK-ARCHITECTURE.md +111 -176
  3. package/PROTOCOLS.md +120 -289
  4. package/README.md +130 -177
  5. package/RESEARCH.md +142 -436
  6. package/RUNTIME.md +253 -261
  7. package/docs/adr/0001-chamber-transport.md +2 -0
  8. package/docs/adr/0002-charter-schema.md +2 -0
  9. package/docs/adr/0003-state-json-schema.md +2 -0
  10. package/docs/adr/0004-motion-enactment.md +2 -0
  11. package/docs/adr/0005-hansard-format.md +2 -0
  12. package/docs/adr/0006-protocol-behavioral-enforcement.md +2 -0
  13. package/docs/adr/0007-protocol-mechanics.md +2 -0
  14. package/docs/adr/0008-session-storage.md +2 -0
  15. package/docs/adr/0009-match-primitive.md +2 -0
  16. package/docs/adr/0010-operator-interface.md +2 -0
  17. package/docs/adr/0011-shared-sessions.md +2 -0
  18. package/docs/adr/0012-plain-vocabulary.md +68 -0
  19. package/docs/adr/0013-rule-defined-protocols.md +89 -0
  20. package/package.json +1 -1
  21. package/protocols/CONTRIBUTING.md +47 -87
  22. package/protocols/adversarial-review.yml +19 -0
  23. package/protocols/elimination-rounds.yml +18 -0
  24. package/protocols/majority-vote.yml +18 -0
  25. package/protocols/panel-review.yml +19 -0
  26. package/protocols/single-decider.yml +18 -0
  27. package/protocols/unanimous-vote.yml +17 -0
  28. package/src/actors.ts +124 -100
  29. package/src/agents.ts +64 -23
  30. package/src/ballot.ts +747 -0
  31. package/src/canon.ts +23 -10
  32. package/src/capability.ts +16 -99
  33. package/src/charter.ts +41 -34
  34. package/src/cli.ts +541 -480
  35. package/src/{prorogation.ts → closing.ts} +43 -43
  36. package/src/conflict.ts +14 -14
  37. package/src/containment.ts +11 -11
  38. package/src/doctor.ts +1 -1
  39. package/src/election.ts +4 -4
  40. package/src/envelope.ts +3 -3
  41. package/src/escalation.ts +44 -44
  42. package/src/fault.ts +8 -8
  43. package/src/federation.ts +14 -14
  44. package/src/git.ts +21 -18
  45. package/src/heartbeat.ts +32 -32
  46. package/src/index.ts +5 -5
  47. package/src/init.ts +66 -65
  48. package/src/integrity.ts +30 -30
  49. package/src/ledger.ts +3 -3
  50. package/src/{hansard.ts → log.ts} +20 -20
  51. package/src/{crisis.ts → misconduct.ts} +70 -70
  52. package/src/operator.ts +5 -5
  53. package/src/pending.ts +9 -9
  54. package/src/projection.ts +30 -30
  55. package/src/protocol-sdk.ts +12 -121
  56. package/src/protocol.ts +8 -78
  57. package/src/providers/github.ts +12 -12
  58. package/src/quorum.ts +7 -7
  59. package/src/remote.ts +1 -1
  60. package/src/runner.ts +134 -55
  61. package/src/scm.ts +14 -14
  62. package/src/spawn.ts +4 -4
  63. package/src/standings.ts +13 -13
  64. package/src/state.ts +6 -6
  65. package/src/templates/session.ts +448 -0
  66. package/src/tournament.ts +20 -20
  67. package/src/transport.ts +4 -4
  68. package/src/tree.ts +16 -16
  69. package/protocols/adversarial-collaboration.yml +0 -28
  70. package/protocols/corporate.yml +0 -35
  71. package/protocols/elimination-tournament.yml +0 -41
  72. package/protocols/emergency-response-ics.yml +0 -27
  73. package/protocols/jury-deliberation.yml +0 -32
  74. package/protocols/monarchy.yml +0 -31
  75. package/protocols/parliamentary.yml +0 -66
  76. package/protocols/peer-review.yml +0 -44
  77. package/protocols/republic.yml +0 -36
  78. package/protocols/socialism-collective.yml +0 -31
  79. package/protocols/solo.yml +0 -32
  80. package/src/division.ts +0 -609
  81. package/src/templates/parliamentary.ts +0 -580
package/src/ballot.ts ADDED
@@ -0,0 +1,747 @@
1
+ /**
2
+ * vote and Enactment — deciding a Motion, then enacting it.
3
+ *
4
+ * ADR-0004 draws the line this module implements: **the vote decides, the
5
+ * Enactment enacts.** They are separate verbs held by different roles. A Motion
6
+ * can carry and still not take effect, because carrying is an outcome and
7
+ * enacting is an act.
8
+ *
9
+ * Pure, like the rest of the governance layer: these functions produce record
10
+ * entries and next-states. The caller commits them.
11
+ *
12
+ * Attribution: Steve Krisjanovs, Cordfuse
13
+ */
14
+
15
+ import { isRole, type Role } from './canon.ts';
16
+ import { appendEntry, parseEntries, type RecordEntry } from './log.ts';
17
+ import { checkQuorum, type QuorumOverride } from './quorum.ts';
18
+ import { createState, type SessionStateFile } from './state.ts';
19
+ import { darwinistExit, seatOf } from './actors.ts';
20
+
21
+ /* -------------------------------------------------------------------------- */
22
+ /* Votes */
23
+ /* -------------------------------------------------------------------------- */
24
+
25
+ export const VOTES = ['YES', 'NO', 'ABSTAIN'] as const;
26
+
27
+ export type Vote = (typeof VOTES)[number];
28
+
29
+ export const isVote = (v: unknown): v is Vote =>
30
+ typeof v === 'string' && (VOTES as readonly string[]).includes(v);
31
+
32
+ export interface CastVote {
33
+ readonly actor: string;
34
+ readonly role: Role;
35
+ readonly vote: Vote;
36
+ }
37
+
38
+ export class BallotError extends Error {
39
+ constructor(message: string) {
40
+ super(message);
41
+ this.name = 'BallotError';
42
+ }
43
+ }
44
+
45
+ /* -------------------------------------------------------------------------- */
46
+ /* Calling a vote */
47
+ /* -------------------------------------------------------------------------- */
48
+
49
+ export interface OpenBallotInput {
50
+ readonly motion: string;
51
+ readonly at: string;
52
+ readonly actor: string;
53
+ readonly role: Role;
54
+ readonly reviewers: readonly string[];
55
+ readonly state: SessionStateFile;
56
+ /**
57
+ * A removal vote: the actor this vote would remove if it carries. Only under
58
+ * `exit: vote`, and never the owner.
59
+ */
60
+ readonly removes?: string;
61
+ /** The Charter's exit policy; required to open a removal vote. */
62
+ readonly exit_policy?: ExitPolicy;
63
+ /** The Charter's resolution rule. Under `owner` no vote can be opened. */
64
+ readonly resolution?: Resolution;
65
+ }
66
+
67
+ /** Open a vote on a tabled Motion. */
68
+ export const openBallot = (input: OpenBallotInput, log: string): {
69
+ readonly entry: RecordEntry;
70
+ readonly log: string;
71
+ } => {
72
+ if (!isRole(input.role)) {
73
+ throw new BallotError(`not a CANON role: ${String(input.role)}`);
74
+ }
75
+ if (input.state.state !== 'CONVENED') {
76
+ throw new BallotError(
77
+ `cannot open a vote while the session is ${input.state.state}`,
78
+ );
79
+ }
80
+ // One vote per Motion. Re-calling would open a second vote on a Motion
81
+ // that may already be decided, letting a settled outcome be overturned. A
82
+ // genuinely new question is a new Motion.
83
+ if (ballotOpened(log, input.motion)) {
84
+ throw new BallotError(`a vote has already been opened on ${input.motion}`);
85
+ }
86
+ if (input.resolution === 'owner') {
87
+ throw new BallotError(
88
+ 'no vote is held in this session — the owner decides (resolution: owner); the owner enacts a motion directly with politik enact',
89
+ );
90
+ }
91
+ if (input.removes !== undefined) {
92
+ if (input.exit_policy !== 'vote') {
93
+ throw new BallotError(
94
+ `a removal vote needs exit: vote — this session runs exit: ${input.exit_policy ?? 'owner'}`,
95
+ );
96
+ }
97
+ const seat = seatOf(log, input.removes);
98
+ if (seat === null) throw new BallotError(`${input.removes} holds no seat — there is no one to remove`);
99
+ if (seat.role === 'AUTHORITY') {
100
+ throw new BallotError('the owner cannot be voted out — report misconduct instead');
101
+ }
102
+ }
103
+
104
+ const entry: RecordEntry = {
105
+ type: 'BALLOT_OPENED',
106
+ at: input.at,
107
+ actor: input.actor,
108
+ role: input.role,
109
+ fields: {
110
+ Motion: input.motion,
111
+ Reviewers: input.reviewers.join(', '),
112
+ ...(input.removes === undefined ? {} : { Removes: input.removes }),
113
+ },
114
+ body: input.removes === undefined
115
+ ? `A vote is opened on ${input.motion}.`
116
+ : `A vote is opened on ${input.motion}: remove ${input.removes}.`,
117
+ };
118
+
119
+ return { entry, log: appendEntry(log, entry) };
120
+ };
121
+
122
+ /* -------------------------------------------------------------------------- */
123
+ /* Casting a vote */
124
+ /* -------------------------------------------------------------------------- */
125
+
126
+ export interface CastVoteInput {
127
+ readonly motion: string;
128
+ readonly at: string;
129
+ readonly actor: string;
130
+ readonly role: Role;
131
+ readonly vote: Vote;
132
+ readonly state: SessionStateFile;
133
+ }
134
+
135
+ /**
136
+ * Record a vote.
137
+ *
138
+ * OBSERVER is refused: the role is defined as read-only with no floor rights. A
139
+ * protocol that wants an observer-class actor to decide something declares a
140
+ * DOMAIN_VETO instead — that is exactly the power inversion CANON models, and
141
+ * it is declared in the Charter rather than smuggled in through a vote.
142
+ */
143
+ export const castVote = (input: CastVoteInput, log: string): {
144
+ readonly entry: RecordEntry;
145
+ readonly log: string;
146
+ } => {
147
+ if (!isRole(input.role)) {
148
+ throw new BallotError(`not a CANON role: ${String(input.role)}`);
149
+ }
150
+ if (input.state.state !== 'CONVENED') {
151
+ throw new BallotError(`cannot vote while the session is ${input.state.state}`);
152
+ }
153
+ if (input.role === 'OBSERVER') {
154
+ throw new BallotError('OBSERVER holds no floor rights and may not vote');
155
+ }
156
+ if (!isVote(input.vote)) {
157
+ throw new BallotError(`not a valid vote: ${String(input.vote)}`);
158
+ }
159
+
160
+ // A vote only exists inside a vote. Without this a vote could be cast on a
161
+ // Motion no vote was ever called on, and enough such phantom votes would
162
+ // let a tally "carry" a Motion that never reached the floor.
163
+ if (!ballotOpened(log, input.motion)) {
164
+ throw new BallotError(`no vote has been opened on ${input.motion}`);
165
+ }
166
+ // A decided vote is closed. Without this a late vote could be cast after
167
+ // the outcome was recorded and a re-tally would overturn a settled decision —
168
+ // the record is append-only, but the decision it carries must be final.
169
+ if (ballotDecided(log, input.motion)) {
170
+ throw new BallotError(`the vote on ${input.motion} has closed — its outcome is on the record`);
171
+ }
172
+
173
+ // One vote per actor per Motion. A second vote is not an amendment — it is an
174
+ // attempt to rewrite a record that is append-only by construction.
175
+ const already = votesFor(log, input.motion).find((v) => v.actor === input.actor);
176
+ if (already !== undefined) {
177
+ throw new BallotError(
178
+ `${input.actor} has already voted ${already.vote} on ${input.motion}`,
179
+ );
180
+ }
181
+
182
+ const entry: RecordEntry = {
183
+ type: 'VOTE_CAST',
184
+ at: input.at,
185
+ actor: input.actor,
186
+ role: input.role,
187
+ fields: { Motion: input.motion, Vote: input.vote },
188
+ };
189
+
190
+ return { entry, log: appendEntry(log, entry) };
191
+ };
192
+
193
+ /** Whether a vote was ever called on this Motion. */
194
+ export const ballotOpened = (log: string, motion: string): boolean =>
195
+ parseEntries(log).some(
196
+ (e) => e.type === 'BALLOT_OPENED' && e.fields['Motion'] === motion,
197
+ );
198
+
199
+ /** Whether a vote on this Motion has been decided — its outcome recorded.
200
+ * A DEADLOCK records MOTION_REJECTED, so it too closes the vote. */
201
+ /**
202
+ * The outcome the tally recorded for a motion: true carried, false rejected,
203
+ * null if no tally is on the record. The record is the authority — a later
204
+ * recompute could apply a different rule than the one the tally used.
205
+ */
206
+ /** The owner's decision under `resolution: owner`: enacting a motion is the decision. */
207
+ export const ownerDecision = (motion: string): BallotOutcome => ({
208
+ motion, yes: 0, no: 0, abstentions: 0, carried: true,
209
+ quorum_met: true, quorum_required: 0,
210
+ reason: 'decided by the owner (resolution: owner)',
211
+ });
212
+
213
+ export const recordedOutcome = (log: string, motion: string): boolean | null => {
214
+ for (const e of parseEntries(log)) {
215
+ if (e.fields['Motion'] !== motion) continue;
216
+ if (e.type === 'MOTION_CARRIED') return true;
217
+ if (e.type === 'MOTION_REJECTED') return false;
218
+ }
219
+ return null;
220
+ };
221
+
222
+ export const ballotDecided = (log: string, motion: string): boolean =>
223
+ parseEntries(log).some(
224
+ (e) =>
225
+ (e.type === 'MOTION_CARRIED' || e.type === 'MOTION_REJECTED') &&
226
+ e.fields['Motion'] === motion,
227
+ );
228
+
229
+ /**
230
+ * Who can remove an actor — the second protocol override point (ADR-0007).
231
+ * Under every policy an actor may still leave voluntarily.
232
+ *
233
+ * - `owner`: the owner removes an actor alone.
234
+ * - `vote` (default): only a carried vote removes an actor; the owner records the
235
+ * removal as EXIT_VOTE, citing the motion.
236
+ * - `elimination`: only the cull after each vote removes actors.
237
+ * - `none`: nobody can be removed until the session closes.
238
+ */
239
+ export type ExitPolicy = 'owner' | 'vote' | 'elimination' | 'none';
240
+
241
+ export const EXIT_POLICIES: readonly ExitPolicy[] = Object.freeze([
242
+ 'owner',
243
+ 'vote',
244
+ 'elimination',
245
+ 'none',
246
+ ]);
247
+
248
+ export const isExitPolicy = (v: unknown): v is ExitPolicy =>
249
+ typeof v === 'string' && (EXIT_POLICIES as readonly string[]).includes(v);
250
+
251
+ /** The actor a removal vote would remove, or null for an ordinary vote. */
252
+ export const removalTarget = (log: string, motion: string): string | null => {
253
+ for (const e of parseEntries(log)) {
254
+ if (e.type === 'BALLOT_OPENED' && e.fields['Motion'] === motion) return e.fields['Removes'] ?? null;
255
+ }
256
+ return null;
257
+ };
258
+
259
+ /**
260
+ * A carried removal vote removes its target (EXIT_VOTE). Declared by the engine,
261
+ * like the elimination cull: the vote decided, so no actor needs to record it.
262
+ */
263
+ export const removeByVote = (log: string, motion: string, at: string): RecordEntry | null => {
264
+ const target = removalTarget(log, motion);
265
+ if (target === null) return null;
266
+ const seat = seatOf(log, target);
267
+ if (seat === null) return null;
268
+ return {
269
+ type: 'ACTOR_EXITED',
270
+ at,
271
+ actor: 'RECORD',
272
+ role: 'OPERATOR',
273
+ fields: {
274
+ 'Actor affected': target,
275
+ 'Seat held': seat.role,
276
+ 'Exit type': 'EXIT_VOTE',
277
+ Motion: motion,
278
+ Declared: 'by the vote',
279
+ Reason: `voted out on ${motion}`,
280
+ Appealable: 'yes — escalate',
281
+ },
282
+ };
283
+ };
284
+
285
+ /**
286
+ * The elimination cull: under `exit: elimination`, the actors on the losing side
287
+ * of a decided vote are removed (EXIT_DARWINIST). The minority is culled; a
288
+ * tie culls no one; abstainers took no side and survive. Only seated actors are
289
+ * culled, so AUTHORITY — which holds no seat in the register — is never touched.
290
+ * Returns the exit entries to append; empty under any other policy.
291
+ */
292
+ export const cull = (
293
+ log: string,
294
+ motion: string,
295
+ policy: ExitPolicy,
296
+ at: string,
297
+ ): readonly RecordEntry[] => {
298
+ if (policy !== 'elimination') return [];
299
+ const votes = votesFor(log, motion);
300
+ const yes = votes.filter((v) => v.vote === 'YES');
301
+ const no = votes.filter((v) => v.vote === 'NO');
302
+ const losers = yes.length > no.length ? no : no.length > yes.length ? yes : [];
303
+ const entries: RecordEntry[] = [];
304
+ for (const loser of losers) {
305
+ const seat = seatOf(log, loser.actor);
306
+ if (seat !== null) entries.push(darwinistExit(loser.actor, seat.role, at));
307
+ }
308
+ return entries;
309
+ };
310
+
311
+ /** Every vote recorded against a Motion, read back from the record. */
312
+ export const votesFor = (log: string, motion: string): readonly CastVote[] =>
313
+ parseEntries(log)
314
+ .filter((e) => e.type === 'VOTE_CAST' && e.fields['Motion'] === motion)
315
+ .map((e) => ({
316
+ actor: e.actor,
317
+ role: e.role as Role,
318
+ vote: (e.fields['Vote'] ?? 'ABSTAIN') as Vote,
319
+ }));
320
+
321
+ /* -------------------------------------------------------------------------- */
322
+ /* Outcome */
323
+ /* -------------------------------------------------------------------------- */
324
+
325
+ export interface BallotOutcome {
326
+ readonly motion: string;
327
+ readonly yes: number;
328
+ readonly no: number;
329
+ readonly abstentions: number;
330
+ /** Did the Motion carry? */
331
+ readonly carried: boolean;
332
+ /** Quorum is counted on votes cast, abstentions excluded. */
333
+ readonly quorum_met: boolean;
334
+ /**
335
+ * The quorum threshold in force when this vote was tallied.
336
+ *
337
+ * Recorded so a vote entry is auditable on its own terms. Without it,
338
+ * "quorum met" only means something to a reader willing to recover the
339
+ * Charter as it stood at that commit — and a record that requires
340
+ * cross-referencing to interpret is doing less work than a record should.
341
+ *
342
+ * Enacted by motion-001 of session clean-001, which observed that the
343
+ * validity of a carried Motion was "unverifiable after the fact".
344
+ */
345
+ readonly quorum_required: number;
346
+ readonly reason: string;
347
+ }
348
+
349
+ /**
350
+ * Tally a vote.
351
+ *
352
+ * Abstentions are recorded but do not count toward quorum: an abstention is a
353
+ * declared non-participation, and counting it would let a vote reach quorum
354
+ * without anyone actually deciding anything.
355
+ *
356
+ * A tie does not carry. Without a majority there is no decision, and a Motion
357
+ * that cannot be decided is a DEADLOCK for AUTHORITY to rule on — not a silent
358
+ * pass.
359
+ */
360
+ /**
361
+ * How a vote resolves — the first protocol override point (ADR-0007). The
362
+ * engine is single and shared; a protocol picks which rule decides the outcome.
363
+ * `majority` is the default. `owner` holds no vote at all: the owner decides,
364
+ * by enacting a motion directly. `both-sides` needs each of two opposing sides —
365
+ * OPERATOR proposes, DELEGATE opposes — to vote and to carry it among themselves.
366
+ */
367
+ export type Resolution = 'majority' | 'supermajority' | 'unanimity' | 'owner' | 'both-sides';
368
+
369
+ export const RESOLUTIONS: readonly Resolution[] = Object.freeze([
370
+ 'majority',
371
+ 'supermajority',
372
+ 'unanimity',
373
+ 'owner',
374
+ 'both-sides',
375
+ ]);
376
+
377
+ export const isResolution = (v: unknown): v is Resolution =>
378
+ typeof v === 'string' && (RESOLUTIONS as readonly string[]).includes(v);
379
+
380
+ /**
381
+ * Each strategy is a pure function of the ballot and nothing else, so the same
382
+ * votes and the same rule always yield the same verdict — the property the
383
+ * record's auditability depends on (ADR-0007).
384
+ */
385
+ const RESOLUTION_RULES: Readonly<
386
+ Record<Resolution, (yes: number, no: number, abstentions: number) => { carried: boolean; reason: string }>
387
+ > = Object.freeze({
388
+ // Never reached through the CLI — no vote can be opened under `owner` — but a
389
+ // tally of stray votes must not carry anything.
390
+ owner: () => ({ carried: false, reason: 'no vote is held — the owner decides (resolution: owner)' }),
391
+ // Needs the voters' roles, so tallyBallot decides it before reaching this table.
392
+ 'both-sides': () => ({ carried: false, reason: 'both-sides is decided per side' }),
393
+ majority: (yes, no) =>
394
+ yes > no
395
+ ? { carried: true, reason: `carried ${yes} to ${no}` }
396
+ : {
397
+ carried: false,
398
+ reason: yes === no ? `tied ${yes} all — no majority, DEADLOCK` : `rejected ${yes} to ${no}`,
399
+ },
400
+ supermajority: (yes, no) => {
401
+ // Two-thirds of the decisive votes, abstentions excluded.
402
+ const carried = yes > 0 && yes * 3 >= (yes + no) * 2 && yes > no;
403
+ return carried
404
+ ? { carried: true, reason: `carried ${yes} to ${no} — two-thirds supermajority met` }
405
+ : { carried: false, reason: `rejected ${yes} to ${no} — a two-thirds supermajority was required` };
406
+ },
407
+ unanimity: (yes, no, abstentions) => {
408
+ // Every seated voter must enact; a single dissent or abstention hangs it.
409
+ const carried = yes > 0 && no === 0 && abstentions === 0;
410
+ if (carried) return { carried: true, reason: `carried unanimously, ${yes} to 0` };
411
+ return {
412
+ carried: false,
413
+ reason:
414
+ no > 0
415
+ ? `rejected — unanimity required, ${no} against`
416
+ : `no verdict — unanimity required, ${abstentions} abstained`,
417
+ };
418
+ },
419
+ });
420
+
421
+ /**
422
+ * `both-sides`: the proposing side (OPERATOR) and the opposing side (DELEGATE)
423
+ * must each vote, and each must carry the motion by a majority of its own votes.
424
+ * Neither side can win by outnumbering the other.
425
+ */
426
+ const bothSides = (votes: readonly CastVote[]): { carried: boolean; reason: string } => {
427
+ const side = (role: Role) => {
428
+ const own = votes.filter((v) => v.role === role);
429
+ return {
430
+ yes: own.filter((v) => v.vote === 'YES').length,
431
+ no: own.filter((v) => v.vote === 'NO').length,
432
+ };
433
+ };
434
+ const pro = side('OPERATOR');
435
+ const con = side('DELEGATE');
436
+ if (pro.yes + pro.no === 0) return { carried: false, reason: 'the proposing side (OPERATOR) has not voted' };
437
+ if (con.yes + con.no === 0) return { carried: false, reason: 'the opposing side (DELEGATE) has not voted' };
438
+ const proCarries = pro.yes > pro.no;
439
+ const conCarries = con.yes > con.no;
440
+ const tally = `proposing ${pro.yes}-${pro.no}, opposing ${con.yes}-${con.no}`;
441
+ if (proCarries && conCarries) return { carried: true, reason: `both sides accept — ${tally}` };
442
+ return {
443
+ carried: false,
444
+ reason: `${!proCarries && !conCarries ? 'neither side accepts' : proCarries ? 'the opposing side does not accept' : 'the proposing side does not accept'} — ${tally}`,
445
+ };
446
+ };
447
+
448
+ export const tallyBallot = (
449
+ log: string,
450
+ motion: string,
451
+ quorumRequired: number,
452
+ override?: QuorumOverride | null,
453
+ resolution: Resolution = 'majority',
454
+ ): BallotOutcome => {
455
+ const votes = votesFor(log, motion);
456
+ const yes = votes.filter((v) => v.vote === 'YES').length;
457
+ const no = votes.filter((v) => v.vote === 'NO').length;
458
+ const abstentions = votes.filter((v) => v.vote === 'ABSTAIN').length;
459
+
460
+ const quorum = checkQuorum({
461
+ required: quorumRequired,
462
+ present: yes + no,
463
+ override,
464
+ });
465
+
466
+ if (!quorum.met) {
467
+ return {
468
+ motion,
469
+ yes,
470
+ no,
471
+ abstentions,
472
+ carried: false,
473
+ quorum_met: false,
474
+ quorum_required: quorumRequired,
475
+ reason: quorum.reason ?? 'quorum not met',
476
+ };
477
+ }
478
+
479
+ const decision = resolution === 'both-sides'
480
+ ? bothSides(votes)
481
+ : RESOLUTION_RULES[resolution](yes, no, abstentions);
482
+ return {
483
+ motion, yes, no, abstentions,
484
+ carried: decision.carried,
485
+ quorum_met: true,
486
+ quorum_required: quorumRequired,
487
+ reason:
488
+ decision.carried && quorum.degraded ? `${decision.reason} (degraded quorum)` : decision.reason,
489
+ };
490
+ };
491
+
492
+ /**
493
+ * A standing veto rejects the motion, whatever the votes. Without this, a vetoed
494
+ * motion still carried; under a protocol that closes at its verdict the session
495
+ * then ended on a vetoed decision, and the veto — panel-review's defining
496
+ * safeguard — did nothing (found dogfooding).
497
+ */
498
+ export const applyVeto = (outcome: BallotOutcome, vetoed: boolean): BallotOutcome =>
499
+ vetoed && outcome.carried
500
+ ? { ...outcome, carried: false, reason: `vetoed — a veto stands against ${outcome.motion} (${outcome.reason})` }
501
+ : outcome;
502
+
503
+ /** Record the outcome of a vote. */
504
+ export const recordOutcome = (
505
+ outcome: BallotOutcome,
506
+ at: string,
507
+ actor: string,
508
+ role: Role,
509
+ log: string,
510
+ ): { readonly entry: RecordEntry; readonly log: string } => {
511
+ const entry: RecordEntry = {
512
+ type: outcome.carried ? 'MOTION_CARRIED' : 'MOTION_REJECTED',
513
+ at,
514
+ actor,
515
+ role,
516
+ fields: {
517
+ Motion: outcome.motion,
518
+ Yes: String(outcome.yes),
519
+ No: String(outcome.no),
520
+ Abstentions: String(outcome.abstentions),
521
+ Quorum: `${outcome.quorum_met ? 'met' : 'NOT MET'} (${outcome.quorum_required} required)`,
522
+ Outcome: outcome.reason,
523
+ },
524
+ };
525
+ return { entry, log: appendEntry(log, entry) };
526
+ };
527
+
528
+ /* -------------------------------------------------------------------------- */
529
+ /* Enactment */
530
+ /* -------------------------------------------------------------------------- */
531
+
532
+ export interface EnactInput {
533
+ readonly motion: string;
534
+ readonly at: string;
535
+ readonly actor: string;
536
+ readonly role: Role;
537
+ /** Role the Charter grants ENACT. Defaults to AUTHORITY (ADR-0004). */
538
+ readonly enact_role: Role;
539
+ readonly outcome: BallotOutcome;
540
+ readonly state: SessionStateFile;
541
+ /**
542
+ * Is a veto standing against this Motion? ADR-0004 makes Enactment invalid while
543
+ * one is outstanding — the fourth condition, and the one a caller is most
544
+ * likely to forget, so it is explicit rather than inferred.
545
+ */
546
+ readonly veto_outstanding?: boolean;
547
+ }
548
+
549
+ /**
550
+ * Grant Enactment — enact a carried Motion.
551
+ *
552
+ * Four conditions, all from ADR-0004. Every one is checked rather than assumed,
553
+ * because Enactment is the moment a decision becomes an effect and it is the last
554
+ * point at which the constitution can refuse.
555
+ */
556
+ export const enactMotion = (input: EnactInput, log: string): {
557
+ readonly entry: RecordEntry;
558
+ readonly log: string;
559
+ readonly state: SessionStateFile;
560
+ } => {
561
+ if (input.role !== input.enact_role) {
562
+ throw new BallotError(
563
+ `ENACT is held by ${input.enact_role} — ${input.actor} is ${input.role}`,
564
+ );
565
+ }
566
+ if (input.state.state !== 'CONVENED') {
567
+ throw new BallotError(`cannot grant Enactment while the session is ${input.state.state}`);
568
+ }
569
+ if (!input.outcome.carried) {
570
+ throw new BallotError(
571
+ `${input.motion} did not carry (${input.outcome.reason}) — there is nothing to enact`,
572
+ );
573
+ }
574
+ if (alreadyEnacted(log, input.motion)) {
575
+ throw new BallotError(`${input.motion} has already received Enactment`);
576
+ }
577
+ if (input.veto_outstanding === true) {
578
+ throw new BallotError(
579
+ `a veto stands against ${input.motion} — it may not receive Enactment while that veto is outstanding`,
580
+ );
581
+ }
582
+
583
+ const entry: RecordEntry = {
584
+ type: 'MOTION_ENACTED',
585
+ at: input.at,
586
+ actor: input.actor,
587
+ role: input.role,
588
+ fields: {
589
+ Motion: input.motion,
590
+ vote: input.outcome.reason,
591
+ Effect: 'enacted',
592
+ },
593
+ body: `Enactment granted. ${input.motion} is enacted.`,
594
+ };
595
+
596
+ return {
597
+ entry,
598
+ log: appendEntry(log, entry),
599
+ state: createState({
600
+ session_guid: input.state.session_guid,
601
+ protocol: input.state.protocol,
602
+ state: 'CONVENED',
603
+ quorum: input.state.quorum,
604
+ log_head: input.state.log_head,
605
+ updated_at: input.at,
606
+ }),
607
+ };
608
+ };
609
+
610
+ /** Has this Motion already been enacted? */
611
+ export const alreadyEnacted = (log: string, motion: string): boolean =>
612
+ parseEntries(log).some(
613
+ (e) => e.type === 'MOTION_ENACTED' && e.fields['Motion'] === motion,
614
+ );
615
+
616
+ /* -------------------------------------------------------------------------- */
617
+ /* Deadlock */
618
+ /* -------------------------------------------------------------------------- */
619
+
620
+ /**
621
+ * Suspend a proceeding on an undecidable vote.
622
+ *
623
+ * ADR-0004 Proposal 4 adds `DEADLOCK` to the suspension causes: a vote that
624
+ * yields no valid outcome is a governance failure, not a silent pass. Until
625
+ * this existed the tally wrote the word "DEADLOCK" into free text and the
626
+ * session carried on as though nothing had happened.
627
+ *
628
+ * Suspends rather than rejects, because a tie is not a decision against the
629
+ * Motion — it is the absence of one, and only AUTHORITY can supply what the
630
+ * vote could not.
631
+ */
632
+ export const suspendForDeadlock = (
633
+ outcome: BallotOutcome,
634
+ at: string,
635
+ state: SessionStateFile,
636
+ log: string,
637
+ ): {
638
+ readonly entry: RecordEntry;
639
+ readonly log: string;
640
+ readonly state: SessionStateFile;
641
+ } => {
642
+ if (outcome.carried || outcome.yes !== outcome.no || !outcome.quorum_met) {
643
+ throw new BallotError(
644
+ `${outcome.motion} is not deadlocked — ${outcome.reason}`,
645
+ );
646
+ }
647
+ if (state.state !== 'CONVENED') {
648
+ throw new BallotError(`cannot declare a deadlock while the session is ${state.state}`);
649
+ }
650
+
651
+ const entry: RecordEntry = {
652
+ type: 'DEADLOCK',
653
+ at,
654
+ actor: 'RECORD',
655
+ role: 'OPERATOR',
656
+ fields: {
657
+ Motion: outcome.motion,
658
+ vote: outcome.reason,
659
+ 'Session status': 'SUSPENDED — no valid vote outcome',
660
+ Resolution: 'AUTHORITY must rule; the vote could not decide',
661
+ },
662
+ };
663
+
664
+ return {
665
+ entry,
666
+ log: appendEntry(log, entry),
667
+ state: createState({
668
+ session_guid: state.session_guid,
669
+ protocol: state.protocol,
670
+ state: 'SUSPENDED',
671
+ quorum: state.quorum,
672
+ log_head: state.log_head,
673
+ updated_at: at,
674
+ suspension: {
675
+ cause: 'DEADLOCK',
676
+ since: at,
677
+ record_ref: 'LOG.md',
678
+ escalation_ref: null,
679
+ },
680
+ }),
681
+ };
682
+ };
683
+
684
+ /**
685
+ * AUTHORITY breaks a DEADLOCK with a casting vote.
686
+ *
687
+ * The tie suspended the session because the vote could not decide; only
688
+ * AUTHORITY can supply the decision it could not reach (suspendForDeadlock:
689
+ * "AUTHORITY must rule; the vote could not decide"). The casting vote decides
690
+ * the Motion — carried or rejected — and the session resumes. Refuses unless the
691
+ * session is actually deadlocked, so a casting vote can never override a vote
692
+ * the vote did decide.
693
+ */
694
+ export const breakDeadlock = (
695
+ motion: string,
696
+ decision: 'carry' | 'reject',
697
+ at: string,
698
+ authority: string,
699
+ state: SessionStateFile,
700
+ log: string,
701
+ quorumRequired: number,
702
+ resolution: Resolution = 'majority',
703
+ ): {
704
+ /** The casting vote, then the outcome it produces. */
705
+ readonly entries: readonly RecordEntry[];
706
+ readonly log: string;
707
+ readonly outcome: BallotOutcome;
708
+ readonly state: SessionStateFile;
709
+ } => {
710
+ if (state.state !== 'SUSPENDED' || state.suspension?.cause !== 'DEADLOCK') {
711
+ throw new BallotError('the session is not deadlocked — there is no tie for a casting vote to break');
712
+ }
713
+
714
+ // The casting vote is a real vote: YES to carry, NO to reject. It flows through
715
+ // the ordinary tally, so every downstream reader (Enactment included) sees a
716
+ // decided vote, not a special case only this command understands.
717
+ const casting: RecordEntry = {
718
+ type: 'VOTE_CAST',
719
+ at,
720
+ actor: authority,
721
+ role: 'AUTHORITY',
722
+ fields: {
723
+ Motion: motion,
724
+ Vote: decision === 'carry' ? 'YES' : 'NO',
725
+ Note: 'AUTHORITY casting vote to break a DEADLOCK',
726
+ },
727
+ };
728
+ const withVote = appendEntry(log, casting);
729
+ const outcome = tallyBallot(withVote, motion, quorumRequired, null, resolution);
730
+ const recorded = recordOutcome(outcome, at, authority, 'AUTHORITY', withVote);
731
+
732
+ return {
733
+ entries: [casting, recorded.entry],
734
+ log: recorded.log,
735
+ outcome,
736
+ state: createState({
737
+ session_guid: state.session_guid,
738
+ protocol: state.protocol,
739
+ state: 'CONVENED',
740
+ quorum: state.quorum,
741
+ log_head: state.log_head,
742
+ updated_at: at,
743
+ updated_by: authority,
744
+ suspension: null,
745
+ }),
746
+ };
747
+ };