@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
package/src/actors.ts ADDED
@@ -0,0 +1,742 @@
1
+ /**
2
+ * Actor lifecycle — seating, moving and removing actors.
3
+ *
4
+ * Implements the CANON verbs that change who holds what: HIRE, FIRE, PROMOTE,
5
+ * DEMOTE, EXPEL, VETO, SPAWN and EXIT.
6
+ *
7
+ * The design constraint that shapes everything here is RUNTIME.md § Actor
8
+ * Elimination: an immutable Hansard records *that* an actor was removed but not
9
+ * *why*, or whether the why was legitimate. So every removal must declare an
10
+ * exit type, and the taxonomy deliberately distinguishes forms of leaving that
11
+ * look identical in a naive log — a Minister who conceded on the merits and one
12
+ * who was pressured out record differently, on purpose.
13
+ *
14
+ * Pure, like the rest of the governance layer. These functions produce Hansard
15
+ * entries; the caller commits them.
16
+ *
17
+ * Attribution: Steve Krisjanovs, Cordfuse
18
+ */
19
+
20
+ import { ROLE_PRECEDENCE, isRole, type Role } from './canon.ts';
21
+ import { appendEntry, parseEntries, type HansardEntry } from './hansard.ts';
22
+ import { createState } from './state.ts';
23
+ import type { SessionStateFile } from './state.ts';
24
+
25
+ /* -------------------------------------------------------------------------- */
26
+ /* Exit taxonomy */
27
+ /* -------------------------------------------------------------------------- */
28
+
29
+ export const EXIT_TYPES = [
30
+ 'EXIT_PERFORMANCE',
31
+ 'EXIT_PROTOCOL',
32
+ 'EXIT_DIVISION',
33
+ 'EXIT_VOLUNTARY_CONCESSION',
34
+ 'EXIT_VOLUNTARY_STRATEGIC',
35
+ 'EXIT_VOLUNTARY_COERCED',
36
+ 'EXIT_DARWINIST',
37
+ 'EXIT_SPEAKER',
38
+ 'EXIT_DISPUTED',
39
+ ] as const;
40
+
41
+ export type ExitType = (typeof EXIT_TYPES)[number];
42
+
43
+ export const isExitType = (v: unknown): v is ExitType =>
44
+ typeof v === 'string' && (EXIT_TYPES as readonly string[]).includes(v);
45
+
46
+ /** Exits an actor declares about themselves. */
47
+ const VOLUNTARY: readonly ExitType[] = Object.freeze([
48
+ 'EXIT_VOLUNTARY_CONCESSION',
49
+ 'EXIT_VOLUNTARY_STRATEGIC',
50
+ 'EXIT_VOLUNTARY_COERCED',
51
+ ]);
52
+
53
+ export const isVoluntary = (type: ExitType): boolean => VOLUNTARY.includes(type);
54
+
55
+ export class ActorError extends Error {
56
+ constructor(message: string) {
57
+ super(message);
58
+ this.name = 'ActorError';
59
+ }
60
+ }
61
+
62
+ /* -------------------------------------------------------------------------- */
63
+ /* Seat state */
64
+ /* -------------------------------------------------------------------------- */
65
+
66
+ export interface Seat {
67
+ readonly actor: string;
68
+ readonly role: Role;
69
+ readonly seated_at: string;
70
+ }
71
+
72
+ /**
73
+ * Who currently holds a seat, read back from the Hansard.
74
+ *
75
+ * The Hansard is the register: there is no separate roster to fall out of sync
76
+ * with the record. An actor is seated if they were admitted and have not since
77
+ * exited, and their role is whatever the most recent PROMOTE or DEMOTE made it.
78
+ */
79
+ export const seats = (hansard: string): readonly Seat[] => {
80
+ const held = new Map<string, Seat>();
81
+
82
+ for (const entry of parseEntries(hansard)) {
83
+ const subject = entry.fields['Actor affected'];
84
+ if (subject === undefined) continue;
85
+
86
+ switch (entry.type) {
87
+ case 'ACTOR_HIRED': {
88
+ const role = entry.fields['Role'];
89
+ if (role !== undefined) {
90
+ held.set(subject, { actor: subject, role: role as Role, seated_at: entry.at });
91
+ }
92
+ break;
93
+ }
94
+ case 'ACTOR_PROMOTED':
95
+ case 'ACTOR_DEMOTED': {
96
+ const to = entry.fields['To'];
97
+ const existing = held.get(subject);
98
+ if (to !== undefined && existing !== undefined) {
99
+ held.set(subject, { ...existing, role: to as Role });
100
+ }
101
+ break;
102
+ }
103
+ case 'ACTOR_EXITED':
104
+ held.delete(subject);
105
+ break;
106
+ default:
107
+ break;
108
+ }
109
+ }
110
+
111
+ return [...held.values()];
112
+ };
113
+
114
+ export const seatOf = (hansard: string, actor: string): Seat | null =>
115
+ seats(hansard).find((s) => s.actor === actor) ?? null;
116
+
117
+ /* -------------------------------------------------------------------------- */
118
+ /* Common guards */
119
+ /* -------------------------------------------------------------------------- */
120
+
121
+ interface ActInput {
122
+ readonly at: string;
123
+ /** Who is performing the act. */
124
+ readonly actor: string;
125
+ readonly role: Role;
126
+ readonly state: SessionStateFile;
127
+ }
128
+
129
+ const requireConvened = (state: SessionStateFile, verb: string): void => {
130
+ if (state.state !== 'CONVENED') {
131
+ throw new ActorError(`cannot ${verb} while the session is ${state.state}`);
132
+ }
133
+ };
134
+
135
+ /**
136
+ * Verbs that move actors between roles are AUTHORITY powers.
137
+ *
138
+ * RUNTIME.md § Constitutional Capture names the abuse directly: AUTHORITY
139
+ * "uses legitimately held powers to remove actors who would check those powers,
140
+ * and promotes actors who will not". Restricting the verb does not prevent
141
+ * that — nothing can, since the power is constitutional — but it keeps every
142
+ * use of it attributed to the one role that can be held responsible.
143
+ */
144
+ const requireAuthority = (input: ActInput, verb: string): void => {
145
+ if (input.role !== 'AUTHORITY' && input.role !== 'DELEGATE') {
146
+ throw new ActorError(
147
+ `${verb} is an AUTHORITY power — ${input.actor} is ${input.role}`,
148
+ );
149
+ }
150
+ };
151
+
152
+ const rank = (role: Role): number => ROLE_PRECEDENCE.indexOf(role);
153
+
154
+ /* -------------------------------------------------------------------------- */
155
+ /* HIRE */
156
+ /* -------------------------------------------------------------------------- */
157
+
158
+ export interface HireInput extends ActInput {
159
+ readonly subject: string;
160
+ readonly seat: Role;
161
+ readonly reason: string;
162
+ }
163
+
164
+ /** Bring a new actor into a convened proceeding. */
165
+ export const hire = (input: HireInput, hansard: string): {
166
+ readonly entry: HansardEntry;
167
+ readonly hansard: string;
168
+ } => {
169
+ requireConvened(input.state, 'HIRE');
170
+ requireAuthority(input, 'HIRE');
171
+
172
+ if (!isRole(input.seat)) {
173
+ throw new ActorError(`not a CANON role: ${String(input.seat)}`);
174
+ }
175
+ if (input.seat === 'AUTHORITY') {
176
+ throw new ActorError(
177
+ 'AUTHORITY cannot be granted by HIRE — the Speaker is constitutional, not appointed',
178
+ );
179
+ }
180
+ if (seatOf(hansard, input.subject) !== null) {
181
+ throw new ActorError(`${input.subject} already holds a seat`);
182
+ }
183
+
184
+ const entry: HansardEntry = {
185
+ type: 'ACTOR_HIRED',
186
+ at: input.at,
187
+ actor: input.actor,
188
+ role: input.role,
189
+ fields: {
190
+ 'Actor affected': input.subject,
191
+ Role: input.seat,
192
+ Reason: input.reason,
193
+ },
194
+ };
195
+ return { entry, hansard: appendEntry(hansard, entry) };
196
+ };
197
+
198
+ /* -------------------------------------------------------------------------- */
199
+ /* PROMOTE / DEMOTE */
200
+ /* -------------------------------------------------------------------------- */
201
+
202
+ export interface MoveInput extends ActInput {
203
+ readonly subject: string;
204
+ readonly to: Role;
205
+ readonly reason: string;
206
+ }
207
+
208
+ const move = (
209
+ input: MoveInput,
210
+ hansard: string,
211
+ direction: 'PROMOTE' | 'DEMOTE',
212
+ ): { readonly entry: HansardEntry; readonly hansard: string } => {
213
+ requireConvened(input.state, direction);
214
+ requireAuthority(input, direction);
215
+
216
+ const seat = seatOf(hansard, input.subject);
217
+ if (seat === null) throw new ActorError(`${input.subject} holds no seat`);
218
+
219
+ if (!isRole(input.to)) {
220
+ throw new ActorError(`not a CANON role: ${String(input.to)}`);
221
+ }
222
+ if (input.to === 'AUTHORITY') {
223
+ throw new ActorError('no actor may be promoted into AUTHORITY');
224
+ }
225
+ if (seat.role === input.to) {
226
+ throw new ActorError(`${input.subject} already sits as ${input.to}`);
227
+ }
228
+
229
+ const higher = rank(input.to) < rank(seat.role);
230
+ if (direction === 'PROMOTE' && !higher) {
231
+ throw new ActorError(`${input.to} is not above ${seat.role} — that is a DEMOTE`);
232
+ }
233
+ if (direction === 'DEMOTE' && higher) {
234
+ throw new ActorError(`${input.to} is not below ${seat.role} — that is a PROMOTE`);
235
+ }
236
+
237
+ const entry: HansardEntry = {
238
+ type: direction === 'PROMOTE' ? 'ACTOR_PROMOTED' : 'ACTOR_DEMOTED',
239
+ at: input.at,
240
+ actor: input.actor,
241
+ role: input.role,
242
+ fields: {
243
+ 'Actor affected': input.subject,
244
+ From: seat.role,
245
+ To: input.to,
246
+ Reason: input.reason,
247
+ },
248
+ };
249
+ return { entry, hansard: appendEntry(hansard, entry) };
250
+ };
251
+
252
+ export const promote = (input: MoveInput, hansard: string) => move(input, hansard, 'PROMOTE');
253
+ export const demote = (input: MoveInput, hansard: string) => move(input, hansard, 'DEMOTE');
254
+
255
+ /* -------------------------------------------------------------------------- */
256
+ /* EXIT — removal and withdrawal */
257
+ /* -------------------------------------------------------------------------- */
258
+
259
+ export interface ExitInput extends ActInput {
260
+ readonly subject: string;
261
+ readonly exit_type: ExitType;
262
+ readonly reason: string;
263
+ /** True when the Charter requires a concession statement for voluntary exits. */
264
+ readonly require_concession?: boolean;
265
+ }
266
+
267
+ /**
268
+ * Remove an actor, or record one withdrawing.
269
+ *
270
+ * Every removal declares an exit type. The taxonomy is the point: FIRE and
271
+ * EXPEL both end a seat, but `EXIT_PERFORMANCE` and `EXIT_PROTOCOL` say
272
+ * different things about why, and a reader of the record months later can tell
273
+ * them apart.
274
+ *
275
+ * A voluntary exit may only be declared by the actor leaving. Letting a third
276
+ * party record someone else's resignation is precisely the "voluntold" pattern
277
+ * RUNTIME.md calls the most dangerous exit type — it produces the outcome of an
278
+ * expulsion while generating none of the evidence one would leave.
279
+ */
280
+ export const exitActor = (input: ExitInput, hansard: string): {
281
+ readonly entry: HansardEntry;
282
+ readonly hansard: string;
283
+ } => {
284
+ requireConvened(input.state, 'EXIT');
285
+
286
+ const seat = seatOf(hansard, input.subject);
287
+ if (seat === null) throw new ActorError(`${input.subject} holds no seat`);
288
+ if (!isExitType(input.exit_type)) {
289
+ throw new ActorError(`not a CANON exit type: ${String(input.exit_type)}`);
290
+ }
291
+ if (seat.role === 'AUTHORITY') {
292
+ throw new ActorError(
293
+ 'AUTHORITY cannot be removed from within the session — that is a constitutional crisis, not an exit',
294
+ );
295
+ }
296
+
297
+ const selfDeclared = input.actor === input.subject;
298
+
299
+ if (isVoluntary(input.exit_type) && !selfDeclared) {
300
+ throw new ActorError(
301
+ `a voluntary exit may only be declared by the actor leaving — ${input.actor} cannot record it for ${input.subject}`,
302
+ );
303
+ }
304
+ if (!isVoluntary(input.exit_type) && !selfDeclared) {
305
+ requireAuthority(input, 'removal');
306
+ }
307
+ if (input.require_concession === true && isVoluntary(input.exit_type) && input.reason.trim() === '') {
308
+ throw new ActorError(
309
+ 'this Charter requires a concession statement for a voluntary exit',
310
+ );
311
+ }
312
+ if (input.reason.trim() === '') {
313
+ throw new ActorError('an exit must state its reason — an unexplained removal is not attributable');
314
+ }
315
+
316
+ const entry: HansardEntry = {
317
+ type: 'ACTOR_EXITED',
318
+ at: input.at,
319
+ actor: input.actor,
320
+ role: input.role,
321
+ fields: {
322
+ 'Actor affected': input.subject,
323
+ 'Seat held': seat.role,
324
+ 'Exit type': input.exit_type,
325
+ Declared: selfDeclared ? 'by the actor' : `by ${input.actor} (${input.role})`,
326
+ Reason: input.reason,
327
+ Appealable: input.exit_type === 'EXIT_DISPUTED' ? 'under appeal' : 'yes — file a Point of Order',
328
+ },
329
+ };
330
+ return { entry, hansard: appendEntry(hansard, entry) };
331
+ };
332
+
333
+ /**
334
+ * An elimination exit, declared by the engine rather than an actor (ADR-0007,
335
+ * exit: elimination). A Battle Royale culls the losing side of a Division; the
336
+ * cull is EXIT_DARWINIST and final, so it does not pass through the guarded
337
+ * exit() path — no actor is declaring it and there is nothing to appeal.
338
+ * AUTHORITY is never culled: the Speaker holds no seat in the register, so a
339
+ * caller can never reach this with one.
340
+ */
341
+ export const darwinistExit = (subject: string, seat: Role, at: string): HansardEntry => ({
342
+ type: 'ACTOR_EXITED',
343
+ at,
344
+ actor: subject,
345
+ role: seat,
346
+ fields: {
347
+ 'Actor affected': subject,
348
+ 'Seat held': seat,
349
+ 'Exit type': 'EXIT_DARWINIST',
350
+ Declared: 'by the protocol — elimination',
351
+ Reason: 'eliminated: backed the losing side of a Division under an elimination protocol',
352
+ Appealable: 'no — elimination is final',
353
+ },
354
+ });
355
+
356
+ /* -------------------------------------------------------------------------- */
357
+ /* VETO */
358
+ /* -------------------------------------------------------------------------- */
359
+
360
+ export interface VetoInput extends ActInput {
361
+ readonly motion: string;
362
+ readonly reason: string;
363
+ /** Roles the Charter grants DOMAIN_VETO. */
364
+ readonly domain_veto: readonly Role[];
365
+ }
366
+
367
+ /**
368
+ * Veto a Motion.
369
+ *
370
+ * Two sources of the power: AUTHORITY holds it constitutionally, and a Charter
371
+ * may grant DOMAIN_VETO to a lower-trust role — the Jury in a Criminal Trial,
372
+ * a statistical reviewer in Peer Review. The second is a declared inversion of
373
+ * the trust hierarchy, never inferred from it.
374
+ */
375
+ export const veto = (input: VetoInput, hansard: string): {
376
+ readonly entry: HansardEntry;
377
+ readonly hansard: string;
378
+ } => {
379
+ requireConvened(input.state, 'VETO');
380
+
381
+ const constitutional = input.role === 'AUTHORITY';
382
+ const domain = input.domain_veto.includes(input.role);
383
+ if (!constitutional && !domain) {
384
+ throw new ActorError(
385
+ `${input.role} holds no veto — AUTHORITY, or a role granted DOMAIN_VETO by the Charter`,
386
+ );
387
+ }
388
+ if (input.reason.trim() === '') {
389
+ throw new ActorError('a veto must state its grounds');
390
+ }
391
+
392
+ const entry: HansardEntry = {
393
+ type: 'VETO_EXERCISED',
394
+ at: input.at,
395
+ actor: input.actor,
396
+ role: input.role,
397
+ fields: {
398
+ Motion: input.motion,
399
+ Basis: constitutional ? 'constitutional (AUTHORITY)' : 'DOMAIN_VETO granted by Charter',
400
+ Grounds: input.reason,
401
+ Effect: 'the Motion may not receive Assent while this veto stands',
402
+ },
403
+ };
404
+ return { entry, hansard: appendEntry(hansard, entry) };
405
+ };
406
+
407
+ /** Is there an outstanding veto against this Motion? (ADR-0004 Assent condition.) */
408
+ export const vetoOutstanding = (hansard: string, motion: string): boolean =>
409
+ parseEntries(hansard).some(
410
+ (e) => e.type === 'VETO_EXERCISED' && e.fields['Motion'] === motion,
411
+ );
412
+
413
+ /* -------------------------------------------------------------------------- */
414
+ /* SPAWN */
415
+ /* -------------------------------------------------------------------------- */
416
+
417
+ export interface SpawnInput extends ActInput {
418
+ /** Identifier of the child proceeding. */
419
+ readonly child: string;
420
+ readonly mandate: string;
421
+ }
422
+
423
+ /**
424
+ * Refer business to a sub-session.
425
+ *
426
+ * Records the referral only. Creating the child repo is the caller's job — this
427
+ * layer never performs I/O — but the parent's Hansard carries the referral so
428
+ * the chain from parent to child is on the record at both ends.
429
+ */
430
+ export const spawnChild = (input: SpawnInput, hansard: string): {
431
+ readonly entry: HansardEntry;
432
+ readonly hansard: string;
433
+ } => {
434
+ requireConvened(input.state, 'SPAWN');
435
+ if (input.role === 'MEMBER' || input.role === 'OBSERVER') {
436
+ throw new ActorError(`${input.role} may not refer business to a committee`);
437
+ }
438
+ if (input.mandate.trim() === '') {
439
+ throw new ActorError('a referral must state the committee mandate');
440
+ }
441
+
442
+ const entry: HansardEntry = {
443
+ type: 'COMMITTEE_SPAWNED',
444
+ at: input.at,
445
+ actor: input.actor,
446
+ role: input.role,
447
+ fields: {
448
+ Child: input.child,
449
+ Mandate: input.mandate,
450
+ Parent: input.state.session_guid,
451
+ },
452
+ };
453
+ return { entry, hansard: appendEntry(hansard, entry) };
454
+ };
455
+
456
+ /* -------------------------------------------------------------------------- */
457
+ /* Speaker order */
458
+ /* -------------------------------------------------------------------------- */
459
+
460
+ /**
461
+ * Suspend the sitting by Speaker order.
462
+ *
463
+ * The plainest of the suspension causes and, until now, unreachable: AUTHORITY
464
+ * halting proceedings for a stated reason. Distinct from a Point of Order (an
465
+ * actor asks) and from staleness (nobody acted) — here the Speaker decides, and
466
+ * the record should say so rather than borrowing another cause's label.
467
+ */
468
+ export const speakerOrder = (
469
+ at: string,
470
+ actor: string,
471
+ role: Role,
472
+ reason: string,
473
+ state: SessionStateFile,
474
+ hansard: string,
475
+ ): {
476
+ readonly entry: HansardEntry;
477
+ readonly hansard: string;
478
+ readonly state: SessionStateFile;
479
+ } => {
480
+ if (role !== 'AUTHORITY') {
481
+ throw new ActorError(`only AUTHORITY may suspend the sitting — ${actor} is ${role}`);
482
+ }
483
+ if (state.state !== 'CONVENED') {
484
+ throw new ActorError(`the session is already ${state.state}`);
485
+ }
486
+ if (reason.trim() === '') {
487
+ throw new ActorError('a Speaker order must state its reason');
488
+ }
489
+
490
+ const entry: HansardEntry = {
491
+ type: 'SPEAKER_ORDER',
492
+ at,
493
+ actor,
494
+ role,
495
+ fields: {
496
+ Reason: reason,
497
+ 'Session status': 'SUSPENDED — by order of the Speaker',
498
+ Resolution: 'the Speaker resumes the sitting',
499
+ },
500
+ };
501
+
502
+ return {
503
+ entry,
504
+ hansard: appendEntry(hansard, entry),
505
+ state: createState({
506
+ session_guid: state.session_guid,
507
+ protocol: state.protocol,
508
+ state: 'SUSPENDED',
509
+ quorum: state.quorum,
510
+ hansard_head: state.hansard_head,
511
+ updated_at: at,
512
+ suspension: {
513
+ cause: 'SPEAKER_ORDER',
514
+ since: at,
515
+ record_ref: 'HANSARD.md',
516
+ escalation_ref: null,
517
+ },
518
+ }),
519
+ };
520
+ };
521
+
522
+ /* -------------------------------------------------------------------------- */
523
+ /* Disputed exit */
524
+ /* -------------------------------------------------------------------------- */
525
+
526
+ /**
527
+ * Dispute one's own removal.
528
+ *
529
+ * RUNTIME.md § Actor Elimination: an actor may challenge their removal, and the
530
+ * challenge suspends the sitting pending a Speaker ruling. Only the removed
531
+ * actor may file — a third party disputing on someone's behalf would be the
532
+ * mirror image of the voluntold problem, manufacturing a grievance the actor
533
+ * never raised.
534
+ */
535
+ export const disputeExit = (
536
+ at: string,
537
+ actor: string,
538
+ grounds: string,
539
+ state: SessionStateFile,
540
+ hansard: string,
541
+ ): {
542
+ readonly entry: HansardEntry;
543
+ readonly hansard: string;
544
+ readonly state: SessionStateFile;
545
+ } => {
546
+ const removal = parseEntries(hansard)
547
+ .filter((e) => e.type === 'ACTOR_EXITED' && e.fields['Actor affected'] === actor)
548
+ .at(-1);
549
+
550
+ if (removal === undefined) {
551
+ throw new ActorError(`${actor} has no recorded exit to dispute`);
552
+ }
553
+ if (removal.actor === actor) {
554
+ throw new ActorError('an actor cannot dispute a departure they declared themselves');
555
+ }
556
+ if (grounds.trim() === '') {
557
+ throw new ActorError('a disputed exit must state its grounds');
558
+ }
559
+
560
+ const entry: HansardEntry = {
561
+ type: 'EXIT_DISPUTED',
562
+ at,
563
+ actor,
564
+ role: (removal.fields['Seat held'] ?? 'MEMBER') as Role,
565
+ fields: {
566
+ 'Actor affected': actor,
567
+ 'Removed by': removal.actor,
568
+ 'Original exit type': removal.fields['Exit type'] ?? 'unknown',
569
+ Grounds: grounds,
570
+ 'Session status': 'SUSPENDED — awaiting a Speaker ruling on the removal',
571
+ },
572
+ };
573
+
574
+ return {
575
+ entry,
576
+ hansard: appendEntry(hansard, entry),
577
+ state: createState({
578
+ session_guid: state.session_guid,
579
+ protocol: state.protocol,
580
+ state: 'SUSPENDED',
581
+ quorum: state.quorum,
582
+ hansard_head: state.hansard_head,
583
+ updated_at: at,
584
+ suspension: {
585
+ cause: 'DISPUTED_EXIT',
586
+ since: at,
587
+ record_ref: 'HANSARD.md',
588
+ escalation_ref: null,
589
+ },
590
+ }),
591
+ };
592
+ };
593
+
594
+ /**
595
+ * AUTHORITY rules on a disputed exit, and the sitting resumes.
596
+ *
597
+ * The dispute suspended the sitting pending a ruling; this supplies it. UPHELD
598
+ * overturns the removal and reinstates the actor to the seat they held; REVERSED
599
+ * lets the removal stand. Either way the ruling lifts the suspension — the record
600
+ * carries the decision and the House goes back to work. Only AUTHORITY rules
601
+ * (the CLI gates the role); a bad-faith ruling is visible to everyone who can
602
+ * read the repo, which is the only check on a captured chair the framework claims.
603
+ */
604
+ export const resolveDispute = (
605
+ at: string,
606
+ ruler: string,
607
+ ruling: 'UPHELD' | 'REVERSED',
608
+ subject: string,
609
+ state: SessionStateFile,
610
+ hansard: string,
611
+ ): {
612
+ readonly entries: readonly HansardEntry[];
613
+ readonly hansard: string;
614
+ readonly reinstated: boolean;
615
+ readonly state: SessionStateFile;
616
+ } => {
617
+ if (state.state !== 'SUSPENDED' || state.suspension?.cause !== 'DISPUTED_EXIT') {
618
+ throw new ActorError('the session is not under a disputed exit — there is nothing to rule on');
619
+ }
620
+ const entries = parseEntries(hansard);
621
+ const dispute = entries
622
+ .filter((e) => e.type === 'EXIT_DISPUTED' && e.fields['Actor affected'] === subject)
623
+ .at(-1);
624
+ if (dispute === undefined) {
625
+ throw new ActorError(`${subject} has no disputed exit on the record`);
626
+ }
627
+ const removal = entries
628
+ .filter((e) => e.type === 'ACTOR_EXITED' && e.fields['Actor affected'] === subject)
629
+ .at(-1);
630
+ const seat = (removal?.fields['Seat held'] ?? 'MEMBER') as Role;
631
+ const upheld = ruling === 'UPHELD';
632
+
633
+ const rulingEntry: HansardEntry = {
634
+ type: 'EXIT_RULING',
635
+ at,
636
+ actor: ruler,
637
+ role: 'AUTHORITY',
638
+ fields: {
639
+ 'Actor affected': subject,
640
+ Ruling: ruling,
641
+ Seat: seat,
642
+ Outcome: upheld
643
+ ? `the removal is overturned — ${subject} is reinstated to ${seat}`
644
+ : `the removal stands — ${subject} remains out`,
645
+ 'Session status': 'CONVENED — the sitting resumes',
646
+ },
647
+ };
648
+
649
+ const out: HansardEntry[] = [rulingEntry];
650
+ if (upheld) {
651
+ // Re-seat with a fresh ACTOR_HIRED so seats() counts the actor again. Not
652
+ // the hire() helper — that requires a CONVENED session, and we are resolving
653
+ // the suspension; the ruling itself is what lifts it.
654
+ out.push({
655
+ type: 'ACTOR_HIRED',
656
+ at,
657
+ actor: ruler,
658
+ role: seat,
659
+ fields: {
660
+ 'Actor affected': subject,
661
+ Role: seat,
662
+ Reason: 'reinstated after a disputed exit was upheld',
663
+ },
664
+ });
665
+ }
666
+
667
+ let doc = hansard;
668
+ for (const entry of out) doc = appendEntry(doc, entry);
669
+
670
+ return {
671
+ entries: out,
672
+ hansard: doc,
673
+ reinstated: upheld,
674
+ state: createState({
675
+ session_guid: state.session_guid,
676
+ protocol: state.protocol,
677
+ state: 'CONVENED',
678
+ quorum: state.quorum,
679
+ hansard_head: state.hansard_head,
680
+ updated_at: at,
681
+ updated_by: ruler,
682
+ suspension: null,
683
+ }),
684
+ };
685
+ };
686
+
687
+ /* -------------------------------------------------------------------------- */
688
+ /* DELEGATE challenge */
689
+ /* -------------------------------------------------------------------------- */
690
+
691
+ /**
692
+ * A DELEGATE formally challenges an AUTHORITY action (RUNTIME.md § DELEGATE
693
+ * Challenge Verb).
694
+ *
695
+ * The point is attribution, not obstruction: AUTHORITY still prevails, but the
696
+ * dissent is on the permanent record and names who objected and why. That is the
697
+ * framework's whole answer to a bad-faith chair — the record is visible to
698
+ * everyone who can read the repo. It does not suspend or overturn; it records.
699
+ *
700
+ * The `window_minutes` a Charter may set is a *pause* a hosted deployment with a
701
+ * scheduler can enforce; the local engine has no daemon (by design), so the
702
+ * durable mechanism here is the recorded, attributable challenge — the window is
703
+ * carried on the entry as the declared intent, not enforced by this function.
704
+ * Only a DELEGATE may challenge: it is their specific check on AUTHORITY.
705
+ */
706
+ export const challengeAction = (
707
+ at: string,
708
+ challenger: string,
709
+ challengerRole: Role,
710
+ against: string,
711
+ grounds: string,
712
+ windowMinutes: number,
713
+ hansard: string,
714
+ ): {
715
+ readonly entry: HansardEntry;
716
+ readonly hansard: string;
717
+ } => {
718
+ if (challengerRole !== 'DELEGATE') {
719
+ throw new ActorError('only a DELEGATE may challenge an AUTHORITY action');
720
+ }
721
+ if (against.trim() === '') {
722
+ throw new ActorError('a challenge must name the AUTHORITY action it disputes');
723
+ }
724
+ if (grounds.trim() === '') {
725
+ throw new ActorError('a challenge must state its grounds');
726
+ }
727
+
728
+ const entry: HansardEntry = {
729
+ type: 'DELEGATE_CHALLENGE',
730
+ at,
731
+ actor: challenger,
732
+ role: 'DELEGATE',
733
+ fields: {
734
+ Against: against,
735
+ Grounds: grounds,
736
+ Window: `${windowMinutes} minutes`,
737
+ Effect: 'the AUTHORITY action stands; this dissent is on the permanent record and attributable',
738
+ },
739
+ };
740
+
741
+ return { entry, hansard: appendEntry(hansard, entry) };
742
+ };