@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/cli.ts ADDED
@@ -0,0 +1,2174 @@
1
+ /**
2
+ * politik — command line interface.
3
+ *
4
+ * Thin shell over the library: every command parses arguments, calls a pure
5
+ * function, and renders the result. No governance logic lives here. If a
6
+ * decision is being made in this file, it is in the wrong place.
7
+ *
8
+ * Attribution: Steve Krisjanovs, Cordfuse
9
+ */
10
+
11
+ import { readFileSync } from 'node:fs';
12
+ import { readFile, writeFile, mkdir, rename } from 'node:fs/promises';
13
+ import { dirname, join, relative, resolve } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { parseArgs } from 'node:util';
16
+
17
+ import { isRole, type Role } from './canon.ts';
18
+ import { parseCharter, validateCharter } from './charter.ts';
19
+ import { dropWrit } from './init.ts';
20
+ import { initSessionRepo } from './git.ts';
21
+ import { parseState, serializeState, type SessionStateFile } from './state.ts';
22
+ import { parliamentaryTemplates } from './templates/parliamentary.ts';
23
+ import { generateProtocol, lintSource } from './protocol-sdk.ts';
24
+ import { diagnose } from './doctor.ts';
25
+ import { runTurn } from './runner.ts';
26
+ import { GitTransport } from './transport.ts';
27
+ import { conflictEntry, detectRecordConflicts, openConflicts, resolveConflict } from './conflict.ts';
28
+ import { parseEnvelope, isEligible, type Envelope } from './envelope.ts';
29
+ import { commitRecord, type CommitResult } from './git.ts';
30
+ import { discoverTree, rollUp, detectCascades, type FederationNode } from './federation.ts';
31
+ import { standings, type RankBy } from './standings.ts';
32
+ import {
33
+ isPairingFormat, matchCreatedEntry, matchDecidedEntry, matches, pairRound, reportMatch,
34
+ } from './tournament.ts';
35
+ import { cascadeAlerts, cascadeEntry, recordOnNode } from './tree.ts';
36
+ import {
37
+ linkEntry, projectAssent, projectDivision, projectEscalation,
38
+ projectionEntry, resolveProvider,
39
+ } from './projection.ts';
40
+ import { appendLedgerRow, checkCostCeiling, totals } from './ledger.ts';
41
+ import { checkHeartbeat, lastSnapshot, markStale, resume, snapshot } from './heartbeat.ts';
42
+ import { commitRuling, fileEscalation, type RulingOutcome } from './escalation.ts';
43
+ import {
44
+ challengeAction, demote, disputeExit, exitActor, hire, promote, resolveDispute, seats,
45
+ spawnChild, veto, vetoOutstanding, type ExitType,
46
+ } from './actors.ts';
47
+ import {
48
+ checkCapture, externalReview, fileCrisis, suspendForCrisis,
49
+ type CrisisRuling,
50
+ } from './crisis.ts';
51
+ import {
52
+ breakDeadlock, callDivision, castVote, cull, divisionCalled, divisionDecided, grantAssent,
53
+ isExitPolicy, isResolution, recordOutcome, suspendForDeadlock, tallyDivision, type Vote,
54
+ } from './division.ts';
55
+ import {
56
+ PROTOCOL_MODES, parseProtocol, roleTerm, term, type Protocol, type ProtocolMode,
57
+ } from './protocol.ts';
58
+ import { reviewIntegrity } from './integrity.ts';
59
+ import { checkTermination, isTerminationPolicy, lastStanding, prorogue, type Trigger } from './prorogation.ts';
60
+ import { appendEntry, parseEntries } from './hansard.ts';
61
+ import type { FileWrite } from './scm.ts';
62
+
63
+ /**
64
+ * Read from package.json rather than hardcoded. A duplicated version string
65
+ * goes stale the first time someone bumps one copy and not the other — which is
66
+ * exactly what happened at 0.3.0.
67
+ */
68
+ const VERSION: string = (() => {
69
+ const here = dirname(fileURLToPath(import.meta.url));
70
+ const pkg: unknown = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8'));
71
+ return typeof pkg === 'object' && pkg !== null && 'version' in pkg
72
+ ? String((pkg as { version: unknown }).version)
73
+ : 'unknown';
74
+ })();
75
+
76
+ const USAGE = `politik — governed multi-agent sessions on git
77
+
78
+ Usage
79
+ politik version
80
+ politik scaffold --dir <dir> [--protocol parliamentary] [--quorum <n>] [--parent <dir>]
81
+ politik doctor
82
+ politik protocol lint <manifest.yml>
83
+ politik protocol new <name> [--mode <mode>] [--out <dir>]
84
+ politik validate <charter.md> [--protocol <name>]
85
+ politik init --charter <path> --speaker <handle> [--dir <dir>] [--guid <id>] [--standalone]
86
+ politik run --agent <id> --actor <h> --role <ROLE> (--task <text> | --claim)
87
+ politik division call --motion <id> --actor <h> --role <ROLE> [--reviewers a,b]
88
+ politik division vote --motion <id> --actor <h> --role <ROLE> --vote AYE|NO|ABSTAIN
89
+ politik division tally --motion <id>
90
+ politik division break --motion <id> --actor <handle> --decide carry|reject # break a DEADLOCK
91
+ politik assent --motion <id> --actor <h> --role AUTHORITY
92
+ politik crisis file --actor <h> --role <ROLE> --against <speaker> --grounds <text>
93
+ politik crisis check
94
+ politik crisis review --reviewer <h> --accused <speaker> --ruling UPHELD|DISMISSED --reasons <text>
95
+ politik escalate --actor <h> --role <ROLE> --title <t> --body <text> [--seq <n>]
96
+ politik rule --seq <n> --actor <h> --outcome UPHELD|REVERSED|NOTED --body <text>
97
+ politik challenge --actor <delegate> --against <action> --grounds <text> [--window <min>]
98
+ politik actor hire|promote|demote|exit|veto|spawn ... (see below)
99
+ politik actor dispute --actor <removed> --grounds <text> # challenge one's own removal
100
+ politik actor reinstate --subject <h> --actor <speaker> --ruling UPHELD|REVERSED
101
+ politik actor list
102
+ politik heartbeat [--dir <dir>] [--suspend]
103
+ politik snapshot [--dir <dir>] [--completed a,b] [--in-flight a] [--pending a]
104
+ politik resume --actor <handle> [--dir <dir>]
105
+ politik conflict check [--dir <dir>]
106
+ politik conflict resolve --motions a,b --actor <h> --role <ROLE> --resolution <t>
107
+ politik broadcast --target <ROLE> --slots <n> --task <text> [--dir <dir>]
108
+ politik motion link --motion <id> --pr <n> [--url <u>]
109
+ politik ledger [--dir <dir>]
110
+ politik status [--dir <dir>]
111
+ politik hansard [--dir <dir>] # the record, in the protocol's vocabulary
112
+ politik integrity [--dir <dir>] # scan the record for bad-faith patterns
113
+ politik prorogue --dir <dir> --actor <handle> --role <ROLE> --trigger <TRIGGER>
114
+ politik standings [--dir <dir>] [--by win-loss|survival] # score a competitive protocol
115
+ politik pair --format swiss|round-robin|single-elim [--dir <dir>] # pair the next round of MATCHes
116
+ politik match report --match <id> --winner <contestant> [--actor <referee>]
117
+ politik match list [--dir <dir>]
118
+ politik registry [--dir <root>] [--state <STATE>] # the whole tree, at a glance
119
+ politik cascade [--dir <root>] # warn where a fault repeats across siblings
120
+
121
+ Commands
122
+ version Print the version.
123
+ scaffold Write a protocol's Charter, roles and Order Paper for editing.
124
+ doctor Probe this host: can it run a session, and with which agents?
125
+ protocol Lint a protocol manifest, or generate a new one.
126
+ validate Parse a CHARTER.md and run the Writ Drop rules. Writes nothing.
127
+ init Drop the Writ — create a session repo file set on disk.
128
+ run Seat an agent, give it the business, record what it did.
129
+ division Call a Division, cast a vote, or tally the result.
130
+ assent Enact a carried Motion. The Division decides; Assent enacts.
131
+ crisis File, check, or externally review a constitutional crisis.
132
+ escalate Raise a Point of Order. Suspends the sitting.
133
+ rule Rule on a Point of Order as AUTHORITY. Resumes the sitting.
134
+ challenge A DELEGATE disputes an AUTHORITY action — recorded, attributable, non-binding.
135
+ actor Seat, move or remove actors; exercise a veto; refer to committee.
136
+ heartbeat Has the proceeding gone quiet? --suspend marks it STALE.
137
+ snapshot Commit a STATE_SNAPSHOT so a new agent can continue the work.
138
+ resume Resume a STALE proceeding.
139
+ conflict Find or resolve Motions touching the same files. Routine, not a fault.
140
+ broadcast Put business on the bus for peers to claim.
141
+ motion Bind a Motion to a pull request so Assent can enact it.
142
+ ledger Total the session's measured cost.
143
+ status Read STATE.json and summarise the proceeding.
144
+ prorogue Close a proceeding permanently and seal the Hansard.
145
+ standings Score a competitive protocol from the record (win-loss or survival).
146
+ pair Pair the next round of MATCHes by format (swiss, round-robin, single-elim).
147
+ match Report a MATCH result, or list the bracket.
148
+ registry Walk the tree: every session, its state and cost, with a roll-up.
149
+ cascade Warn where a fault repeats across sibling sessions.
150
+ `;
151
+
152
+ /* -------------------------------------------------------------------------- */
153
+ /* Output */
154
+ /* -------------------------------------------------------------------------- */
155
+
156
+ const out = (line = '') => process.stdout.write(`${line}\n`);
157
+ const err = (line: string) => process.stderr.write(`${line}\n`);
158
+
159
+ /**
160
+ * A supplied --role/--target must name a CANON role; an absent one falls back to
161
+ * a default downstream. Governance-critical commands (Division, actors) already
162
+ * reject a bad role in their pure layer; this guards the record-writing commands
163
+ * that only carry the role as attribution, so a garbage string never reaches the
164
+ * immutable Hansard.
165
+ */
166
+ const badRole = (value: string | undefined): boolean => value !== undefined && !isRole(value);
167
+
168
+ /** Exit codes: 0 success, 1 refusal (invalid input), 2 usage error. */
169
+ const EXIT = { OK: 0, REFUSED: 1, USAGE: 2 } as const;
170
+
171
+ /* -------------------------------------------------------------------------- */
172
+ /* Helpers */
173
+ /* -------------------------------------------------------------------------- */
174
+
175
+ const writeFiles = async (dir: string, files: readonly FileWrite[]): Promise<void> => {
176
+ for (const file of files) {
177
+ const target = join(dir, file.path);
178
+ await mkdir(dirname(target), { recursive: true });
179
+ await writeFile(target, file.content, 'utf8');
180
+ }
181
+ };
182
+
183
+ const readIfPresent = async (path: string): Promise<string | null> => {
184
+ try {
185
+ return await readFile(path, 'utf8');
186
+ } catch {
187
+ return null;
188
+ }
189
+ };
190
+
191
+ /* -------------------------------------------------------------------------- */
192
+ /* Commands */
193
+ /* -------------------------------------------------------------------------- */
194
+
195
+ /**
196
+ * Scaffold a protocol's editable documents.
197
+ *
198
+ * Deliberately separate from `init`: scaffolding produces prose for a Speaker to
199
+ * edit, while `init` drops the Writ and opens the session. Conflating them would
200
+ * mean a session convened on an unread template.
201
+ */
202
+ const cmdScaffold = async (argv: readonly string[]): Promise<number> => {
203
+ const { values } = parseArgs({
204
+ args: [...argv],
205
+ options: {
206
+ dir: { type: 'string' },
207
+ out: { type: 'string' },
208
+ protocol: { type: 'string' },
209
+ quorum: { type: 'string' },
210
+ resolution: { type: 'string' },
211
+ exit: { type: 'string' },
212
+ termination: { type: 'string' },
213
+ escalation: { type: 'string' },
214
+ parent: { type: 'string' },
215
+ },
216
+ });
217
+
218
+ // Resolve the named protocol's manifest so its declared mechanics (ADR-0007)
219
+ // and escalation flag are inherited into the Charter. Explicit flags below
220
+ // still override. This is what makes `scaffold --protocol battle-royale`
221
+ // produce a Charter that actually behaves like one.
222
+ const protocol = values.protocol ?? 'parliamentary';
223
+ const manifestPath = join(
224
+ dirname(fileURLToPath(import.meta.url)), '..', 'protocols', `${protocol}.yml`,
225
+ );
226
+ const manifestSrc = await readIfPresent(manifestPath);
227
+ if (manifestSrc === null) {
228
+ err(`scaffold: unknown protocol "${protocol}" — no manifest at protocols/${protocol}.yml`);
229
+ return EXIT.USAGE;
230
+ }
231
+ const manifest = parseProtocol(manifestSrc);
232
+ if (!manifest.ok) {
233
+ err(`scaffold: protocols/${protocol}.yml is not a valid manifest`);
234
+ return EXIT.USAGE;
235
+ }
236
+
237
+ const quorum = values.quorum === undefined ? undefined : Number(values.quorum);
238
+ if (quorum !== undefined && (!Number.isInteger(quorum) || quorum < 1)) {
239
+ err('scaffold: --quorum must be an integer >= 1');
240
+ return EXIT.USAGE;
241
+ }
242
+
243
+ // Mechanics flags (ADR-0007) — validate up front so a typo does not silently
244
+ // default to Parliament.
245
+ if (values.resolution !== undefined && !isResolution(values.resolution)) {
246
+ err(`scaffold: --resolution must be majority | supermajority | unanimity`);
247
+ return EXIT.USAGE;
248
+ }
249
+ if (values.exit !== undefined && !isExitPolicy(values.exit)) {
250
+ err(`scaffold: --exit must be division | elimination | none`);
251
+ return EXIT.USAGE;
252
+ }
253
+ if (values.termination !== undefined && !isTerminationPolicy(values.termination)) {
254
+ err(`scaffold: --termination must be objective | last-standing | verdict`);
255
+ return EXIT.USAGE;
256
+ }
257
+ if (values.escalation !== undefined && values.escalation !== 'enabled' && values.escalation !== 'disabled') {
258
+ err(`scaffold: --escalation must be enabled | disabled`);
259
+ return EXIT.USAGE;
260
+ }
261
+
262
+ // Session directory: `--dir` is the standard across every other command;
263
+ // `--out` is kept as an alias so a scaffold script written against the old
264
+ // flag still works.
265
+ const dir = values.dir ?? values.out ?? '.';
266
+ // Explicit flag > manifest default > template default.
267
+ const m = manifest.protocol.mechanics;
268
+ // Monorepo placement (ADR-0008): --parent nests this session under a parent
269
+ // node in the same tree. inherits_from is the child->parent relative path, so
270
+ // the lineage resolves from within the session's own directory. init detects
271
+ // the enclosing repo and commits the writ drop there rather than nesting a repo.
272
+ const inherits_from = values.parent === undefined ? null : (relative(dir, values.parent) || '.');
273
+ const files = parliamentaryTemplates({
274
+ protocol,
275
+ ...(inherits_from === null ? {} : { inherits_from }),
276
+ ...(quorum === undefined ? {} : { quorum }),
277
+ resolution: values.resolution ?? m.resolution,
278
+ exit: values.exit ?? m.exit,
279
+ termination: values.termination ?? m.termination,
280
+ escalation: values.escalation ?? (manifest.protocol.no_escalation ? 'disabled' : 'enabled'),
281
+ });
282
+ await writeFiles(dir, files);
283
+
284
+ out(`SCAFFOLDED ${protocol}`);
285
+ for (const file of files) out(` ${file.path}`);
286
+ out('');
287
+ out(`Edit the Standing Orders, then: politik init --charter ${join(dir, 'CHARTER.md')} --speaker <handle>`);
288
+ return EXIT.OK;
289
+ };
290
+
291
+ /** Probe the host and report whether a session can run here. */
292
+ const cmdDoctor = async (): Promise<number> => {
293
+ const diagnosis = await diagnose();
294
+ out(`platform ${diagnosis.platform}`);
295
+ out('');
296
+ for (const check of diagnosis.checks) {
297
+ const badge =
298
+ check.status === 'ok' ? '[ OK ]' : check.status === 'warn' ? '[WARN]' : '[FAIL]';
299
+ out(`${badge} ${check.name.padEnd(10)} ${check.detail}`);
300
+ }
301
+ out('');
302
+ out(diagnosis.ready ? 'READY — this host can run a Politik session' : 'NOT READY');
303
+ return diagnosis.ready ? EXIT.OK : EXIT.REFUSED;
304
+ };
305
+
306
+ /** `politik protocol lint <file>` / `politik protocol new <name>`. */
307
+ const cmdProtocol = async (argv: readonly string[]): Promise<number> => {
308
+ const [verb, ...rest] = argv;
309
+
310
+ if (verb === 'lint') {
311
+ const path = rest[0];
312
+ if (path === undefined) {
313
+ err('protocol lint: a manifest path is required');
314
+ return EXIT.USAGE;
315
+ }
316
+ const source = await readIfPresent(path);
317
+ if (source === null) {
318
+ err(`protocol lint: cannot read ${path}`);
319
+ return EXIT.USAGE;
320
+ }
321
+
322
+ const result = lintSource(source);
323
+ for (const finding of result.findings) {
324
+ const line = ` ${finding.severity === 'error' ? '[ERROR]' : '[WARN] '} ${finding.field}: ${finding.message}`;
325
+ if (finding.severity === 'error') err(line);
326
+ else out(line);
327
+ }
328
+
329
+ if (!result.ok) {
330
+ err('PROTOCOL INVALID');
331
+ return EXIT.REFUSED;
332
+ }
333
+ out(`PROTOCOL VALID${result.findings.length > 0 ? ` (${result.findings.length} warning(s))` : ''}`);
334
+ return EXIT.OK;
335
+ }
336
+
337
+ if (verb === 'new') {
338
+ const { values, positionals } = parseArgs({
339
+ args: rest,
340
+ options: { mode: { type: 'string' }, out: { type: 'string' } },
341
+ allowPositionals: true,
342
+ });
343
+ const name = positionals[0];
344
+ if (name === undefined) {
345
+ err('protocol new: a protocol name is required');
346
+ return EXIT.USAGE;
347
+ }
348
+ const mode = (values.mode ?? 'constitutional') as ProtocolMode;
349
+ if (!(PROTOCOL_MODES as readonly string[]).includes(mode)) {
350
+ err(`protocol new: --mode must be one of ${PROTOCOL_MODES.join(' | ')}`);
351
+ return EXIT.USAGE;
352
+ }
353
+
354
+ const manifest = generateProtocol({ name, mode });
355
+ if (values.out === undefined) {
356
+ out(manifest);
357
+ } else {
358
+ await writeFiles(values.out, [{ path: `${name}.yml`, content: manifest }]);
359
+ out(`GENERATED ${join(values.out, `${name}.yml`)}`);
360
+ out(` politik protocol lint ${join(values.out, `${name}.yml`)}`);
361
+ }
362
+ return EXIT.OK;
363
+ }
364
+
365
+ err(`protocol: unknown verb "${verb ?? ''}" — expected lint | new`);
366
+ return EXIT.USAGE;
367
+ };
368
+
369
+ const cmdValidate = async (argv: readonly string[]): Promise<number> => {
370
+ const { values, positionals } = parseArgs({
371
+ args: [...argv],
372
+ options: { protocol: { type: 'string' } },
373
+ allowPositionals: true,
374
+ });
375
+
376
+ const path = positionals[0];
377
+ if (path === undefined) {
378
+ err('validate: a CHARTER.md path is required');
379
+ return EXIT.USAGE;
380
+ }
381
+
382
+ const source = await readIfPresent(path);
383
+ if (source === null) {
384
+ err(`validate: cannot read ${path}`);
385
+ return EXIT.USAGE;
386
+ }
387
+
388
+ const parsed = parseCharter(source);
389
+ if (!parsed.ok) {
390
+ err('CHARTER INVALID — the session would never open');
391
+ for (const issue of parsed.issues) err(` ${issue.field}: ${issue.message}`);
392
+ return EXIT.REFUSED;
393
+ }
394
+
395
+ const result = validateCharter(
396
+ parsed.charter,
397
+ values.protocol === undefined ? undefined : { name: values.protocol },
398
+ );
399
+
400
+ if (!result.valid) {
401
+ err('CHARTER INVALID — the session would never open');
402
+ for (const issue of result.issues) {
403
+ const rule = issue.rule === undefined ? '' : ` (rule ${issue.rule})`;
404
+ err(` ${issue.field}: ${issue.message}${rule}`);
405
+ }
406
+ return EXIT.REFUSED;
407
+ }
408
+
409
+ out('CHARTER VALID');
410
+ out(` protocol ${parsed.charter.protocol}`);
411
+ out(` quorum ${parsed.charter.session.quorum}`);
412
+ out(` merge strategy ${parsed.charter.session.merge_strategy}`);
413
+ out(` assent ${parsed.charter.session.assent}`);
414
+ out(` constituencies ${parsed.charter.constituencies.length}`);
415
+ return EXIT.OK;
416
+ };
417
+
418
+ const cmdInit = async (argv: readonly string[]): Promise<number> => {
419
+ const { values } = parseArgs({
420
+ args: [...argv],
421
+ options: {
422
+ charter: { type: 'string' },
423
+ speaker: { type: 'string' },
424
+ dir: { type: 'string' },
425
+ out: { type: 'string' },
426
+ guid: { type: 'string' },
427
+ protocol: { type: 'string' },
428
+ standalone: { type: 'boolean' },
429
+ },
430
+ });
431
+
432
+ if (values.charter === undefined || values.speaker === undefined) {
433
+ err('init: --charter and --speaker are required');
434
+ return EXIT.USAGE;
435
+ }
436
+
437
+ const source = await readIfPresent(values.charter);
438
+ if (source === null) {
439
+ err(`init: cannot read ${values.charter}`);
440
+ return EXIT.USAGE;
441
+ }
442
+
443
+ const result = dropWrit({
444
+ charter_source: source,
445
+ session_guid: values.guid ?? crypto.randomUUID(),
446
+ now: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
447
+ speaker: values.speaker,
448
+ protocol: values.protocol === undefined ? undefined : { name: values.protocol },
449
+ });
450
+
451
+ // `--dir` is the standard flag; `--out` stays an accepted alias here.
452
+ const dir = values.dir ?? values.out ?? '.';
453
+ await writeFiles(dir, result.files);
454
+
455
+ if (!result.ok) {
456
+ err('WRIT DROP REFUSED — session did not open');
457
+ for (const issue of result.issues) {
458
+ const rule = issue.rule === undefined ? '' : ` (rule ${issue.rule})`;
459
+ err(` ${issue.field}: ${issue.message}${rule}`);
460
+ }
461
+ err('');
462
+ err(`The refusal is on the record in ${join(dir, 'HANSARD.md')}`);
463
+ return EXIT.REFUSED;
464
+ }
465
+
466
+ // Writ Drop creates the session repo. On a local session that means making
467
+ // `dir` a git repo, or the record silently never commits. Idempotent — an
468
+ // existing (e.g. cloned GitHub) repo is left alone.
469
+ const repo = await initSessionRepo(dir, values.speaker, result.state.session_guid, undefined, {
470
+ standalone: values.standalone === true,
471
+ });
472
+
473
+ out('WRIT DROPPED');
474
+ out(` session ${result.state.session_guid}`);
475
+ out(` protocol ${result.charter.protocol}`);
476
+ out(` state ${result.state.state}`);
477
+ out(` files ${result.files.length} written to ${dir}`);
478
+ out(` git ${repo.reason}${repo.sha ? ` (${repo.sha.slice(0, 7)})` : ''}`);
479
+ return EXIT.OK;
480
+ };
481
+
482
+
483
+ /* -------------------------------------------------------------------------- */
484
+ /* Division helpers */
485
+ /* -------------------------------------------------------------------------- */
486
+
487
+ /**
488
+ * The protocol a session runs, resolved from its manifest for vocabulary
489
+ * translation (ADR-0007 / protocol.ts). The stored record stays CANON — the
490
+ * engine reads it — so translation is presentation only, applied to what the
491
+ * user sees. Null for a protocol with no shipped manifest; callers fall back to
492
+ * the CANON term, which is exactly what roleTerm/term do.
493
+ */
494
+ const sessionProtocol = async (protocolName: string): Promise<Protocol | null> => {
495
+ const path = join(dirname(fileURLToPath(import.meta.url)), '..', 'protocols', `${protocolName}.yml`);
496
+ const src = await readIfPresent(path);
497
+ if (src === null) return null;
498
+ const parsed = parseProtocol(src);
499
+ return parsed.ok ? parsed.protocol : null;
500
+ };
501
+
502
+ /** Render a CANON role in the session protocol's vocabulary, or CANON if none. */
503
+ const asRoleTerm = (protocol: Protocol | null, role: string): string =>
504
+ protocol === null ? role : roleTerm(protocol, role as never);
505
+
506
+ /** Render a CANON primitive/verb in the session protocol's vocabulary. */
507
+ const asTerm = (protocol: Protocol | null, canon: string): string =>
508
+ protocol === null ? canon : term(protocol, canon);
509
+
510
+ const loadSession = async (dir: string) => {
511
+ const stateRaw = await readIfPresent(join(dir, 'STATE.json'));
512
+ const state = stateRaw === null ? null : parseState(stateRaw);
513
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
514
+ const charterRaw = await readIfPresent(join(dir, 'CHARTER.md'));
515
+ const charter = charterRaw === null ? null : parseCharter(charterRaw);
516
+ return { state, hansard, charter: charter?.ok === true ? charter.charter : null };
517
+ };
518
+
519
+ /**
520
+ * Atomic file write: land a complete temp file, then rename it over the target.
521
+ *
522
+ * The Hansard is the immutable record — the whole point of Politik — and a
523
+ * half-written record is worse than none. A plain writeFile opens with O_TRUNC:
524
+ * an interrupt between the truncate and the write (SIGPIPE from a closed `| head`,
525
+ * Ctrl-C, SIGTERM, a crash) leaves the file at zero bytes, and the operator has
526
+ * already been told the act succeeded. rename(2) is atomic on a POSIX filesystem,
527
+ * so the target is only ever replaced by a fully-written file; an interrupted
528
+ * write orphans a `.tmp` and leaves the record intact. This is the durability the
529
+ * Standing Orders assume when they say the record is the source of truth.
530
+ */
531
+ const atomicWrite = async (path: string, content: string): Promise<void> => {
532
+ const tmp = `${path}.tmp`;
533
+ await writeFile(tmp, content, 'utf8');
534
+ await rename(tmp, path);
535
+ };
536
+
537
+ const writeHansard = (dir: string, hansard: string) =>
538
+ atomicWrite(join(dir, 'HANSARD.md'), hansard);
539
+
540
+ const writeState = (dir: string, state: SessionStateFile) =>
541
+ atomicWrite(join(dir, 'STATE.json'), serializeState(state));
542
+
543
+ /**
544
+ * Persist a governance act to the record.
545
+ *
546
+ * Writing the file is not enough: the Standing Orders this framework ships say
547
+ * uncommitted work does not exist, and that binds the engine as much as an
548
+ * actor. Reports what happened rather than failing silently — a session run
549
+ * outside git is legitimate, but the operator should know the record is not
550
+ * durable.
551
+ */
552
+ /**
553
+ * Record a governance act in the LEDGER. Governance acts spawn no agent, so
554
+ * their cost is `unmeasured` — but the act still belongs in the cost record, or
555
+ * the LEDGER accounts for a session's agent turns and nothing else, and the
556
+ * "replaces a ticket system" claim covers exactly these acts (AUDIT). Loads the
557
+ * Charter itself so a caller needs only the act's who and what. Call before the
558
+ * commit, which then includes the new row.
559
+ */
560
+ const logAct = async (dir: string, actor: string, role: Role, item: string): Promise<void> => {
561
+ const { charter } = await loadSession(dir);
562
+ if (charter === null || !charter.ledger.enabled) return;
563
+ const path = join(dir, charter.ledger.path);
564
+ const doc = (await readIfPresent(path)) ?? '';
565
+ await atomicWrite(
566
+ path,
567
+ appendLedgerRow(doc, { at: nowStamp(), actor, role, item, elapsed_ms: 0, usage: null }),
568
+ );
569
+ };
570
+
571
+ /**
572
+ * Commit the act and return the result WITHOUT printing — "record, then report."
573
+ *
574
+ * The git commit is the durable point and touches no stdout, so a closed pipe
575
+ * (`… | head`, Ctrl-C) cannot interrupt it. Printing — which *can* fault on a
576
+ * closed pipe — happens only after this returns, via reportCommit(). So an
577
+ * interrupt can never land between telling the operator "success" and the record
578
+ * actually existing: every command writes, commits, then reports.
579
+ */
580
+ const commitAct = (
581
+ dir: string,
582
+ message: string,
583
+ extra: readonly string[] = [],
584
+ ): Promise<CommitResult> =>
585
+ commitRecord(dir, message, [
586
+ 'HANSARD.md',
587
+ 'STATE.json',
588
+ 'LEDGER.md',
589
+ '.politik/LEDGER.md',
590
+ ...extra,
591
+ ]);
592
+
593
+ /** Print a commit's outcome. Call only AFTER the commit, as part of the report. */
594
+ const reportCommit = (result: CommitResult): void => {
595
+ if (result.committed) out(` recorded ${result.sha?.slice(0, 8) ?? ''}`);
596
+ else if (result.reason === 'not a git repository') {
597
+ out(' [WARN] not a git repository — the record is not durable');
598
+ }
599
+ };
600
+
601
+ const nowStamp = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
602
+
603
+ /** Provider flags shared by every command that can project. */
604
+ const PROVIDER_OPTS = {
605
+ repo: { type: 'string' },
606
+ token: { type: 'string' },
607
+ } as const;
608
+
609
+ /**
610
+ * Report a projection and put it on the record.
611
+ *
612
+ * Both outcomes are recorded. A reader must be able to see that a Motion
613
+ * carried and its merge did not land — the gap between decision and effect is
614
+ * exactly what a governance record exists to expose.
615
+ */
616
+ /**
617
+ * Write the projection entry to the record and return the line to print later.
618
+ *
619
+ * Write-now, report-later: the projection entry must be on the record before the
620
+ * commit, but its "projected / not projected" line is output and must wait until
621
+ * after the commit (see commitAct). Callers append this to their report block.
622
+ */
623
+ const applyProjection = async (
624
+ dir: string,
625
+ act: string,
626
+ result: { projected: boolean; detail: string; ref: string | null },
627
+ hansard: string,
628
+ ): Promise<string> => {
629
+ await writeHansard(dir, appendEntry(hansard, projectionEntry(act, result, nowStamp())));
630
+ return ` ${result.projected ? 'projected' : 'not projected'} — ${result.detail}`;
631
+ };
632
+
633
+ /** `politik division call|vote|tally`. */
634
+ const cmdDivision = async (argv: readonly string[]): Promise<number> => {
635
+ const [verb, ...rest] = argv;
636
+ const { values } = parseArgs({
637
+ args: rest,
638
+ options: {
639
+ dir: { type: 'string' }, motion: { type: 'string' }, actor: { type: 'string' },
640
+ role: { type: 'string' }, vote: { type: 'string' }, reviewers: { type: 'string' },
641
+ decide: { type: 'string' },
642
+ ...PROVIDER_OPTS,
643
+ },
644
+ });
645
+
646
+ const dir = values.dir ?? '.';
647
+ const { state, hansard, charter } = await loadSession(dir);
648
+ if (state === null || charter === null) {
649
+ err(`division: ${dir} is not a session repo`);
650
+ return EXIT.USAGE;
651
+ }
652
+ if (values.motion === undefined) {
653
+ err('division: --motion is required');
654
+ return EXIT.USAGE;
655
+ }
656
+ const protocol = await sessionProtocol(charter.protocol);
657
+
658
+ try {
659
+ if (verb === 'call') {
660
+ if (values.actor === undefined) { err('division call: --actor is required'); return EXIT.USAGE; }
661
+ const result = callDivision({
662
+ motion: values.motion, at: nowStamp(), actor: values.actor,
663
+ role: (values.role ?? 'OPERATOR') as never,
664
+ reviewers: (values.reviewers ?? '').split(',').filter((r) => r.length > 0),
665
+ state,
666
+ }, hansard);
667
+ await writeHansard(dir, result.hansard);
668
+ const { provider } = resolveProvider({ repo: values.repo, token: values.token });
669
+ const reviewers = (values.reviewers ?? '').split(',').filter((r) => r.length > 0);
670
+ const projected = await projectDivision(provider, result.hansard, values.motion, reviewers);
671
+ const projMsg = await applyProjection(dir, `DIVISION_CALLED ${values.motion}`, projected, result.hansard);
672
+
673
+ const rec = await commitAct(dir, `DIVISION_CALLED — ${values.motion}`);
674
+ out(`${asTerm(protocol, 'DIVISION')} called on ${values.motion}`);
675
+ out(projMsg);
676
+ reportCommit(rec);
677
+ return EXIT.OK;
678
+ }
679
+
680
+ if (verb === 'vote') {
681
+ if (values.actor === undefined || values.vote === undefined) {
682
+ err('division vote: --actor and --vote are required'); return EXIT.USAGE;
683
+ }
684
+ const result = castVote({
685
+ motion: values.motion, at: nowStamp(), actor: values.actor,
686
+ role: (values.role ?? 'OPERATOR') as never,
687
+ vote: values.vote.toUpperCase() as Vote, state,
688
+ }, hansard);
689
+ await writeHansard(dir, result.hansard);
690
+ const rec = await commitAct(dir, `VOTE_CAST — ${values.actor} on ${values.motion}`);
691
+ out(`${asTerm(protocol, 'VOTE')} recorded — ${values.actor}: ${values.vote.toUpperCase()}`);
692
+ reportCommit(rec);
693
+ return EXIT.OK;
694
+ }
695
+
696
+ if (verb === 'tally') {
697
+ if (!divisionCalled(hansard, values.motion)) {
698
+ err(`division refused: no Division has been called on ${values.motion}`);
699
+ return EXIT.REFUSED;
700
+ }
701
+ if (divisionDecided(hansard, values.motion)) {
702
+ err(`division refused: the Division on ${values.motion} is already decided — its outcome is on the record`);
703
+ return EXIT.REFUSED;
704
+ }
705
+ const outcome = tallyDivision(
706
+ hansard, values.motion, charter.session.quorum, null, charter.mechanics.resolution,
707
+ );
708
+
709
+ // A tie with quorum is a DEADLOCK, not a rejection (ADR-0004 Proposal 4):
710
+ // the House could not decide, so the sitting suspends for AUTHORITY to
711
+ // break rather than silently recording a loss. Only genuine ties suspend;
712
+ // a majority either way falls through to the ordinary outcome below.
713
+ if (!outcome.carried && outcome.ayes === outcome.noes && outcome.quorum_met) {
714
+ const deadlock = suspendForDeadlock(outcome, nowStamp(), state, hansard);
715
+ await writeHansard(dir, deadlock.hansard);
716
+ await writeState(dir, deadlock.state);
717
+ await logAct(dir, values.actor ?? 'RECORD', (values.role ?? 'OPERATOR') as never, `DEADLOCK ${values.motion}`);
718
+ const rec = await commitAct(dir, `DEADLOCK — ${values.motion}`);
719
+ out(`${asTerm(protocol, 'MOTION')} DEADLOCKED — tied ${outcome.ayes} all, no majority`);
720
+ out(' the session is SUSPENDED — AUTHORITY must break the tie:');
721
+ out(` politik division break --motion ${values.motion} --actor <speaker> --decide carry|reject`);
722
+ reportCommit(rec);
723
+ return EXIT.REFUSED;
724
+ }
725
+
726
+ const result = recordOutcome(outcome, nowStamp(), values.actor ?? 'RECORD',
727
+ (values.role ?? 'OPERATOR') as never, hansard);
728
+ // exit: elimination culls the losing side (ADR-0007). The outcome is
729
+ // recorded first, then the cull it triggers, so the record reads in order.
730
+ let doc = result.hansard;
731
+ const eliminated = cull(doc, values.motion, charter.mechanics.exit, nowStamp());
732
+ for (const entry of eliminated) doc = appendEntry(doc, entry);
733
+
734
+ // termination override point (ADR-0007). last-standing seals the moment a
735
+ // cull leaves one seated actor — checked only after an actual elimination,
736
+ // so a fresh session is never mistaken for a finished one. verdict seals the
737
+ // moment a Division carries: a decision has been reached and the body rises.
738
+ let terminationMsg: string | null = null;
739
+ const seal = async (trigger: Trigger, summary: string, msg: string) => {
740
+ const end = prorogue(
741
+ { at: nowStamp(), actor: 'RECORD', role: 'OPERATOR' as never, trigger, state, summary },
742
+ doc,
743
+ );
744
+ doc = end.hansard;
745
+ await writeState(dir, end.state);
746
+ terminationMsg = msg;
747
+ };
748
+ if (charter.mechanics.termination === 'last-standing' && eliminated.length > 0) {
749
+ const standing = lastStanding(doc);
750
+ if (standing.terminate) {
751
+ await seal(
752
+ 'TRIGGER_LAST_STANDING' as Trigger,
753
+ standing.survivor ? `Last standing: ${standing.survivor}` : 'No actors remain',
754
+ `last standing: ${standing.survivor ?? 'none'}`,
755
+ );
756
+ }
757
+ } else if (charter.mechanics.termination === 'verdict' && outcome.carried) {
758
+ await seal(
759
+ 'TRIGGER_VERDICT' as Trigger,
760
+ `Verdict reached on ${values.motion}`,
761
+ `verdict reached on ${values.motion}`,
762
+ );
763
+ }
764
+
765
+ await writeHansard(dir, doc);
766
+ await logAct(dir, values.actor ?? 'RECORD', (values.role ?? 'OPERATOR') as never,
767
+ `${outcome.carried ? 'MOTION_CARRIED' : 'MOTION_REJECTED'} ${values.motion}`);
768
+ const rec = await commitAct(dir, `${outcome.carried ? 'MOTION_CARRIED' : 'MOTION_REJECTED'} — ${values.motion}`);
769
+
770
+ out(outcome.carried ? `${asTerm(protocol, 'MOTION')} CARRIED` : `${asTerm(protocol, 'MOTION')} NOT CARRIED`);
771
+ out(` ayes ${outcome.ayes} noes ${outcome.noes} abstentions ${outcome.abstentions}`);
772
+ out(` quorum ${outcome.quorum_met ? 'met' : 'NOT MET'}`);
773
+ out(` ${outcome.reason}`);
774
+ if (eliminated.length > 0) {
775
+ out(` eliminated ${eliminated.length}: ${eliminated.map((e) => e.fields?.['Actor affected']).join(', ')}`);
776
+ }
777
+ if (terminationMsg !== null) {
778
+ out(` TERMINATED — ${terminationMsg} — the Hansard is sealed`);
779
+ }
780
+ reportCommit(rec);
781
+ return outcome.carried ? EXIT.OK : EXIT.REFUSED;
782
+ }
783
+
784
+ if (verb === 'break') {
785
+ if (values.actor === undefined || values.decide === undefined) {
786
+ err('division break: --actor and --decide (carry|reject) are required'); return EXIT.USAGE;
787
+ }
788
+ const decision = values.decide.toLowerCase();
789
+ if (decision !== 'carry' && decision !== 'reject') {
790
+ err('division break: --decide must be carry or reject'); return EXIT.USAGE;
791
+ }
792
+ const result = breakDeadlock(values.motion, decision, nowStamp(), values.actor, state, hansard,
793
+ charter.session.quorum, charter.mechanics.resolution);
794
+ await writeHansard(dir, result.hansard);
795
+ await writeState(dir, result.state);
796
+ await logAct(dir, values.actor, 'AUTHORITY' as never, `DEADLOCK_BROKEN ${values.motion} ${decision}`);
797
+ const rec = await commitAct(dir, `DEADLOCK_BROKEN — ${values.motion} ${decision}`);
798
+ out(`${asTerm(protocol, 'MOTION')} ${result.outcome.carried ? 'CARRIED' : 'NOT CARRIED'} — AUTHORITY broke the deadlock`);
799
+ out(` casting vote ${decision === 'carry' ? 'AYE' : 'NO'} — ${result.outcome.reason}`);
800
+ out(' the sitting resumes');
801
+ reportCommit(rec);
802
+ return result.outcome.carried ? EXIT.OK : EXIT.REFUSED;
803
+ }
804
+
805
+ err(`division: unknown verb "${verb ?? ''}" — expected call | vote | tally | break`);
806
+ return EXIT.USAGE;
807
+ } catch (error) {
808
+ err(`division refused: ${error instanceof Error ? error.message : String(error)}`);
809
+ return EXIT.REFUSED;
810
+ }
811
+ };
812
+
813
+ /** `politik assent` — enact a carried Motion. */
814
+ const cmdAssent = async (argv: readonly string[]): Promise<number> => {
815
+ const { values } = parseArgs({
816
+ args: [...argv],
817
+ options: {
818
+ dir: { type: 'string' }, motion: { type: 'string' },
819
+ actor: { type: 'string' }, role: { type: 'string' },
820
+ ...PROVIDER_OPTS,
821
+ },
822
+ });
823
+
824
+ const dir = values.dir ?? '.';
825
+ const { state, hansard, charter } = await loadSession(dir);
826
+ if (state === null || charter === null) { err(`assent: ${dir} is not a session repo`); return EXIT.USAGE; }
827
+ if (values.motion === undefined || values.actor === undefined) {
828
+ err('assent: --motion and --actor are required'); return EXIT.USAGE;
829
+ }
830
+
831
+ try {
832
+ const outcome = tallyDivision(hansard, values.motion, charter.session.quorum);
833
+ const result = grantAssent({
834
+ motion: values.motion, at: nowStamp(), actor: values.actor,
835
+ role: (values.role ?? 'AUTHORITY') as never,
836
+ assent_role: charter.session.assent, outcome, state,
837
+ veto_outstanding: vetoOutstanding(hansard, values.motion),
838
+ }, hansard);
839
+ await writeHansard(dir, result.hansard);
840
+ await writeState(dir, result.state);
841
+
842
+ // ADR-0004 defines ASSENT as merging the Motion. This is where the decision
843
+ // reaches the world; until it was wired, assent recorded a decision that
844
+ // changed nothing.
845
+ const { provider } = resolveProvider({ repo: values.repo, token: values.token });
846
+ const merged = await projectAssent(
847
+ provider, result.hansard, values.motion, charter.session.merge_strategy,
848
+ );
849
+ const projMsg = await applyProjection(dir, `ASSENT ${values.motion}`, merged, result.hansard);
850
+
851
+ await logAct(dir, values.actor ?? 'RECORD', (values.role ?? 'AUTHORITY') as never, `ASSENT ${values.motion}`);
852
+ const rec = await commitAct(dir, `ASSENT_GRANTED — ${values.motion} enacted`);
853
+ out(`${asTerm(await sessionProtocol(charter.protocol), 'ASSENT')} granted — ${values.motion} is enacted`);
854
+ out(projMsg);
855
+ reportCommit(rec);
856
+ return EXIT.OK;
857
+ } catch (error) {
858
+ err(`assent refused: ${error instanceof Error ? error.message : String(error)}`);
859
+ return EXIT.REFUSED;
860
+ }
861
+ };
862
+
863
+
864
+ /** `politik crisis file|check|review`. */
865
+ const cmdCrisis = async (argv: readonly string[]): Promise<number> => {
866
+ const [verb, ...rest] = argv;
867
+ const { values } = parseArgs({
868
+ args: rest,
869
+ options: {
870
+ dir: { type: 'string' }, actor: { type: 'string' }, role: { type: 'string' },
871
+ against: { type: 'string' }, grounds: { type: 'string' },
872
+ reviewer: { type: 'string' }, accused: { type: 'string' },
873
+ ruling: { type: 'string' }, reasons: { type: 'string' },
874
+ },
875
+ });
876
+
877
+ const dir = values.dir ?? '.';
878
+ const { state, hansard, charter } = await loadSession(dir);
879
+ if (state === null || charter === null) {
880
+ err(`crisis: ${dir} is not a session repo`);
881
+ return EXIT.USAGE;
882
+ }
883
+
884
+ const operators = charter.constituencies
885
+ .filter((c) => c.role === 'OPERATOR')
886
+ .reduce((n, c) => n + c.slots, 0);
887
+
888
+ try {
889
+ if (verb === 'file') {
890
+ if (values.actor === undefined || values.against === undefined || values.grounds === undefined) {
891
+ err('crisis file: --actor, --against and --grounds are required');
892
+ return EXIT.USAGE;
893
+ }
894
+ if (badRole(values.role)) { err(`crisis file: "${values.role}" is not a CANON role`); return EXIT.USAGE; }
895
+ const result = fileCrisis({
896
+ at: nowStamp(), actor: values.actor, role: (values.role ?? 'OPERATOR') as never,
897
+ grounds: values.grounds, against: values.against, state,
898
+ witness: charter.governance.witness_council.enabled
899
+ ? { ...charter.governance.witness_council, can_file: 'CONSTITUTIONAL_CRISIS' as const }
900
+ : null,
901
+ }, hansard);
902
+ await writeHansard(dir, result.hansard);
903
+ await logAct(dir, values.actor ?? 'RECORD', (values.role ?? 'OPERATOR') as never, `CRISIS_FILED against ${values.against}`);
904
+ const rec = await commitAct(dir, `CONSTITUTIONAL_CRISIS_FILED — ${values.actor}`);
905
+ out(`CRISIS FILED by ${values.actor} against ${values.against}`);
906
+ reportCommit(rec);
907
+
908
+ // The Charter's own declaration, not a hardcoded default. Until these
909
+ // were parsed, a Speaker could declare a Witness Council and get nothing.
910
+ const check = checkCapture(
911
+ result.hansard,
912
+ operators,
913
+ charter.governance.witness_council.enabled
914
+ ? { ...charter.governance.witness_council, can_file: 'CONSTITUTIONAL_CRISIS' as const }
915
+ : null,
916
+ { ...charter.governance.consensus_suspension, resume_requires: 'external_review' as const },
917
+ );
918
+ if (check.triggered) {
919
+ const suspended = suspendForCrisis(check, nowStamp(), state, result.hansard);
920
+ await writeHansard(dir, suspended.hansard);
921
+ await writeState(dir, suspended.state);
922
+ const sealed = await commitAct(dir, 'CONSTITUTIONAL_CRISIS — session suspended');
923
+ out(` ${check.reason}`);
924
+ out('');
925
+ out(' CONSTITUTIONAL CRISIS — the session is SUSPENDED');
926
+ out(' Resumption requires review by a human outside this session.');
927
+ reportCommit(sealed);
928
+ } else {
929
+ out(` ${check.reason}`);
930
+ }
931
+ return EXIT.OK;
932
+ }
933
+
934
+ if (verb === 'check') {
935
+ const check = checkCapture(
936
+ hansard,
937
+ operators,
938
+ charter.governance.witness_council.enabled
939
+ ? { ...charter.governance.witness_council, can_file: 'CONSTITUTIONAL_CRISIS' as const }
940
+ : null,
941
+ { ...charter.governance.consensus_suspension, resume_requires: 'external_review' as const },
942
+ );
943
+ out(check.triggered ? 'CAPTURE DECLARED' : 'no capture declared');
944
+ out(` filings ${check.filed} of ${check.operators} OPERATOR actors`);
945
+ out(` threshold ${check.required}`);
946
+ out(` ${check.reason}`);
947
+ return check.triggered ? EXIT.REFUSED : EXIT.OK;
948
+ }
949
+
950
+ if (verb === 'review') {
951
+ if (values.reviewer === undefined || values.accused === undefined || values.reasons === undefined) {
952
+ err('crisis review: --reviewer, --accused and --reasons are required');
953
+ return EXIT.USAGE;
954
+ }
955
+ const result = externalReview({
956
+ at: nowStamp(), reviewer: values.reviewer, accused: values.accused,
957
+ ruling: ((values.ruling ?? 'UPHELD').toUpperCase()) as CrisisRuling,
958
+ reasons: values.reasons, state,
959
+ }, hansard);
960
+ await writeHansard(dir, result.hansard);
961
+ await writeState(dir, result.state);
962
+ await logAct(dir, values.reviewer ?? 'RECORD', 'OBSERVER' as never, `CRISIS_RULING ${values.ruling?.toUpperCase() ?? 'UPHELD'}`);
963
+ const rec = await commitAct(dir, `CONSTITUTIONAL_CRISIS_RULING — ${values.ruling?.toUpperCase() ?? 'UPHELD'}`);
964
+ out(`EXTERNAL RULING — ${values.ruling?.toUpperCase() ?? 'UPHELD'}`);
965
+ out(` session is now ${result.state.state}`);
966
+ reportCommit(rec);
967
+ return EXIT.OK;
968
+ }
969
+
970
+ err(`crisis: unknown verb "${verb ?? ''}" — expected file | check | review`);
971
+ return EXIT.USAGE;
972
+ } catch (error) {
973
+ err(`crisis refused: ${error instanceof Error ? error.message : String(error)}`);
974
+ return EXIT.REFUSED;
975
+ }
976
+ };
977
+
978
+
979
+
980
+
981
+ /** `politik heartbeat` — is the proceeding still beating? */
982
+ const cmdHeartbeat = async (argv: readonly string[]): Promise<number> => {
983
+ const { values } = parseArgs({
984
+ args: [...argv],
985
+ options: { dir: { type: 'string' }, suspend: { type: 'boolean' } },
986
+ });
987
+ const dir = values.dir ?? '.';
988
+ const { state, hansard, charter } = await loadSession(dir);
989
+ if (state === null || charter === null) { err(`heartbeat: ${dir} is not a session repo`); return EXIT.USAGE; }
990
+
991
+ const check = checkHeartbeat(hansard, charter.session.heartbeat_timeout_hours, nowStamp());
992
+ out(check.stale ? 'STALE' : 'beating');
993
+ out(` last beat ${check.last_beat ?? 'none'}`);
994
+ out(` ${check.reason}`);
995
+
996
+ if (check.stale && values.suspend === true) {
997
+ try {
998
+ const result = markStale(check, nowStamp(), state, hansard);
999
+ await writeHansard(dir, result.hansard);
1000
+ await writeState(dir, result.state);
1001
+ const rec = await commitAct(dir, 'SESSION_STALE — heartbeat window elapsed');
1002
+ out(` session marked STALE — resumable, nothing lost (stale_action: ${charter.session.stale_action})`);
1003
+ reportCommit(rec);
1004
+ } catch (error) {
1005
+ err(`heartbeat: ${error instanceof Error ? error.message : String(error)}`);
1006
+ return EXIT.REFUSED;
1007
+ }
1008
+ }
1009
+ return check.stale ? EXIT.REFUSED : EXIT.OK;
1010
+ };
1011
+
1012
+ const list = (v: string | undefined): string[] =>
1013
+ (v ?? '').split(',').map((s) => s.trim()).filter((s) => s.length > 0);
1014
+
1015
+ /** `politik snapshot` — checkpoint the proceeding. */
1016
+ const cmdSnapshot = async (argv: readonly string[]): Promise<number> => {
1017
+ const { values } = parseArgs({
1018
+ args: [...argv],
1019
+ options: {
1020
+ dir: { type: 'string' }, completed: { type: 'string' },
1021
+ 'in-flight': { type: 'string' }, pending: { type: 'string' },
1022
+ blocked: { type: 'string' },
1023
+ },
1024
+ });
1025
+ const dir = values.dir ?? '.';
1026
+ const { state, hansard, charter } = await loadSession(dir);
1027
+ if (state === null || charter === null) { err(`snapshot: ${dir} is not a session repo`); return EXIT.USAGE; }
1028
+ // A checkpoint records live business (completed/in-flight/pending) so a STALE
1029
+ // sitting can resume from it — meaningless on a sealed or dead session, and
1030
+ // appending to a Hansard prorogation sealed would break the seal.
1031
+ if (state.state === 'PROROGUED' || state.state === 'INVALID') {
1032
+ err(`snapshot refused: the session is ${state.state} — its Hansard is sealed`);
1033
+ return EXIT.REFUSED;
1034
+ }
1035
+
1036
+ const ledgerDoc = (await readIfPresent(join(dir, charter.ledger.path))) ?? '';
1037
+ const spent = totals(ledgerDoc);
1038
+
1039
+ const result = snapshot({
1040
+ completed: list(values.completed),
1041
+ in_flight: list(values['in-flight']),
1042
+ pending: list(values.pending),
1043
+ blocked: list(values.blocked),
1044
+ cost_usd: spent.cost_usd,
1045
+ max_cost_usd: charter.session.endurance.max_cost_usd,
1046
+ motions: spent.rows,
1047
+ max_motions: charter.session.endurance.max_motions,
1048
+ }, nowStamp(), state, hansard);
1049
+
1050
+ await writeHansard(dir, result.hansard);
1051
+ const rec = await commitAct(dir, 'STATE_SNAPSHOT');
1052
+ out('STATE_SNAPSHOT committed');
1053
+ out(` spent $${spent.cost_usd.toFixed(4)} over ${spent.rows} act(s)`);
1054
+ reportCommit(rec);
1055
+ return EXIT.OK;
1056
+ };
1057
+
1058
+ /** `politik resume` — bring a STALE proceeding back. */
1059
+ const cmdResume = async (argv: readonly string[]): Promise<number> => {
1060
+ const { values } = parseArgs({
1061
+ args: [...argv],
1062
+ options: { dir: { type: 'string' }, actor: { type: 'string' } },
1063
+ });
1064
+ const dir = values.dir ?? '.';
1065
+ if (values.actor === undefined) { err('resume: --actor is required'); return EXIT.USAGE; }
1066
+
1067
+ const { state, hansard } = await loadSession(dir);
1068
+ if (state === null) { err(`resume: ${dir} is not a session repo`); return EXIT.USAGE; }
1069
+
1070
+ try {
1071
+ const result = resume(nowStamp(), values.actor, state, hansard);
1072
+ await writeHansard(dir, result.hansard);
1073
+ await writeState(dir, result.state);
1074
+ const rec = await commitAct(dir, 'SESSION_RESUMED');
1075
+ out('RESUMED — the sitting continues');
1076
+ const snap = lastSnapshot(result.hansard);
1077
+ out(snap === null ? ' no snapshot; agents resume from the Hansard' : ' agents resume from the last STATE_SNAPSHOT');
1078
+ reportCommit(rec);
1079
+ return EXIT.OK;
1080
+ } catch (error) {
1081
+ err(`resume refused: ${error instanceof Error ? error.message : String(error)}`);
1082
+ return EXIT.REFUSED;
1083
+ }
1084
+ };
1085
+
1086
+ /** `politik actor <verb>` — the actor lifecycle verbs. */
1087
+ const cmdActor = async (argv: readonly string[]): Promise<number> => {
1088
+ const [verb, ...rest] = argv;
1089
+ const { values } = parseArgs({
1090
+ args: rest,
1091
+ options: {
1092
+ dir: { type: 'string' }, actor: { type: 'string' }, role: { type: 'string' },
1093
+ subject: { type: 'string' }, seat: { type: 'string' }, to: { type: 'string' },
1094
+ reason: { type: 'string' }, type: { type: 'string' }, motion: { type: 'string' },
1095
+ child: { type: 'string' }, mandate: { type: 'string' },
1096
+ grounds: { type: 'string' }, ruling: { type: 'string' },
1097
+ },
1098
+ });
1099
+
1100
+ const dir = values.dir ?? '.';
1101
+ const { state, hansard, charter } = await loadSession(dir);
1102
+ if (state === null || charter === null) {
1103
+ err(`actor: ${dir} is not a session repo`);
1104
+ return EXIT.USAGE;
1105
+ }
1106
+
1107
+ if (verb === 'list') {
1108
+ const protocol = await sessionProtocol(charter.protocol);
1109
+ const held = seats(hansard);
1110
+ if (held.length === 0) out('no actors seated');
1111
+ for (const seat of held) out(` ${asRoleTerm(protocol, seat.role).padEnd(16)} ${seat.actor}`);
1112
+ return EXIT.OK;
1113
+ }
1114
+
1115
+ const by = {
1116
+ at: nowStamp(),
1117
+ actor: values.actor ?? '',
1118
+ role: (values.role ?? 'AUTHORITY') as never,
1119
+ state,
1120
+ };
1121
+ if (by.actor === '') { err('actor: --actor is required'); return EXIT.USAGE; }
1122
+ const protocol = await sessionProtocol(charter.protocol);
1123
+
1124
+ try {
1125
+ // Disputed exit files and rulings change the session's state (suspend, then
1126
+ // resume), unlike the seat verbs below which only touch the record — so they
1127
+ // write STATE.json and return here rather than falling through the shared tail.
1128
+ if (verb === 'dispute') {
1129
+ if (values.grounds === undefined) { err('actor dispute: --grounds is required'); return EXIT.USAGE; }
1130
+ const disputed = disputeExit(nowStamp(), by.actor, values.grounds, state, hansard);
1131
+ await writeHansard(dir, disputed.hansard);
1132
+ await writeState(dir, disputed.state);
1133
+ await logAct(dir, by.actor, by.role, `EXIT_DISPUTED ${by.actor}`);
1134
+ const rec = await commitAct(dir, `EXIT_DISPUTED — ${by.actor}`);
1135
+ out(`EXIT DISPUTED by ${by.actor}`);
1136
+ out(' the sitting is SUSPENDED pending a Speaker ruling:');
1137
+ out(` politik actor reinstate --subject ${by.actor} --actor <speaker> --ruling UPHELD|REVERSED`);
1138
+ reportCommit(rec);
1139
+ return EXIT.OK;
1140
+ }
1141
+
1142
+ if (verb === 'reinstate') {
1143
+ if (values.subject === undefined || values.ruling === undefined) {
1144
+ err('actor reinstate: --subject and --ruling (UPHELD|REVERSED) are required'); return EXIT.USAGE;
1145
+ }
1146
+ const ruling = values.ruling.toUpperCase();
1147
+ if (ruling !== 'UPHELD' && ruling !== 'REVERSED') {
1148
+ err('actor reinstate: --ruling must be UPHELD or REVERSED'); return EXIT.USAGE;
1149
+ }
1150
+ const resolved = resolveDispute(nowStamp(), by.actor, ruling, values.subject, state, hansard);
1151
+ await writeHansard(dir, resolved.hansard);
1152
+ await writeState(dir, resolved.state);
1153
+ await logAct(dir, by.actor, by.role, `EXIT_RULING ${ruling} ${values.subject}`);
1154
+ const rec = await commitAct(dir, `EXIT_RULING — ${ruling} on ${values.subject}`);
1155
+ out(`DISPUTED EXIT ${ruling} — ${resolved.reinstated ? `${values.subject} reinstated` : 'the removal stands'}`);
1156
+ out(' the sitting resumes');
1157
+ reportCommit(rec);
1158
+ return EXIT.OK;
1159
+ }
1160
+
1161
+ let result: { hansard: string } | null = null;
1162
+ let message = '';
1163
+
1164
+ if (verb === 'hire') {
1165
+ if (values.subject === undefined || values.seat === undefined) {
1166
+ err('actor hire: --subject and --seat are required'); return EXIT.USAGE;
1167
+ }
1168
+ result = hire({ ...by, subject: values.subject, seat: values.seat as never, reason: values.reason ?? 'seated' }, hansard);
1169
+ message = `HIRED ${values.subject} as ${asRoleTerm(protocol, values.seat)}`;
1170
+ } else if (verb === 'promote' || verb === 'demote') {
1171
+ if (values.subject === undefined || values.to === undefined) {
1172
+ err(`actor ${verb}: --subject and --to are required`); return EXIT.USAGE;
1173
+ }
1174
+ const move = verb === 'promote' ? promote : demote;
1175
+ result = move({ ...by, subject: values.subject, to: values.to as never, reason: values.reason ?? '' }, hansard);
1176
+ message = `${verb.toUpperCase()}D ${values.subject} to ${asRoleTerm(protocol, values.to)}`;
1177
+ } else if (verb === 'exit') {
1178
+ if (values.subject === undefined || values.type === undefined) {
1179
+ err('actor exit: --subject and --type are required'); return EXIT.USAGE;
1180
+ }
1181
+ result = exitActor({
1182
+ ...by, subject: values.subject, exit_type: values.type as ExitType,
1183
+ reason: values.reason ?? '',
1184
+ }, hansard);
1185
+ message = `EXITED ${values.subject} — ${values.type}`;
1186
+ } else if (verb === 'veto') {
1187
+ if (values.motion === undefined) { err('actor veto: --motion is required'); return EXIT.USAGE; }
1188
+ result = veto({
1189
+ ...by, motion: values.motion, reason: values.reason ?? '',
1190
+ domain_veto: charter.domain_veto,
1191
+ }, hansard);
1192
+ message = `VETO EXERCISED against ${values.motion}`;
1193
+ } else if (verb === 'spawn') {
1194
+ if (values.child === undefined) { err('actor spawn: --child is required'); return EXIT.USAGE; }
1195
+ result = spawnChild({ ...by, child: values.child, mandate: values.mandate ?? '' }, hansard);
1196
+ message = `REFERRED to committee ${values.child}`;
1197
+ } else {
1198
+ err(`actor: unknown verb "${verb ?? ''}" — expected hire | promote | demote | exit | veto | spawn | dispute | reinstate | list`);
1199
+ return EXIT.USAGE;
1200
+ }
1201
+
1202
+ await writeHansard(dir, result.hansard);
1203
+ await logAct(dir, by.actor, by.role as never, message);
1204
+ const rec = await commitAct(dir, `${message} — by ${by.actor}`);
1205
+ out(message);
1206
+ reportCommit(rec);
1207
+ return EXIT.OK;
1208
+ } catch (error) {
1209
+ err(`actor refused: ${error instanceof Error ? error.message : String(error)}`);
1210
+ return EXIT.REFUSED;
1211
+ }
1212
+ };
1213
+
1214
+ /** `politik escalate` — raise a Point of Order. */
1215
+ const cmdEscalate = async (argv: readonly string[]): Promise<number> => {
1216
+ const { values } = parseArgs({
1217
+ args: [...argv],
1218
+ options: {
1219
+ dir: { type: 'string' }, actor: { type: 'string' }, role: { type: 'string' },
1220
+ title: { type: 'string' }, body: { type: 'string' }, seq: { type: 'string' },
1221
+ ...PROVIDER_OPTS,
1222
+ },
1223
+ });
1224
+
1225
+ const dir = values.dir ?? '.';
1226
+ const { state, charter } = await loadSession(dir);
1227
+ if (state === null) { err(`escalate: ${dir} is not a session repo`); return EXIT.USAGE; }
1228
+ if (values.actor === undefined || values.title === undefined || values.body === undefined) {
1229
+ err('escalate: --actor, --title and --body are required');
1230
+ return EXIT.USAGE;
1231
+ }
1232
+ if (badRole(values.role)) { err(`escalate: "${values.role}" is not a CANON role`); return EXIT.USAGE; }
1233
+ // A protocol that declares no escalation refuses a Point of Order outright
1234
+ // (ADR-0006) — there is no mechanism to resolve one.
1235
+ if (charter?.session.escalation === 'disabled') {
1236
+ err('escalate refused: this protocol declares no escalation — a Point of Order cannot be raised');
1237
+ return EXIT.REFUSED;
1238
+ }
1239
+ // A Point of Order suspends a live sitting; refuse from any other state so a
1240
+ // sealed (PROROGUED) session is never reopened and a pending ruling is never
1241
+ // clobbered. Mirrors division/assent.
1242
+ if (state.state !== 'CONVENED') {
1243
+ err(`escalate refused: cannot raise a Point of Order while the session is ${state.state}`);
1244
+ return EXIT.REFUSED;
1245
+ }
1246
+
1247
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
1248
+ const filed = fileEscalation({
1249
+ sequence: values.seq === undefined ? 1 : Number(values.seq),
1250
+ at: nowStamp(),
1251
+ actor: values.actor,
1252
+ role: (values.role ?? 'OPERATOR') as never,
1253
+ title: values.title,
1254
+ body: values.body,
1255
+ state,
1256
+ // The escalation-disabled case already returned above, so it cannot be
1257
+ // disabled here; fileEscalation's own guard covers non-CLI callers.
1258
+ }, hansard);
1259
+
1260
+ await writeFiles(dir, filed.files);
1261
+ await writeHansard(dir, filed.hansard);
1262
+ await writeState(dir, filed.state);
1263
+
1264
+ const { provider } = resolveProvider({ repo: values.repo, token: values.token });
1265
+ const opened = await projectEscalation(
1266
+ provider, `POINT OF ORDER — ${values.title}`, filed.notification,
1267
+ );
1268
+ const projMsg = await applyProjection(dir, `ESCALATION ${values.title}`, opened, filed.hansard);
1269
+
1270
+ await logAct(dir, values.actor ?? 'RECORD', (values.role ?? 'OPERATOR') as never, `POINT_OF_ORDER ${values.title}`);
1271
+ // The Hansard cites the escalation file by path as the record; commit it, or
1272
+ // the substance of the Point of Order lives only in an untracked file.
1273
+ const rec = await commitAct(dir, `POINT_OF_ORDER — ${values.actor}: ${values.title}`, [filed.escalation_path]);
1274
+ out(`${asTerm(await sessionProtocol(charter?.protocol ?? 'parliamentary'), 'ESCALATION')} raised`);
1275
+ out(` escalation ${filed.escalation_path}`);
1276
+ out(` ruling due ${filed.ruling_path}`);
1277
+ out(' session is SUSPENDED pending a Speaker ruling');
1278
+ out(projMsg);
1279
+ reportCommit(rec);
1280
+
1281
+ // The notification body is built here; delivery is the provider's job.
1282
+ out('');
1283
+ out(' --- Speaker notification ---');
1284
+ for (const line of filed.notification.split('\n')) out(` ${line}`);
1285
+ return EXIT.OK;
1286
+ };
1287
+
1288
+ /** `politik rule` — the Speaker rules, and the sitting resumes. */
1289
+ const cmdRule = async (argv: readonly string[]): Promise<number> => {
1290
+ const { values } = parseArgs({
1291
+ args: [...argv],
1292
+ options: {
1293
+ dir: { type: 'string' }, seq: { type: 'string' }, actor: { type: 'string' },
1294
+ role: { type: 'string' }, outcome: { type: 'string' }, body: { type: 'string' },
1295
+ },
1296
+ });
1297
+
1298
+ const dir = values.dir ?? '.';
1299
+ const { state } = await loadSession(dir);
1300
+ if (state === null) { err(`rule: ${dir} is not a session repo`); return EXIT.USAGE; }
1301
+ if (values.actor === undefined || values.body === undefined) {
1302
+ err('rule: --actor and --body are required');
1303
+ return EXIT.USAGE;
1304
+ }
1305
+ if (badRole(values.role)) { err(`rule: "${values.role}" is not a CANON role`); return EXIT.USAGE; }
1306
+
1307
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
1308
+
1309
+ try {
1310
+ const ruling = commitRuling({
1311
+ sequence: values.seq === undefined ? 1 : Number(values.seq),
1312
+ at: nowStamp(),
1313
+ actor: values.actor,
1314
+ role: (values.role ?? 'AUTHORITY') as never,
1315
+ outcome: ((values.outcome ?? 'UPHELD').toUpperCase()) as RulingOutcome,
1316
+ body: values.body,
1317
+ escalation_path: state.suspension?.escalation_ref ?? 'escalations/',
1318
+ state,
1319
+ }, hansard);
1320
+
1321
+ await writeFiles(dir, ruling.files);
1322
+ await writeHansard(dir, ruling.hansard);
1323
+ await writeState(dir, ruling.state);
1324
+
1325
+ await logAct(dir, values.actor ?? 'RECORD', (values.role ?? 'AUTHORITY') as never,
1326
+ `RULING ${(values.outcome ?? 'UPHELD').toUpperCase()}`);
1327
+ // The Hansard cites the ruling file by path; commit it so the ruling's
1328
+ // reasoning is in the immutable record, not just an untracked file.
1329
+ const rec = await commitAct(dir, `RULING — ${(values.outcome ?? 'UPHELD').toUpperCase()}`, [ruling.ruling_path]);
1330
+ out(`RULING COMMITTED — ${(values.outcome ?? 'UPHELD').toUpperCase()}`);
1331
+ out(` ${ruling.ruling_path}`);
1332
+ out(` session is ${ruling.state.state} — the sitting resumes`);
1333
+ reportCommit(rec);
1334
+ return EXIT.OK;
1335
+ } catch (error) {
1336
+ err(`ruling refused: ${error instanceof Error ? error.message : String(error)}`);
1337
+ return EXIT.REFUSED;
1338
+ }
1339
+ };
1340
+
1341
+
1342
+
1343
+ /**
1344
+ * `politik conflict` — routine, not a governance event.
1345
+ *
1346
+ * Nothing here suspends the session or reaches for AUTHORITY: a merge conflict
1347
+ * is ordinary concurrent work, and treating it as a fault would train actors to
1348
+ * escalate things two Ministers can settle themselves.
1349
+ */
1350
+ const cmdConflict = async (argv: readonly string[]): Promise<number> => {
1351
+ const [verb, ...rest] = argv;
1352
+ const { values } = parseArgs({
1353
+ args: rest,
1354
+ options: {
1355
+ dir: { type: 'string' }, motions: { type: 'string' }, actor: { type: 'string' },
1356
+ role: { type: 'string' }, resolution: { type: 'string' }, verbs: { type: 'string' },
1357
+ },
1358
+ });
1359
+
1360
+ const dir = values.dir ?? '.';
1361
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
1362
+
1363
+ if (verb === 'check') {
1364
+ // Motions are files under motions/; a conflict is an overlap in what the
1365
+ // Motions themselves touch, read from the record.
1366
+ const conflicts = detectRecordConflicts(hansard);
1367
+
1368
+ if (conflicts.length === 0) {
1369
+ out('no conflicts');
1370
+ } else {
1371
+ // Accumulate every conflict entry into one document before writing — a
1372
+ // per-iteration `appendEntry(hansard, …)` against the original would keep
1373
+ // only the last conflict on the record.
1374
+ let doc = hansard;
1375
+ for (const c of conflicts) doc = appendEntry(doc, conflictEntry(c, nowStamp(), 'RECORD', 'OPERATOR'));
1376
+ await writeHansard(dir, doc);
1377
+ const rec = await commitAct(dir, `CONFLICT — ${conflicts.length} detected`);
1378
+ for (const c of conflicts) {
1379
+ out(`CONFLICT ${c.motions.join(' <-> ')}`);
1380
+ out(` files ${c.files.join(', ')}`);
1381
+ }
1382
+ reportCommit(rec);
1383
+ }
1384
+
1385
+ const open = openConflicts(hansard);
1386
+ if (open.length > 0) out(` ${open.length} unresolved`);
1387
+ // A conflict is not a failure, so this never exits non-zero.
1388
+ return EXIT.OK;
1389
+ }
1390
+
1391
+ if (verb === 'resolve') {
1392
+ if (values.motions === undefined || values.actor === undefined || values.resolution === undefined) {
1393
+ err('conflict resolve: --motions, --actor and --resolution are required');
1394
+ return EXIT.USAGE;
1395
+ }
1396
+ try {
1397
+ const result = resolveConflict({
1398
+ at: nowStamp(),
1399
+ actor: values.actor,
1400
+ role: (values.role ?? 'OPERATOR') as never,
1401
+ verbs: (values.verbs ?? 'READ,WRITE').split(',').map((v) => v.trim()) as never,
1402
+ motions: values.motions.split(',').map((m) => m.trim()).filter((m) => m.length > 0),
1403
+ resolution: values.resolution,
1404
+ }, hansard);
1405
+
1406
+ await writeHansard(dir, result.hansard);
1407
+ const rec = await commitAct(dir, `CONFLICT_RESOLVED — ${values.motions}`);
1408
+ out(`CONFLICT RESOLVED — ${values.motions}`);
1409
+ out(' no Speaker intervention required');
1410
+ reportCommit(rec);
1411
+ return EXIT.OK;
1412
+ } catch (error) {
1413
+ err(`conflict refused: ${error instanceof Error ? error.message : String(error)}`);
1414
+ return EXIT.REFUSED;
1415
+ }
1416
+ }
1417
+
1418
+ err(`conflict: unknown verb "${verb ?? ''}" — expected check | resolve`);
1419
+ return EXIT.USAGE;
1420
+ };
1421
+
1422
+ /**
1423
+ * `politik broadcast` — put business on the bus.
1424
+ *
1425
+ * The chamber transport carries the ephemeral nudge; the Hansard remains the
1426
+ * record. A broadcast nobody hears loses nothing, because a peer that hears
1427
+ * nothing falls back to reading the repo.
1428
+ */
1429
+ const cmdBroadcast = async (argv: readonly string[]): Promise<number> => {
1430
+ const { values } = parseArgs({
1431
+ args: [...argv],
1432
+ options: {
1433
+ dir: { type: 'string' }, target: { type: 'string' },
1434
+ slots: { type: 'string' }, task: { type: 'string' },
1435
+ },
1436
+ });
1437
+
1438
+ const dir = values.dir ?? '.';
1439
+ const { state, charter } = await loadSession(dir);
1440
+ if (state === null || charter === null) {
1441
+ err(`broadcast: ${dir} is not a session repo`);
1442
+ return EXIT.USAGE;
1443
+ }
1444
+ if (values.task === undefined) {
1445
+ err('broadcast: --task is required');
1446
+ return EXIT.USAGE;
1447
+ }
1448
+ // Opening the floor dispatches work to agents; only a live sitting may do so.
1449
+ // A sealed or suspended session must not be sending out fresh business.
1450
+ if (state.state !== 'CONVENED') {
1451
+ err(`broadcast refused: cannot open the floor while the session is ${state.state}`);
1452
+ return EXIT.REFUSED;
1453
+ }
1454
+
1455
+ if (badRole(values.target)) { err(`broadcast: "${values.target}" is not a CANON role`); return EXIT.USAGE; }
1456
+ const target = values.target ?? 'OPERATOR';
1457
+ const declared = charter.constituencies
1458
+ .filter((c) => c.role === target)
1459
+ .reduce((n, c) => n + c.slots, 0);
1460
+ const slots = values.slots === undefined ? declared : Number(values.slots);
1461
+
1462
+ if (!Number.isInteger(slots) || slots < 0) {
1463
+ err('broadcast: --slots must be a non-negative integer');
1464
+ return EXIT.USAGE;
1465
+ }
1466
+ if (declared === 0) {
1467
+ err(`broadcast: the Charter seats no ${target} constituency`);
1468
+ return EXIT.REFUSED;
1469
+ }
1470
+
1471
+ const source = [
1472
+ `# [${state.session_guid}]`,
1473
+ `## target-actor: ${target}`,
1474
+ `## slots-remaining: ${slots}`,
1475
+ `## protocol: ${charter.protocol}`,
1476
+ '## prompt: |',
1477
+ ...values.task.split('\n').map((l) => ` ${l}`),
1478
+ '',
1479
+ ].join('\n');
1480
+
1481
+ const parsed = parseEnvelope(source);
1482
+ if (!parsed.ok) {
1483
+ err(`broadcast: ${parsed.issues.map((i) => i.message).join('; ')}`);
1484
+ return EXIT.REFUSED;
1485
+ }
1486
+
1487
+ const bus = new GitTransport({ dir });
1488
+ const result = await bus.publish(parsed.envelope);
1489
+ out('BROADCAST PUBLISHED');
1490
+ out(` target ${target}, ${slots} slot(s)`);
1491
+ out(` ${result.ref}`);
1492
+ return EXIT.OK;
1493
+ };
1494
+
1495
+ /**
1496
+ * `politik motion link` — bind a Motion to its platform object.
1497
+ *
1498
+ * Without a link, Assent has no pull request to merge and degrades to a
1499
+ * local-only record. Kept explicit rather than inferred: guessing which PR a
1500
+ * Motion means would risk merging the wrong branch on the strength of a
1501
+ * filename match.
1502
+ */
1503
+ const cmdMotion = async (argv: readonly string[]): Promise<number> => {
1504
+ const [verb, ...rest] = argv;
1505
+ if (verb !== 'link') {
1506
+ err(`motion: unknown verb "${verb ?? ''}" — expected link`);
1507
+ return EXIT.USAGE;
1508
+ }
1509
+
1510
+ const { values } = parseArgs({
1511
+ args: rest,
1512
+ options: {
1513
+ dir: { type: 'string' }, motion: { type: 'string' },
1514
+ pr: { type: 'string' }, url: { type: 'string' },
1515
+ },
1516
+ });
1517
+
1518
+ const dir = values.dir ?? '.';
1519
+ if (values.motion === undefined || values.pr === undefined) {
1520
+ err('motion link: --motion and --pr are required');
1521
+ return EXIT.USAGE;
1522
+ }
1523
+ const pr = Number.parseInt(values.pr.replace(/^#/, ''), 10);
1524
+ if (!Number.isInteger(pr) || pr < 1) {
1525
+ err('motion link: --pr must be a positive integer');
1526
+ return EXIT.USAGE;
1527
+ }
1528
+
1529
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
1530
+ const updated = appendEntry(hansard, linkEntry(values.motion, pr, values.url ?? '', nowStamp()));
1531
+ await writeHansard(dir, updated);
1532
+ const rec = await commitAct(dir, `MOTION_PROJECTED — ${values.motion} -> #${pr}`);
1533
+ out(`LINKED ${values.motion} -> #${pr}`);
1534
+ reportCommit(rec);
1535
+ return EXIT.OK;
1536
+ };
1537
+
1538
+ /** `politik ledger` — total the cost record. */
1539
+ const cmdLedger = async (argv: readonly string[]): Promise<number> => {
1540
+ const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' } } });
1541
+ const dir = values.dir ?? '.';
1542
+ const { charter } = await loadSession(dir);
1543
+ const path = charter?.ledger.path ?? 'LEDGER.md';
1544
+ const document = await readIfPresent(join(dir, path));
1545
+ if (document === null) {
1546
+ err(`ledger: no ${path} in ${dir}`);
1547
+ return EXIT.USAGE;
1548
+ }
1549
+
1550
+ const t = totals(document);
1551
+ out(`rows ${t.rows}`);
1552
+ out(`elapsed ${(t.elapsed_ms / 1000).toFixed(1)}s`);
1553
+ out(`tokens ${t.tokens.toLocaleString('en-US')}`);
1554
+ out(`cost $${t.cost_usd.toFixed(6)}`);
1555
+ if (t.unmeasured > 0) {
1556
+ // Never fold unmeasured rows into the total — that would understate spend
1557
+ // while looking authoritative.
1558
+ out(`unmeasured ${t.unmeasured} row(s) — cost not reported by the agent`);
1559
+ }
1560
+
1561
+ const ceiling = checkCostCeiling(
1562
+ document,
1563
+ charter?.session.endurance.max_cost_usd ?? null,
1564
+ charter?.session.endurance.cost_warning_usd ?? null,
1565
+ );
1566
+ if (ceiling.warning) {
1567
+ out(`WARNING — $${ceiling.spent.toFixed(4)} spent, warning line $${(charter?.session.endurance.cost_warning_usd ?? 0).toFixed(2)}`);
1568
+ }
1569
+ if (ceiling.exceeded) {
1570
+ err('COST CEILING EXCEEDED — the session should suspend');
1571
+ return EXIT.REFUSED;
1572
+ }
1573
+ return EXIT.OK;
1574
+ };
1575
+
1576
+ /** Run one turn of a session. */
1577
+ const cmdRun = async (argv: readonly string[]): Promise<number> => {
1578
+ const { values } = parseArgs({
1579
+ args: [...argv],
1580
+ options: {
1581
+ dir: { type: 'string' },
1582
+ agent: { type: 'string' },
1583
+ actor: { type: 'string' },
1584
+ role: { type: 'string' },
1585
+ task: { type: 'string' },
1586
+ timeout: { type: 'string' },
1587
+ claim: { type: 'boolean' },
1588
+ },
1589
+ });
1590
+
1591
+ const dir = values.dir ?? '.';
1592
+ if (badRole(values.role)) { err(`run: "${values.role}" is not a CANON role`); return EXIT.USAGE; }
1593
+ const role = (values.role ?? 'OPERATOR') as never;
1594
+
1595
+ // Claim mode: take business off the bus rather than inventing it. This is the
1596
+ // path the Self-Organization Protocol describes — a peer acts because it
1597
+ // heard a broadcast it is eligible for, not because someone typed a task.
1598
+ let received: Envelope | undefined;
1599
+ if (values.claim === true) {
1600
+ const { state } = await loadSession(dir);
1601
+ if (state === null) { err(`run: ${dir} is not a session repo`); return EXIT.USAGE; }
1602
+
1603
+ const bus = new GitTransport({ dir });
1604
+ const waiting = await bus.poll(state.session_guid);
1605
+ received = waiting.find((e) => isEligible(e, role));
1606
+
1607
+ if (received === undefined) {
1608
+ out(waiting.length === 0
1609
+ ? 'no broadcasts on the bus'
1610
+ : `no broadcast this agent is eligible for (${waiting.length} waiting)`);
1611
+ return EXIT.OK;
1612
+ }
1613
+ out(`CLAIMED a broadcast — ${received.target_actor}, ${received.slots_remaining} slot(s)`);
1614
+ }
1615
+
1616
+ if (values.agent === undefined || values.actor === undefined) {
1617
+ err('run: --agent and --actor are required');
1618
+ return EXIT.USAGE;
1619
+ }
1620
+ if (received === undefined && values.task === undefined) {
1621
+ err('run: --task is required (or use --claim to take one off the bus)');
1622
+ return EXIT.USAGE;
1623
+ }
1624
+
1625
+ const outcome = await runTurn({
1626
+ dir,
1627
+ agent_id: values.agent,
1628
+ actor: values.actor,
1629
+ role,
1630
+ task: received?.prompt ?? values.task ?? '',
1631
+ ...(received === undefined ? {} : { envelope: received }),
1632
+ now: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
1633
+ timeout_ms: values.timeout === undefined ? undefined : Number(values.timeout),
1634
+ });
1635
+
1636
+ if (!outcome.ok) {
1637
+ err(`TURN REFUSED — ${outcome.reason}`);
1638
+ if (outcome.entry !== undefined) err('The failure is on the record.');
1639
+ return EXIT.REFUSED;
1640
+ }
1641
+
1642
+ const rec = await commitAct(
1643
+ dir,
1644
+ `${outcome.entry.type} — ${values.actor} (${values.role ?? 'OPERATOR'})`,
1645
+ );
1646
+ out('TURN COMPLETE');
1647
+ out(` agent ${outcome.result.agent}`);
1648
+ out(` elapsed ${outcome.result.elapsed_ms}ms`);
1649
+ out(` files ${outcome.files_touched.length > 0 ? outcome.files_touched.join(', ') : 'none'}`);
1650
+ out(' recorded in HANSARD.md');
1651
+ if (outcome.suspended === true) {
1652
+ out(' POINT OF ORDER — the agent escalated; the sitting is SUSPENDED pending a Speaker ruling');
1653
+ }
1654
+ reportCommit(rec);
1655
+ return EXIT.OK;
1656
+ };
1657
+
1658
+ /**
1659
+ * Render a CANON entry type in the protocol's vocabulary. The stored type stays
1660
+ * CANON (the engine parses it); this is only for the human-facing `hansard` view.
1661
+ * Unknown types humanise gracefully rather than showing a raw token.
1662
+ */
1663
+ const translateEntryType = (protocol: Protocol | null, type: string): string => {
1664
+ const t = (canon: string) => asTerm(protocol, canon);
1665
+ const map: Record<string, string> = {
1666
+ WRIT_DROP: 'Writ dropped',
1667
+ MOTION_TABLED: `${t('MOTION')} tabled`,
1668
+ MOTION_CARRIED: `${t('MOTION')} carried`,
1669
+ MOTION_REJECTED: `${t('MOTION')} rejected`,
1670
+ VOTE_CAST: `${t('VOTE')} cast`,
1671
+ DIVISION_CALLED: `${t('DIVISION')} called`,
1672
+ POINT_OF_ORDER: `${t('ESCALATION')} raised`,
1673
+ RULING: 'Ruling',
1674
+ ASSENT_GRANTED: `${t('ASSENT')} granted`,
1675
+ ACTOR_HIRED: 'Seated',
1676
+ ACTOR_EXITED: `${t('EXIT')}`,
1677
+ ACTOR_PROMOTED: `${t('PROMOTE')}`,
1678
+ ACTOR_DEMOTED: `${t('DEMOTE')}`,
1679
+ STATE_SNAPSHOT: 'Checkpoint',
1680
+ SESSION_TIMEOUT: `${t('DISSOLVE')}`,
1681
+ };
1682
+ return map[type] ?? type.toLowerCase().replace(/_/g, ' ');
1683
+ };
1684
+
1685
+ /** `politik integrity` — read the record for bad-faith patterns (integrity.ts). */
1686
+ const cmdIntegrity = async (argv: readonly string[]): Promise<number> => {
1687
+ const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' } } });
1688
+ const dir = values.dir ?? '.';
1689
+ const { state, hansard } = await loadSession(dir);
1690
+ if (state === null) { err(`integrity: ${dir} is not a session repo`); return EXIT.USAGE; }
1691
+
1692
+ const findings = reviewIntegrity(hansard);
1693
+ if (findings.length === 0) {
1694
+ out('no bad-faith patterns detected — the record is clean');
1695
+ return EXIT.OK;
1696
+ }
1697
+ const vices = findings.filter((f) => f.kind === 'vice');
1698
+ const virtues = findings.filter((f) => f.kind === 'virtue');
1699
+ for (const f of vices) out(` [${f.severity.toUpperCase()}] ${f.signature} — ${f.evidence}`);
1700
+ for (const f of virtues) out(` [praise] ${f.signature} — ${f.evidence}`);
1701
+ out('');
1702
+ out(`${vices.length} vice finding(s), ${virtues.length} virtue(s). Surfaced to the Speaker; no action taken — the Speaker rules.`);
1703
+ // A high-severity vice exits non-zero so a watching Speaker/CI is alerted.
1704
+ return vices.some((f) => f.severity === 'high') ? EXIT.REFUSED : EXIT.OK;
1705
+ };
1706
+
1707
+ /** `politik hansard` — the record, rendered in the protocol's vocabulary. */
1708
+ const cmdHansard = async (argv: readonly string[]): Promise<number> => {
1709
+ const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' } } });
1710
+ const dir = values.dir ?? '.';
1711
+ const { state, hansard, charter } = await loadSession(dir);
1712
+ if (state === null) { err(`hansard: ${dir} is not a session repo`); return EXIT.USAGE; }
1713
+
1714
+ const protocol = charter === null ? null : await sessionProtocol(charter.protocol);
1715
+ const entries = parseEntries(hansard);
1716
+ out(`RECORD — ${charter?.protocol ?? 'session'} (${entries.length} entr${entries.length === 1 ? 'y' : 'ies'})`);
1717
+ out('');
1718
+ for (const entry of entries) {
1719
+ out(`${entry.at} ${translateEntryType(protocol, entry.type)}`);
1720
+ out(` by ${entry.actor} (${asRoleTerm(protocol, entry.role)})`);
1721
+ const body = (entry.fields['Body'] ?? '').trim();
1722
+ if (body !== '') out(` ${body}`);
1723
+ }
1724
+ return EXIT.OK;
1725
+ };
1726
+
1727
+ const cmdStatus = async (argv: readonly string[]): Promise<number> => {
1728
+ const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' } } });
1729
+ const dir = values.dir ?? '.';
1730
+
1731
+ const raw = await readIfPresent(join(dir, 'STATE.json'));
1732
+ if (raw === null) {
1733
+ err(`status: no STATE.json in ${dir} — not a session repo`);
1734
+ return EXIT.USAGE;
1735
+ }
1736
+
1737
+ const state = parseState(raw);
1738
+ if (state === null) {
1739
+ err('status: STATE.json is unreadable');
1740
+ return EXIT.REFUSED;
1741
+ }
1742
+
1743
+ out(`session ${state.session_guid}`);
1744
+ out(`protocol ${state.protocol}`);
1745
+ out(`state ${state.state}`);
1746
+ if (state.suspension !== null) {
1747
+ out(`cause ${state.suspension.cause} since ${state.suspension.since}`);
1748
+ }
1749
+ out(`quorum ${state.quorum.present} of ${state.quorum.required}`);
1750
+ out(`updated ${state.updated_at} by ${state.updated_by}`);
1751
+
1752
+ const hansard = await readIfPresent(join(dir, 'HANSARD.md'));
1753
+ if (hansard !== null) {
1754
+ const entries = parseEntries(hansard);
1755
+ out(`record ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'}`);
1756
+ const last = entries.at(-1);
1757
+ if (last !== undefined) out(`last ${last.type} by ${last.actor} at ${last.at}`);
1758
+ }
1759
+ return EXIT.OK;
1760
+ };
1761
+
1762
+ const cmdProrogue = async (argv: readonly string[]): Promise<number> => {
1763
+ const { values } = parseArgs({
1764
+ args: [...argv],
1765
+ options: {
1766
+ dir: { type: 'string' },
1767
+ actor: { type: 'string' },
1768
+ role: { type: 'string' },
1769
+ trigger: { type: 'string' },
1770
+ summary: { type: 'string' },
1771
+ },
1772
+ });
1773
+
1774
+ const dir = values.dir ?? '.';
1775
+ if (values.actor === undefined || values.role === undefined) {
1776
+ err('prorogue: --actor and --role are required');
1777
+ return EXIT.USAGE;
1778
+ }
1779
+ if (badRole(values.role)) {
1780
+ err(`prorogue: "${values.role}" is not a CANON role`);
1781
+ return EXIT.USAGE;
1782
+ }
1783
+
1784
+ const rawState = await readIfPresent(join(dir, 'STATE.json'));
1785
+ const state = rawState === null ? null : parseState(rawState);
1786
+ if (state === null) {
1787
+ err(`prorogue: no readable STATE.json in ${dir}`);
1788
+ return EXIT.USAGE;
1789
+ }
1790
+
1791
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
1792
+ const trigger = (values.trigger ?? 'TRIGGER_SPEAKER') as Trigger;
1793
+
1794
+ try {
1795
+ const result = prorogue(
1796
+ {
1797
+ at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
1798
+ actor: values.actor,
1799
+ role: values.role as never,
1800
+ trigger,
1801
+ state,
1802
+ check: checkTermination(
1803
+ { max_motions: null, deadline: null, max_cost_usd: null },
1804
+ { motions: 0, total_cost_usd: 0, now: new Date().toISOString() },
1805
+ trigger === 'TRIGGER_SPEAKER',
1806
+ ),
1807
+ summary: values.summary,
1808
+ },
1809
+ hansard,
1810
+ );
1811
+
1812
+ await logAct(dir, values.actor, values.role as never, `PROROGUED ${trigger}`);
1813
+ await writeState(dir, result.state);
1814
+ await writeHansard(dir, result.hansard);
1815
+ await writeFiles(dir, result.files);
1816
+ // The seal is the one act that most needs to be in the immutable record —
1817
+ // "the Hansard is sealed" must be true on git, not just in the working tree.
1818
+ // Commit the record and the rendered summary the seal produces.
1819
+ const rec = await commitAct(dir, `PROROGUED — ${trigger}`, ['SUMMARY.md']);
1820
+
1821
+ out('PROROGUED');
1822
+ out(` trigger ${trigger}`);
1823
+ out(' the Hansard is sealed');
1824
+ if (result.milestone_to_close !== null) {
1825
+ out(` milestone ${result.milestone_to_close} must be closed on the SCM`);
1826
+ }
1827
+ reportCommit(rec);
1828
+ return EXIT.OK;
1829
+ } catch (error) {
1830
+ err(`prorogue refused: ${error instanceof Error ? error.message : String(error)}`);
1831
+ return EXIT.REFUSED;
1832
+ }
1833
+ };
1834
+
1835
+ /**
1836
+ * `politik challenge` — a DELEGATE formally disputes an AUTHORITY action.
1837
+ *
1838
+ * Attribution, not obstruction (RUNTIME.md § DELEGATE Challenge Verb): the
1839
+ * AUTHORITY action stands, but the dissent is on the permanent record with a
1840
+ * name against it. Records; never suspends or overturns.
1841
+ */
1842
+ const cmdChallenge = async (argv: readonly string[]): Promise<number> => {
1843
+ const { values } = parseArgs({
1844
+ args: [...argv],
1845
+ options: {
1846
+ dir: { type: 'string' }, actor: { type: 'string' }, role: { type: 'string' },
1847
+ against: { type: 'string' }, grounds: { type: 'string' }, window: { type: 'string' },
1848
+ },
1849
+ });
1850
+ const dir = values.dir ?? '.';
1851
+ const { hansard, charter } = await loadSession(dir);
1852
+ if (charter === null) { err(`challenge: ${dir} is not a session repo`); return EXIT.USAGE; }
1853
+ if (values.actor === undefined || values.against === undefined || values.grounds === undefined) {
1854
+ err('challenge: --actor, --against and --grounds are required'); return EXIT.USAGE;
1855
+ }
1856
+ if (badRole(values.role)) { err(`challenge: "${values.role}" is not a CANON role`); return EXIT.USAGE; }
1857
+ const windowMinutes = values.window === undefined ? 30 : Number(values.window);
1858
+
1859
+ try {
1860
+ const result = challengeAction(nowStamp(), values.actor, (values.role ?? 'DELEGATE') as never,
1861
+ values.against, values.grounds, windowMinutes, hansard);
1862
+ await writeHansard(dir, result.hansard);
1863
+ await logAct(dir, values.actor, (values.role ?? 'DELEGATE') as never, `DELEGATE_CHALLENGE against ${values.against}`);
1864
+ const rec = await commitAct(dir, `DELEGATE_CHALLENGE — ${values.actor} vs ${values.against}`);
1865
+ out(`CHALLENGE recorded — ${values.actor} disputes ${values.against}`);
1866
+ out(' the AUTHORITY action stands; the dissent is permanent and attributable');
1867
+ reportCommit(rec);
1868
+ return EXIT.OK;
1869
+ } catch (error) {
1870
+ err(`challenge refused: ${error instanceof Error ? error.message : String(error)}`);
1871
+ return EXIT.REFUSED;
1872
+ }
1873
+ };
1874
+
1875
+ /**
1876
+ * `politik standings` — score a competitive protocol from the record.
1877
+ *
1878
+ * A read over the Hansard (like `integrity`): who won the most divisions
1879
+ * (win-loss) or who lasted longest (survival). Neutral on protocol — a
1880
+ * parliamentary session simply shows how each actor's votes fared.
1881
+ */
1882
+ const cmdStandings = async (argv: readonly string[]): Promise<number> => {
1883
+ const { values } = parseArgs({
1884
+ args: [...argv],
1885
+ options: { dir: { type: 'string' }, by: { type: 'string' } },
1886
+ });
1887
+ const dir = values.dir ?? '.';
1888
+ const { hansard, charter } = await loadSession(dir);
1889
+ if (charter === null) { err(`standings: ${dir} is not a session repo`); return EXIT.USAGE; }
1890
+
1891
+ const by: RankBy = values.by === 'survival' ? 'survival' : 'win-loss';
1892
+ const table = standings(hansard, by);
1893
+ if (table.length === 0) { out('no standings — no actor has taken part yet'); return EXIT.OK; }
1894
+
1895
+ const protocol = await sessionProtocol(charter.protocol);
1896
+ out(`STANDINGS — by ${by}`);
1897
+ let rankNo = 0;
1898
+ for (const row of table) {
1899
+ rankNo += 1;
1900
+ const seat = row.seat === null
1901
+ ? (row.eliminated ? 'eliminated' : 'out')
1902
+ : asRoleTerm(protocol, row.seat);
1903
+ out(` ${String(rankNo).padStart(2)}. ${row.actor.padEnd(14)} ${row.wins}–${row.losses} · ${seat}`);
1904
+ }
1905
+ return EXIT.OK;
1906
+ };
1907
+
1908
+ /**
1909
+ * `politik pair` — generate the next round of MATCHes (ADR-0009).
1910
+ *
1911
+ * The field is the seated actors; the format decides who faces whom (swiss by
1912
+ * score, round-robin by unplayed pair, single-elim among the undefeated). A bye
1913
+ * is created already decided. The Speaker then reports each result with
1914
+ * `politik match report`.
1915
+ */
1916
+ const cmdPair = async (argv: readonly string[]): Promise<number> => {
1917
+ const { values } = parseArgs({
1918
+ args: [...argv],
1919
+ options: { dir: { type: 'string' }, format: { type: 'string' }, actor: { type: 'string' }, round: { type: 'string' } },
1920
+ });
1921
+ const dir = values.dir ?? '.';
1922
+ const { hansard, charter } = await loadSession(dir);
1923
+ if (charter === null) { err(`pair: ${dir} is not a session repo`); return EXIT.USAGE; }
1924
+ if (!isPairingFormat(values.format)) {
1925
+ err('pair: --format must be swiss | round-robin | single-elim'); return EXIT.USAGE;
1926
+ }
1927
+
1928
+ const contestants = seats(hansard).map((s) => s.actor);
1929
+ if (contestants.length < 2) { err('pair: fewer than two contestants are seated'); return EXIT.REFUSED; }
1930
+ const played = matches(hansard);
1931
+ const round = values.round !== undefined
1932
+ ? Number(values.round)
1933
+ : Math.max(0, ...played.map((m) => m.round)) + 1;
1934
+
1935
+ const pairings = pairRound(contestants, standings(hansard), values.format, round, played);
1936
+ if (pairings.length === 0) {
1937
+ out(`no pairings for round ${round} — the ${values.format} field is decided`);
1938
+ return EXIT.OK;
1939
+ }
1940
+
1941
+ let doc = hansard;
1942
+ for (const pairing of pairings) {
1943
+ const created = matchCreatedEntry(pairing, round, nowStamp());
1944
+ doc = appendEntry(doc, created);
1945
+ if (pairing.b === null) {
1946
+ // A bye advances unopposed — record it decided so standings count it.
1947
+ doc = appendEntry(doc, matchDecidedEntry(
1948
+ created.fields?.['Match'] ?? '', round, pairing.a, null, nowStamp(), values.actor ?? 'RECORD'));
1949
+ }
1950
+ }
1951
+ await writeHansard(dir, doc);
1952
+ await logAct(dir, values.actor ?? 'RECORD', 'OPERATOR' as never, `PAIRED round ${round} (${values.format})`);
1953
+ const rec = await commitAct(dir, `MATCH_PAIRING — round ${round} (${values.format})`);
1954
+ out(`ROUND ${round} — ${values.format}`);
1955
+ for (const pairing of pairings) out(` ${pairing.a} vs ${pairing.b ?? 'BYE'}`);
1956
+ out(' report each result: politik match report --match <id> --winner <contestant>');
1957
+ reportCommit(rec);
1958
+ return EXIT.OK;
1959
+ };
1960
+
1961
+ /** `politik match report|list` — resolve or view MATCHes (ADR-0009). */
1962
+ const cmdMatch = async (argv: readonly string[]): Promise<number> => {
1963
+ const [verb, ...rest] = argv;
1964
+ const { values } = parseArgs({
1965
+ args: rest,
1966
+ options: { dir: { type: 'string' }, match: { type: 'string' }, winner: { type: 'string' }, actor: { type: 'string' } },
1967
+ });
1968
+ const dir = values.dir ?? '.';
1969
+ const { hansard, charter } = await loadSession(dir);
1970
+ if (charter === null) { err(`match: ${dir} is not a session repo`); return EXIT.USAGE; }
1971
+
1972
+ if (verb === 'list') {
1973
+ const all = matches(hansard);
1974
+ if (all.length === 0) { out('no matches yet — pair a round first'); return EXIT.OK; }
1975
+ for (const m of all) {
1976
+ const status = m.winner === null ? 'open' : `${m.winner} won`;
1977
+ out(` [${status.padEnd(12)}] ${m.id} · ${m.a} vs ${m.b ?? 'bye'}`);
1978
+ }
1979
+ return EXIT.OK;
1980
+ }
1981
+
1982
+ if (verb === 'report') {
1983
+ if (values.match === undefined || values.winner === undefined) {
1984
+ err('match report: --match and --winner are required'); return EXIT.USAGE;
1985
+ }
1986
+ try {
1987
+ const result = reportMatch(values.match, values.winner, nowStamp(), values.actor ?? 'RECORD', hansard);
1988
+ await writeHansard(dir, result.hansard);
1989
+ await logAct(dir, values.actor ?? 'RECORD', 'AUTHORITY' as never, `MATCH_DECIDED ${values.match} -> ${values.winner}`);
1990
+ const rec = await commitAct(dir, `MATCH_DECIDED — ${values.match}: ${values.winner}`);
1991
+ out(`MATCH ${values.match} — ${values.winner} won`);
1992
+ reportCommit(rec);
1993
+ return EXIT.OK;
1994
+ } catch (error) {
1995
+ err(`match refused: ${error instanceof Error ? error.message : String(error)}`);
1996
+ return EXIT.REFUSED;
1997
+ }
1998
+ }
1999
+
2000
+ err(`match: unknown verb "${verb ?? ''}" — expected report | list`);
2001
+ return EXIT.USAGE;
2002
+ };
2003
+
2004
+ /** A one-glance mark for a node's state — colour-free, terminal-safe. */
2005
+ const stateMark = (state: string): string => {
2006
+ switch (state) {
2007
+ case 'CONVENED': return '[OK]';
2008
+ case 'SUSPENDED': return '[!!]';
2009
+ case 'PROROGUED': return '[--]';
2010
+ case 'STALE': return '[~~]';
2011
+ case 'INVALID': return '[XX]';
2012
+ default: return '[??]';
2013
+ }
2014
+ };
2015
+
2016
+ /**
2017
+ * `politik registry` — the state of everything. Walks the tree (ADR-0008
2018
+ * federation-as-traversal), prints every session with its state, protocol and
2019
+ * cost, and a roll-up. `--state <S>` answers "show all SUSPENDED under here"; the
2020
+ * roll-up always totals the whole tree so the filter never hides the context.
2021
+ */
2022
+ const cmdRegistry = async (argv: readonly string[]): Promise<number> => {
2023
+ const { values } = parseArgs({
2024
+ args: [...argv],
2025
+ options: { dir: { type: 'string' }, state: { type: 'string' } },
2026
+ });
2027
+ const root = resolve(values.dir ?? '.');
2028
+ const nodes = await discoverTree(root);
2029
+ if (nodes.length === 0) {
2030
+ err(`registry: no sessions found under ${values.dir ?? '.'}`);
2031
+ return EXIT.USAGE;
2032
+ }
2033
+
2034
+ const filter = values.state?.toUpperCase();
2035
+ const shown: readonly FederationNode[] = filter === undefined
2036
+ ? nodes
2037
+ : nodes.filter((n) => n.state === filter);
2038
+
2039
+ out(`REGISTRY — ${values.dir ?? '.'}`);
2040
+ for (const node of shown) {
2041
+ const indent = ' '.repeat(node.depth + 1);
2042
+ const cost = node.cost_usd > 0 ? ` $${node.cost_usd.toFixed(4)}` : '';
2043
+ const cause = node.cause === null ? '' : ` (${node.cause})`;
2044
+ out(`${indent}${stateMark(node.state)} ${node.rel} · ${node.protocol} · ${node.state}${cost}${cause}`);
2045
+ }
2046
+ if (filter !== undefined && shown.length === 0) out(` (no ${filter} sessions)`);
2047
+
2048
+ const summary = rollUp(nodes);
2049
+ out('');
2050
+ out(' -- roll-up (whole tree) --');
2051
+ out(` nodes ${summary.nodes}`);
2052
+ out(` by state ${Object.entries(summary.by_state).map(([s, c]) => `${s} ${c}`).join(' ')}`);
2053
+ out(` open motions ${summary.open_divisions}`);
2054
+ out(` total cost $${summary.total_cost_usd.toFixed(4)}`);
2055
+ out(` total tokens ${summary.total_tokens.toLocaleString()}`);
2056
+ return EXIT.OK;
2057
+ };
2058
+
2059
+ /**
2060
+ * `politik cascade` — a fault repeating across siblings is a signal, not a
2061
+ * coincidence. Walks the tree, and where enough siblings share a suspension
2062
+ * cause within the window (tree.ts checkCascade), records a CASCADE_ALERT on
2063
+ * their parent so a Speaker chartering the same configuration is warned. Idempotent:
2064
+ * a parent already carrying the alert is left alone.
2065
+ */
2066
+ const cmdCascade = async (argv: readonly string[]): Promise<number> => {
2067
+ const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' } } });
2068
+ const root = resolve(values.dir ?? '.');
2069
+ const nodes = await discoverTree(root);
2070
+ const findings = detectCascades(nodes, nowStamp());
2071
+ if (findings.length === 0) {
2072
+ out('no cascades — no fault repeats across siblings within the window');
2073
+ return EXIT.OK;
2074
+ }
2075
+
2076
+ for (const finding of findings) {
2077
+ const signature = finding.alert.signature ?? 'unknown';
2078
+ if (cascadeAlerts(finding.parent.hansard).includes(signature)) {
2079
+ out(`${finding.parent.rel}: cascade on ${signature} already recorded`);
2080
+ continue;
2081
+ }
2082
+ const updated = recordOnNode(finding.parent.hansard, cascadeEntry(finding.alert, nowStamp()));
2083
+ await writeHansard(finding.parent.dir, updated);
2084
+ const rec = await commitAct(finding.parent.dir,
2085
+ `CASCADE_ALERT — ${signature} across ${finding.alert.nodes.length} siblings`);
2086
+ out(`CASCADE — ${signature} across ${finding.alert.nodes.length} siblings`);
2087
+ out(` recorded on ${finding.parent.rel}`);
2088
+ reportCommit(rec);
2089
+ }
2090
+ return EXIT.OK;
2091
+ };
2092
+
2093
+ /* -------------------------------------------------------------------------- */
2094
+ /* Entry */
2095
+ /* -------------------------------------------------------------------------- */
2096
+
2097
+ export const run = async (argv: readonly string[]): Promise<number> => {
2098
+ const [command, ...rest] = argv;
2099
+
2100
+ switch (command) {
2101
+ case undefined:
2102
+ case '-h':
2103
+ case '--help':
2104
+ case 'help':
2105
+ out(USAGE);
2106
+ return EXIT.OK;
2107
+ case 'version':
2108
+ case '--version':
2109
+ out(VERSION);
2110
+ return EXIT.OK;
2111
+ case 'scaffold':
2112
+ return cmdScaffold(rest);
2113
+ case 'doctor':
2114
+ return cmdDoctor();
2115
+ case 'protocol':
2116
+ return cmdProtocol(rest);
2117
+ case 'validate':
2118
+ return cmdValidate(rest);
2119
+ case 'init':
2120
+ return cmdInit(rest);
2121
+ case 'crisis':
2122
+ return cmdCrisis(rest);
2123
+ case 'division':
2124
+ return cmdDivision(rest);
2125
+ case 'assent':
2126
+ return cmdAssent(rest);
2127
+ case 'heartbeat':
2128
+ return cmdHeartbeat(rest);
2129
+ case 'snapshot':
2130
+ return cmdSnapshot(rest);
2131
+ case 'resume':
2132
+ return cmdResume(rest);
2133
+ case 'actor':
2134
+ return cmdActor(rest);
2135
+ case 'escalate':
2136
+ return cmdEscalate(rest);
2137
+ case 'rule':
2138
+ return cmdRule(rest);
2139
+ case 'conflict':
2140
+ return cmdConflict(rest);
2141
+ case 'broadcast':
2142
+ return cmdBroadcast(rest);
2143
+ case 'motion':
2144
+ return cmdMotion(rest);
2145
+ case 'ledger':
2146
+ return cmdLedger(rest);
2147
+ case 'run':
2148
+ return cmdRun(rest);
2149
+ case 'hansard':
2150
+ return cmdHansard(rest);
2151
+ case 'integrity':
2152
+ return cmdIntegrity(rest);
2153
+ case 'status':
2154
+ return cmdStatus(rest);
2155
+ case 'prorogue':
2156
+ return cmdProrogue(rest);
2157
+ case 'registry':
2158
+ return cmdRegistry(rest);
2159
+ case 'cascade':
2160
+ return cmdCascade(rest);
2161
+ case 'challenge':
2162
+ return cmdChallenge(rest);
2163
+ case 'standings':
2164
+ return cmdStandings(rest);
2165
+ case 'pair':
2166
+ return cmdPair(rest);
2167
+ case 'match':
2168
+ return cmdMatch(rest);
2169
+ default:
2170
+ err(`unknown command: ${command}`);
2171
+ err(USAGE);
2172
+ return EXIT.USAGE;
2173
+ }
2174
+ };