@cordfuse/politik 0.3.0 → 0.4.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.
package/src/cli.ts CHANGED
@@ -8,20 +8,32 @@
8
8
  * Attribution: Steve Krisjanovs, Cordfuse
9
9
  */
10
10
 
11
- import { readFileSync } from 'node:fs';
12
- import { readFile, writeFile, mkdir, rename } from 'node:fs/promises';
11
+ import { existsSync, readFileSync } from 'node:fs';
12
+ import { readFile, readdir, writeFile, mkdir, rename, rm } from 'node:fs/promises';
13
13
  import { dirname, join, relative, resolve } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { parseArgs } from 'node:util';
16
16
 
17
17
  import { isRole, type Role } from './canon.ts';
18
- import { parseCharter, validateCharter } from './charter.ts';
18
+ import { charterFingerprint, instructionsFingerprint, parseCharter, validateCharter } from './charter.ts';
19
19
  import { dropWrit } from './init.ts';
20
20
  import { initSessionRepo } from './git.ts';
21
21
  import { parseState, serializeState, type SessionStateFile } from './state.ts';
22
- import { parliamentaryTemplates } from './templates/parliamentary.ts';
22
+ import { INSTRUCTION_FILES, bootstrapTemplate, pointerFiles, scaffoldTemplates } from './templates/parliamentary.ts';
23
23
  import { generateProtocol, lintSource } from './protocol-sdk.ts';
24
24
  import { diagnose } from './doctor.ts';
25
+ import {
26
+ isPendingId, listPending, readPending, removePending, stagePending, withDir,
27
+ type ConstitutionalAct,
28
+ } from './pending.ts';
29
+ import { createInterface } from 'node:readline/promises';
30
+ import {
31
+ configureClone, disableSync, discardTo, enableSync, fastForward, fetchRemote, gitx, headSha,
32
+ operatorHandle, operatorIdentity, pushRecord, syncConfig, syncNow,
33
+ } from './remote.ts';
34
+ import {
35
+ CONFIRMED_BY_SPEAKER, detectHarness, isSpeakerAtTerminal, provenanceTrailers, requestedVia,
36
+ } from './operator.ts';
25
37
  import { runTurn } from './runner.ts';
26
38
  import { GitTransport } from './transport.ts';
27
39
  import { conflictEntry, detectRecordConflicts, openConflicts, resolveConflict } from './conflict.ts';
@@ -53,11 +65,12 @@ import {
53
65
  isExitPolicy, isResolution, recordOutcome, suspendForDeadlock, tallyDivision, type Vote,
54
66
  } from './division.ts';
55
67
  import {
56
- PROTOCOL_MODES, parseProtocol, roleTerm, term, type Protocol, type ProtocolMode,
68
+ PROTOCOL_MODES, allowsCharterAmendment, parseProtocol, roleTerm, term,
69
+ type Protocol, type ProtocolMode,
57
70
  } from './protocol.ts';
58
71
  import { reviewIntegrity } from './integrity.ts';
59
72
  import { checkTermination, isTerminationPolicy, lastStanding, prorogue, type Trigger } from './prorogation.ts';
60
- import { appendEntry, parseEntries } from './hansard.ts';
73
+ import { RECORD_TYPES, appendEntry, parseEntries } from './hansard.ts';
61
74
  import type { FileWrite } from './scm.ts';
62
75
 
63
76
  /**
@@ -77,12 +90,21 @@ const USAGE = `politik — governed multi-agent sessions on git
77
90
 
78
91
  Usage
79
92
  politik version
80
- politik scaffold --dir <dir> [--protocol parliamentary] [--quorum <n>] [--parent <dir>]
93
+ politik new <dir> # start here: folder + instructions for your AI harness
94
+ politik scaffold [--dir <dir>] [--protocol parliamentary] [--quorum <n>] [--parent <dir>]
95
+ [--speaker-confirmation required|off]
81
96
  politik doctor
97
+ politik pending [--dir <dir>] [--json] # constitutional acts staged for the Speaker
98
+ politik confirm <id> [--dir <dir>] # the Speaker, at a terminal: execute a staged act
99
+ politik reject <id> [--dir <dir>] # discard a staged act
100
+ politik remote [<url>] [--as <handle>] [--off] # share this session through a git remote
101
+ politik join <url> [<dir>] --as <handle> # take a seat in a shared session from this machine
102
+ politik sync [--dir <dir>] # reconcile this clone with the shared record
103
+ politik protocol list # the shipped protocols
82
104
  politik protocol lint <manifest.yml>
83
105
  politik protocol new <name> [--mode <mode>] [--out <dir>]
84
106
  politik validate <charter.md> [--protocol <name>]
85
- politik init --charter <path> --speaker <handle> [--dir <dir>] [--guid <id>] [--standalone]
107
+ politik init --charter <path> --speaker <handle> [--dir <dir>] [--guid <id>] [--standalone] [--remote <url>]
86
108
  politik run --agent <id> --actor <h> --role <ROLE> (--task <text> | --claim)
87
109
  politik division call --motion <id> --actor <h> --role <ROLE> [--reviewers a,b]
88
110
  politik division vote --motion <id> --actor <h> --role <ROLE> --vote AYE|NO|ABSTAIN
@@ -107,10 +129,10 @@ Usage
107
129
  politik broadcast --target <ROLE> --slots <n> --task <text> [--dir <dir>]
108
130
  politik motion link --motion <id> --pr <n> [--url <u>]
109
131
  politik ledger [--dir <dir>]
110
- politik status [--dir <dir>]
132
+ politik status [--dir <dir>] [--json]
111
133
  politik hansard [--dir <dir>] # the record, in the protocol's vocabulary
112
134
  politik integrity [--dir <dir>] # scan the record for bad-faith patterns
113
- politik prorogue --dir <dir> --actor <handle> --role <ROLE> --trigger <TRIGGER>
135
+ politik prorogue [--dir <dir>] --actor <handle> --role <ROLE> --trigger <TRIGGER>
114
136
  politik standings [--dir <dir>] [--by win-loss|survival] # score a competitive protocol
115
137
  politik pair --format swiss|round-robin|single-elim [--dir <dir>] # pair the next round of MATCHes
116
138
  politik match report --match <id> --winner <contestant> [--actor <referee>]
@@ -153,8 +175,23 @@ Commands
153
175
  /* Output */
154
176
  /* -------------------------------------------------------------------------- */
155
177
 
156
- const out = (line = '') => process.stdout.write(`${line}\n`);
157
- const err = (line: string) => process.stderr.write(`${line}\n`);
178
+ /**
179
+ * Output is buffered while a shared-session act is attempted (ADR-0011 §2): if the
180
+ * push is rejected the attempt is discarded and redone, and the operator must only
181
+ * ever see the attempt that was actually recorded.
182
+ */
183
+ let outputBuffer: Array<readonly ['out' | 'err', string]> | null = null;
184
+ const out = (line = '') => {
185
+ if (outputBuffer !== null) outputBuffer.push(['out', line]);
186
+ else process.stdout.write(`${line}\n`);
187
+ };
188
+ const err = (line: string) => {
189
+ if (outputBuffer !== null) outputBuffer.push(['err', line]);
190
+ else process.stderr.write(`${line}\n`);
191
+ };
192
+ const flushOutput = (lines: ReadonlyArray<readonly ['out' | 'err', string]>): void => {
193
+ for (const [stream, line] of lines) (stream === 'out' ? process.stdout : process.stderr).write(`${line}\n`);
194
+ };
158
195
 
159
196
  /**
160
197
  * A supplied --role/--target must name a CANON role; an absent one falls back to
@@ -166,7 +203,8 @@ const err = (line: string) => process.stderr.write(`${line}\n`);
166
203
  const badRole = (value: string | undefined): boolean => value !== undefined && !isRole(value);
167
204
 
168
205
  /** Exit codes: 0 success, 1 refusal (invalid input), 2 usage error. */
169
- const EXIT = { OK: 0, REFUSED: 1, USAGE: 2 } as const;
206
+ /** PENDING (ADR-0010): the act was staged for the Speaker's confirmation, not recorded. */
207
+ const EXIT = { OK: 0, REFUSED: 1, USAGE: 2, PENDING: 3 } as const;
170
208
 
171
209
  /* -------------------------------------------------------------------------- */
172
210
  /* Helpers */
@@ -212,6 +250,7 @@ const cmdScaffold = async (argv: readonly string[]): Promise<number> => {
212
250
  termination: { type: 'string' },
213
251
  escalation: { type: 'string' },
214
252
  parent: { type: 'string' },
253
+ 'speaker-confirmation': { type: 'string' },
215
254
  },
216
255
  });
217
256
 
@@ -234,6 +273,11 @@ const cmdScaffold = async (argv: readonly string[]): Promise<number> => {
234
273
  return EXIT.USAGE;
235
274
  }
236
275
 
276
+ const speakerConfirmation = values['speaker-confirmation'] ?? 'required';
277
+ if (speakerConfirmation !== 'required' && speakerConfirmation !== 'off') {
278
+ err('scaffold: --speaker-confirmation must be required | off');
279
+ return EXIT.USAGE;
280
+ }
237
281
  const quorum = values.quorum === undefined ? undefined : Number(values.quorum);
238
282
  if (quorum !== undefined && (!Number.isInteger(quorum) || quorum < 1)) {
239
283
  err('scaffold: --quorum must be an integer >= 1');
@@ -270,7 +314,7 @@ const cmdScaffold = async (argv: readonly string[]): Promise<number> => {
270
314
  // the lineage resolves from within the session's own directory. init detects
271
315
  // the enclosing repo and commits the writ drop there rather than nesting a repo.
272
316
  const inherits_from = values.parent === undefined ? null : (relative(dir, values.parent) || '.');
273
- const files = parliamentaryTemplates({
317
+ const files = scaffoldTemplates(manifest.protocol, {
274
318
  protocol,
275
319
  ...(inherits_from === null ? {} : { inherits_from }),
276
320
  ...(quorum === undefined ? {} : { quorum }),
@@ -278,16 +322,403 @@ const cmdScaffold = async (argv: readonly string[]): Promise<number> => {
278
322
  exit: values.exit ?? m.exit,
279
323
  termination: values.termination ?? m.termination,
280
324
  escalation: values.escalation ?? (manifest.protocol.no_escalation ? 'disabled' : 'enabled'),
325
+ speaker_confirmation: speakerConfirmation,
281
326
  });
327
+ // Scaffold writes over same-named files (ADR-0010: it replaces the bootstrap
328
+ // instructions `politik new` leaves). Say so, rather than doing it silently.
329
+ const replaced = new Set(files.filter((f) => existsSync(join(dir, f.path))).map((f) => f.path));
282
330
  await writeFiles(dir, files);
283
331
 
284
332
  out(`SCAFFOLDED ${protocol}`);
285
- for (const file of files) out(` ${file.path}`);
333
+ for (const file of files) out(` ${file.path}${replaced.has(file.path) ? ' (replaced existing file)' : ''}`);
286
334
  out('');
287
335
  out(`Edit the Standing Orders, then: politik init --charter ${join(dir, 'CHARTER.md')} --speaker <handle>`);
288
336
  return EXIT.OK;
289
337
  };
290
338
 
339
+ /**
340
+ * `politik new <dir>` — the operator's front door (ADR-0010 §1).
341
+ *
342
+ * Creates the folder and writes bootstrap instructions for whichever harness the
343
+ * operator opens there; the harness runs first-time setup as a conversation and
344
+ * calls `scaffold` and `init` itself. Deliberately does almost nothing: protocol,
345
+ * quorum and seats are decided in that conversation, not by flags here.
346
+ */
347
+ const cmdNew = async (argv: readonly string[]): Promise<number> => {
348
+ const target = argv[0];
349
+ if (target === undefined || target.startsWith('-')) {
350
+ err('new: a folder name is required — politik new <dir>');
351
+ return EXIT.USAGE;
352
+ }
353
+ if (existsSync(target) && (await readdir(target)).length > 0) {
354
+ err(`new: ${target} already exists and is not empty. To set up a session in an existing folder, run: politik scaffold --dir ${target}`);
355
+ return EXIT.REFUSED;
356
+ }
357
+ const files = [{ path: 'AGENTS.md', content: bootstrapTemplate() }, ...pointerFiles()];
358
+ await writeFiles(target, files);
359
+
360
+ out(`NEW SESSION FOLDER ${target}`);
361
+ for (const file of files) out(` ${file.path}`);
362
+ out('');
363
+ out(`Next: cd ${target} and open your AI harness (claude, codex, agy, opencode…).`);
364
+ out('It will walk you through choosing a protocol, writing the Charter, and convening the session.');
365
+ return EXIT.OK;
366
+ };
367
+
368
+
369
+ /* -------------------------------------------------------------------------- */
370
+ /* Shared sessions across machines (ADR-0011) */
371
+ /* -------------------------------------------------------------------------- */
372
+
373
+ /** Nesting depth of sync: only the outermost governance command syncs. */
374
+ let syncDepth = 0;
375
+
376
+ /**
377
+ * Run a governance act against a shared session: fetch and fast-forward, act,
378
+ * push. If the push is rejected because someone acted first, discard the local
379
+ * attempt, catch up, and recompute — up to three attempts — showing only the
380
+ * output of the attempt that was recorded. An unshared session, or a nested call,
381
+ * runs the act directly.
382
+ */
383
+ const withSync = async (
384
+ dir: string,
385
+ exec: () => Promise<number>,
386
+ opts: { readonly retry: boolean },
387
+ ): Promise<number> => {
388
+ const cfg = syncDepth > 0 ? null : await syncConfig(dir);
389
+ if (cfg === null) return exec();
390
+ syncDepth += 1;
391
+ try {
392
+ const attempts = opts.retry ? 3 : 1;
393
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
394
+ const fetched = await fetchRemote(dir, cfg);
395
+ if (!fetched.ok) {
396
+ err(`Refused: this is a shared session and ${cfg.remote} cannot be reached (${fetched.reason}).`);
397
+ err(' Acting offline would let acts land out of order. Reads still work; try again when connected.');
398
+ return EXIT.REFUSED;
399
+ }
400
+ const ff = await fastForward(dir, cfg);
401
+ if (ff === 'diverged' || ff === 'blocked') {
402
+ err(ff === 'diverged'
403
+ ? 'Refused: the local and shared records have diverged. Run: politik sync'
404
+ : 'Refused: cannot catch up with the shared record — uncommitted changes conflict with it.');
405
+ return EXIT.REFUSED;
406
+ }
407
+ if (ff === 'ahead') {
408
+ const caughtUp = await pushRecord(dir, cfg);
409
+ if (!caughtUp.ok) { err(`Refused: earlier local acts are not shared yet and could not be pushed (${caughtUp.reason}). Run: politik sync`); return EXIT.REFUSED; }
410
+ }
411
+
412
+ const start = await headSha(dir);
413
+ outputBuffer = [];
414
+ let code: number;
415
+ try { code = await exec(); } catch (error) { flushOutput(outputBuffer); outputBuffer = null; throw error; }
416
+ const lines = outputBuffer;
417
+ outputBuffer = null;
418
+
419
+ const end = await headSha(dir);
420
+ if (end === start) { flushOutput(lines); return code; }
421
+
422
+ const pushed = await pushRecord(dir, cfg);
423
+ if (pushed.ok) { flushOutput(lines); return code; }
424
+
425
+ if (pushed.rejected && opts.retry && attempt < attempts && start !== null) {
426
+ if (await discardTo(dir, start)) continue;
427
+ flushOutput(lines);
428
+ err('Recorded locally, but someone else acted first and the attempt could not be redone safely. Run: politik sync');
429
+ return code;
430
+ }
431
+ flushOutput(lines);
432
+ err(pushed.rejected
433
+ ? 'Recorded locally, but not shared yet — someone else acted first. Run: politik sync'
434
+ : `Recorded locally, but could not reach ${cfg.remote} to share it (${pushed.reason}). Run: politik sync`);
435
+ return code;
436
+ }
437
+ err(`Refused: the shared session is busy — ${attempts} attempts were overtaken by other acts. Try again.`);
438
+ return EXIT.REFUSED;
439
+ } finally {
440
+ syncDepth -= 1;
441
+ }
442
+ };
443
+
444
+ /** Before a read: catch up with the shared record if possible, silently if not. */
445
+ const refreshForRead = async (dir: string): Promise<void> => {
446
+ const cfg = await syncConfig(dir);
447
+ if (cfg === null) return;
448
+ if ((await fetchRemote(dir, cfg)).ok) await fastForward(dir, cfg);
449
+ };
450
+
451
+ /** `politik remote [<url>] [--as <handle>] [--off]` — make a session shared, or show how it is. */
452
+ const cmdRemote = async (argv: readonly string[]): Promise<number> => {
453
+ const { values, positionals } = parseArgs({
454
+ args: [...argv], allowPositionals: true,
455
+ options: { dir: { type: 'string' }, as: { type: 'string' }, off: { type: 'boolean' }, name: { type: 'string' } },
456
+ });
457
+ const dir = values.dir ?? '.';
458
+ if (values.off === true) {
459
+ await disableSync(dir);
460
+ out('Sync off — this clone no longer pushes or pulls the record. The remote is unchanged.');
461
+ return EXIT.OK;
462
+ }
463
+ const url = positionals[0];
464
+ if (url === undefined) {
465
+ const cfg = await syncConfig(dir);
466
+ if (cfg === null) { out('Not shared. Share it with: politik remote <url>'); return EXIT.OK; }
467
+ const where = await gitx(dir, ['remote', 'get-url', cfg.remote]);
468
+ out(`shared via ${cfg.remote} — ${where.out || '(no url)'}`);
469
+ out(`branch ${cfg.branch}`);
470
+ out(`you are ${cfg.handle ?? '(unknown — set with: politik remote --as <handle>)'}`);
471
+ return EXIT.OK;
472
+ }
473
+ if ((await readIfPresent(join(dir, 'STATE.json'))) === null) {
474
+ err(`remote: ${dir} is not a convened session — run politik init first`);
475
+ return EXIT.USAGE;
476
+ }
477
+ const handle = values.as ?? (await writDropSpeaker(dir));
478
+ const result = await enableSync(dir, url, { remote: values.name ?? 'origin', handle });
479
+ if (!result.ok) { err(`remote: ${result.message}`); return EXIT.REFUSED; }
480
+ out(`SHARED — ${result.message}`);
481
+ if (handle !== null) out(` you are ${handle}`);
482
+ out(` Others join with: politik join ${url} <dir> --as <their handle>`);
483
+ return EXIT.OK;
484
+ };
485
+
486
+ /** The Speaker named on the WRIT_DROP entry. */
487
+ const writDropSpeaker = async (dir: string): Promise<string | null> => {
488
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
489
+ for (const entry of parseEntries(hansard)) {
490
+ if (entry.type === RECORD_TYPES.WRIT_DROP) return entry.actor;
491
+ }
492
+ return null;
493
+ };
494
+
495
+ /**
496
+ * `politik join <url> [dir] --as <handle>` — take a seat in a shared session from
497
+ * this machine: clone it, check it is a session with intact seals, turn on sync.
498
+ */
499
+ const cmdJoin = async (argv: readonly string[]): Promise<number> => {
500
+ const { values, positionals } = parseArgs({
501
+ args: [...argv], allowPositionals: true, options: { as: { type: 'string' } },
502
+ });
503
+ const url = positionals[0];
504
+ if (url === undefined) { err('join: a remote url is required — politik join <url> [dir] --as <handle>'); return EXIT.USAGE; }
505
+ const dir = positionals[1] ?? (url.replace(/\/+$/, '').split(/[/:]/).pop() ?? 'session').replace(/\.git$/, '');
506
+ if (existsSync(dir) && (await readdir(dir)).length > 0) {
507
+ err(`join: ${dir} already exists and is not empty`);
508
+ return EXIT.REFUSED;
509
+ }
510
+ const clone = await gitx('.', ['clone', '--quiet', url, dir]);
511
+ if (clone.code !== 0) { err(`join: could not clone ${url}: ${clone.err.split('\n')[0] ?? ''}`); return EXIT.REFUSED; }
512
+ await gitx(dir, ['fetch', '--quiet', 'origin', '+refs/politik/pending/*:refs/politik/pending/*']);
513
+ // A bare remote whose HEAD names a branch that was never pushed clones with
514
+ // nothing checked out. If the remote has exactly one branch, that is the record.
515
+ if ((await gitx(dir, ['rev-parse', '--verify', '--quiet', 'HEAD'])).code !== 0) {
516
+ const branches = (await gitx(dir, ['for-each-ref', '--format=%(refname:lstrip=3)', 'refs/remotes/origin/'])).out
517
+ .split('\n').filter((b) => b !== '' && b !== 'HEAD');
518
+ if (branches.length === 1 && branches[0] !== undefined) {
519
+ await gitx(dir, ['checkout', '--quiet', '-b', branches[0], '--track', `origin/${branches[0]}`]);
520
+ }
521
+ }
522
+
523
+ if ((await readIfPresent(join(dir, 'STATE.json'))) === null) {
524
+ err(`join: ${url} was cloned to ${dir}, but its root is not a convened session.`);
525
+ err(' If it is a tree of sessions, cd into the node you want and run: politik remote --as <handle> --dir .');
526
+ return EXIT.REFUSED;
527
+ }
528
+ const tampered = await instructionsViolation(dir);
529
+ if (tampered !== null) { err(`join: ${tampered}`); return EXIT.REFUSED; }
530
+
531
+ const cfg = await configureClone(dir, values.as ?? null);
532
+ if (cfg === null) { err('join: the clone is not on a branch'); return EXIT.REFUSED; }
533
+ out(`JOINED ${dir} — shared via ${cfg.remote}, branch ${cfg.branch}`);
534
+ out(` you are ${cfg.handle ?? '(unknown — set with: politik remote --as <handle>)'}`);
535
+ out('');
536
+ out(`Next: cd ${dir} and open your AI harness (claude, codex, agy, opencode…).`);
537
+ return EXIT.OK;
538
+ };
539
+
540
+ /** `politik sync` — reconcile this clone's record with the shared one. */
541
+ const cmdSync = async (argv: readonly string[]): Promise<number> => {
542
+ const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' } } });
543
+ const dir = values.dir ?? '.';
544
+ const cfg = await syncConfig(dir);
545
+ if (cfg === null) { out('Not shared — nothing to sync. Share it with: politik remote <url>'); return EXIT.OK; }
546
+ const result = await syncNow(dir, cfg);
547
+ if (!result.ok) { err(`sync: ${result.message}`); return EXIT.REFUSED; }
548
+ out(`SYNCED — ${result.message}`);
549
+ return EXIT.OK;
550
+ };
551
+
552
+ /* -------------------------------------------------------------------------- */
553
+ /* The Speaker's confirmation (ADR-0010 §2) */
554
+ /* -------------------------------------------------------------------------- */
555
+
556
+ /**
557
+ * Set only by `politik confirm`, in-process, after the Speaker has typed the act's
558
+ * id at a terminal. There is deliberately no flag or environment variable that
559
+ * sets it: a harness cannot pass its way past the gate.
560
+ */
561
+ let speakerConfirmed = false;
562
+
563
+ /** Read one line from the terminal. Only ever called when stdin is a TTY. */
564
+ const askSpeaker = async (prompt: string): Promise<string> => {
565
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
566
+ try { return (await rl.question(prompt)).trim(); } finally { rl.close(); }
567
+ };
568
+
569
+ /**
570
+ * Gate a constitutional act. Returns null when it may proceed, or an exit code
571
+ * when it must not run now.
572
+ *
573
+ * Under `speaker_confirmation: required`: a person at a terminal (no harness
574
+ * detected) is asked inline; anything else — an AI harness, a script, a pipe — has
575
+ * the act staged for `politik confirm` and nothing reaches the record. A Charter
576
+ * without the setting (every pre-ADR-0010 session) is never gated.
577
+ */
578
+ const awaitSpeaker = async (
579
+ act: ConstitutionalAct,
580
+ argv: readonly string[],
581
+ dir: string,
582
+ summary: string,
583
+ ): Promise<number | null> => {
584
+ if (speakerConfirmed) return null;
585
+ const charterRaw = await readIfPresent(join(dir, 'CHARTER.md'));
586
+ const parsed = charterRaw === null ? null : parseCharter(charterRaw);
587
+ if (parsed === null || !parsed.ok || parsed.charter.session.speaker_confirmation !== 'required') return null;
588
+
589
+ const interactive = process.stdin.isTTY === true;
590
+ if (isSpeakerAtTerminal(process.env, interactive)) {
591
+ out(`Constitutional act — this will be permanently recorded in the Hansard:`);
592
+ out(` ${summary}`);
593
+ const typed = await askSpeaker(`Type "${act}" to confirm: `);
594
+ if (typed === act) return null;
595
+ err('Not confirmed — nothing was recorded.');
596
+ return EXIT.REFUSED;
597
+ }
598
+
599
+ const sessionDir = resolve(dir);
600
+ let pending;
601
+ try {
602
+ pending = await stagePending(sessionDir, {
603
+ act,
604
+ argv: withDir(argv, sessionDir),
605
+ summary,
606
+ requested_via: requestedVia(process.env, interactive),
607
+ requested_at: nowStamp(),
608
+ });
609
+ } catch (error) {
610
+ err(`Refused: ${error instanceof Error ? error.message : String(error)}. Nothing was staged or recorded.`);
611
+ return EXIT.REFUSED;
612
+ }
613
+ out(`STAGED — ${summary}`);
614
+ out(` pending act: ${pending.id}`);
615
+ out(' Nothing is recorded yet. This is the Speaker\'s decision: they confirm it in');
616
+ out(' their own terminal (not through an AI harness):');
617
+ out(` politik confirm ${pending.id}${dir === '.' ? '' : ` --dir ${dir}`}`);
618
+ out(` To discard it instead: politik reject ${pending.id}${dir === '.' ? '' : ` --dir ${dir}`}`);
619
+ return EXIT.PENDING;
620
+ };
621
+
622
+ /** `politik pending [--dir] [--json]` — staged acts awaiting the Speaker. */
623
+ const cmdPending = async (argv: readonly string[]): Promise<number> => {
624
+ const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' }, json: { type: 'boolean' } } });
625
+ await refreshForRead(values.dir ?? '.');
626
+ const acts = await listPending(resolve(values.dir ?? '.'));
627
+ if (values.json === true) { out(JSON.stringify(acts, null, 2)); return EXIT.OK; }
628
+ if (acts.length === 0) { out('No pending acts.'); return EXIT.OK; }
629
+ out(`PENDING ACTS (${acts.length}) — confirm each with: politik confirm <id>`);
630
+ for (const a of acts) {
631
+ out(` ${a.id} ${a.summary}`);
632
+ out(` requested via ${a.requested_via} at ${a.requested_at}`);
633
+ }
634
+ return EXIT.OK;
635
+ };
636
+
637
+ /** The `--actor` a staged act names. */
638
+ const actorOf = (argv: readonly string[]): string | null => {
639
+ const i = argv.indexOf('--actor');
640
+ return i >= 0 ? argv[i + 1] ?? null : null;
641
+ };
642
+
643
+ /**
644
+ * `politik confirm <id>` — the Speaker executes a staged act.
645
+ *
646
+ * Refuses without a terminal or under a detected harness, shows exactly what will
647
+ * run, and requires the act's id to be typed back. Only then is the act replayed
648
+ * and committed, with provenance naming who requested it and that the Speaker
649
+ * confirmed it.
650
+ */
651
+ const cmdConfirm = async (argv: readonly string[]): Promise<number> => {
652
+ const { values, positionals } = parseArgs({
653
+ args: [...argv], options: { dir: { type: 'string' } }, allowPositionals: true,
654
+ });
655
+ const id = positionals[0];
656
+ if (id === undefined || !isPendingId(id)) { err('confirm: a pending act id is required — see: politik pending'); return EXIT.USAGE; }
657
+
658
+ const harness = detectHarness(process.env);
659
+ if (!isSpeakerAtTerminal(process.env, process.stdin.isTTY === true)) {
660
+ err(`confirm: refused — this must be run by the Speaker at a terminal, not by ${harness ?? 'a script or pipe'}.`);
661
+ err(` Open your own terminal and run: politik confirm ${id}${values.dir === undefined ? '' : ` --dir ${values.dir}`}`);
662
+ return EXIT.REFUSED;
663
+ }
664
+
665
+ const sessionDir = resolve(values.dir ?? '.');
666
+ await refreshForRead(sessionDir);
667
+ const pending = await readPending(sessionDir, id);
668
+ if (pending === null) { err(`confirm: no pending act ${id} in ${sessionDir}`); return EXIT.USAGE; }
669
+
670
+ // ADR-0011 §4: in a shared session only the seat the act names may confirm it.
671
+ if ((await syncConfig(sessionDir)) !== null) {
672
+ const actor = actorOf(pending.argv);
673
+ const me = await operatorHandle(sessionDir);
674
+ if (actor !== null && me !== actor) {
675
+ err(`confirm: refused — ${id} is ${actor}'s act to confirm, and this clone is operated by ${me ?? 'an unknown seat'}.`);
676
+ err(' Set who you are with: politik remote --as <handle>');
677
+ return EXIT.REFUSED;
678
+ }
679
+ }
680
+
681
+ out(`Constitutional act — this will be permanently recorded in the Hansard:`);
682
+ out(` ${pending.summary}`);
683
+ out(` command: politik ${pending.act} ${withDir(pending.argv, sessionDir).join(' ')}`);
684
+ out(` requested via: ${pending.requested_via} at ${pending.requested_at}`);
685
+ const typed = await askSpeaker(`Type ${id} to confirm: `);
686
+ if (typed !== id) { err('Not confirmed — nothing was recorded. The act is still pending.'); return EXIT.REFUSED; }
687
+
688
+ speakerConfirmed = true;
689
+ actProvenance = { via: pending.requested_via, confirmedBy: CONFIRMED_BY_SPEAKER };
690
+ try {
691
+ // Replay against this machine's copy of the session: a pending act shared from
692
+ // another machine names that machine's path (ADR-0011 §4).
693
+ const argv = withDir(pending.argv, sessionDir);
694
+ const code = await withSync(sessionDir, () => run([pending.act, ...argv]), { retry: true });
695
+ if (code === EXIT.OK) {
696
+ await removePending(sessionDir, id);
697
+ out(`CONFIRMED — ${id}`);
698
+ } else {
699
+ err(`confirm: the act did not complete — ${id} is still pending (discard it with: politik reject ${id})`);
700
+ }
701
+ return code;
702
+ } finally {
703
+ speakerConfirmed = false;
704
+ actProvenance = null;
705
+ }
706
+ };
707
+
708
+ /** `politik reject <id>` — discard a staged act. Nothing was recorded, so nothing is. */
709
+ const cmdReject = async (argv: readonly string[]): Promise<number> => {
710
+ const { values, positionals } = parseArgs({
711
+ args: [...argv], options: { dir: { type: 'string' } }, allowPositionals: true,
712
+ });
713
+ const id = positionals[0];
714
+ if (id === undefined || !isPendingId(id)) { err('reject: a pending act id is required — see: politik pending'); return EXIT.USAGE; }
715
+ const sessionDir = resolve(values.dir ?? '.');
716
+ if ((await readPending(sessionDir, id)) === null) { err(`reject: no pending act ${id} in ${sessionDir}`); return EXIT.USAGE; }
717
+ await removePending(sessionDir, id);
718
+ out(`REJECTED — ${id} discarded; nothing was recorded`);
719
+ return EXIT.OK;
720
+ };
721
+
291
722
  /** Probe the host and report whether a session can run here. */
292
723
  const cmdDoctor = async (): Promise<number> => {
293
724
  const diagnosis = await diagnose();
@@ -307,6 +738,20 @@ const cmdDoctor = async (): Promise<number> => {
307
738
  const cmdProtocol = async (argv: readonly string[]): Promise<number> => {
308
739
  const [verb, ...rest] = argv;
309
740
 
741
+ if (verb === 'list') {
742
+ // The shipped protocols, so a harness guiding first-time setup can offer real
743
+ // choices instead of guessing names (ADR-0010).
744
+ const dir = join(dirname(fileURLToPath(import.meta.url)), '..', 'protocols');
745
+ const names = (await readdir(dir)).filter((f) => f.endsWith('.yml')).sort();
746
+ for (const file of names) {
747
+ const src = (await readIfPresent(join(dir, file))) ?? '';
748
+ const blurb = (src.split('\n').find((l) => l.startsWith('#')) ?? '')
749
+ .replace(/^#\s*/, '').split(/(?<=\.)\s/)[0] ?? '';
750
+ out(` ${file.replace(/\.yml$/, '').padEnd(28)} ${blurb}`);
751
+ }
752
+ return EXIT.OK;
753
+ }
754
+
310
755
  if (verb === 'lint') {
311
756
  const path = rest[0];
312
757
  if (path === undefined) {
@@ -426,6 +871,7 @@ const cmdInit = async (argv: readonly string[]): Promise<number> => {
426
871
  guid: { type: 'string' },
427
872
  protocol: { type: 'string' },
428
873
  standalone: { type: 'boolean' },
874
+ remote: { type: 'string' },
429
875
  },
430
876
  });
431
877
 
@@ -440,16 +886,17 @@ const cmdInit = async (argv: readonly string[]): Promise<number> => {
440
886
  return EXIT.USAGE;
441
887
  }
442
888
 
889
+ // `--dir` is the standard flag; `--out` stays an accepted alias here.
890
+ const dir = values.dir ?? values.out ?? '.';
891
+
443
892
  const result = dropWrit({
444
893
  charter_source: source,
445
894
  session_guid: values.guid ?? crypto.randomUUID(),
446
895
  now: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
447
896
  speaker: values.speaker,
448
897
  protocol: values.protocol === undefined ? undefined : { name: values.protocol },
898
+ instruction_files: await readInstructionFiles(dir),
449
899
  });
450
-
451
- // `--dir` is the standard flag; `--out` stays an accepted alias here.
452
- const dir = values.dir ?? values.out ?? '.';
453
900
  await writeFiles(dir, result.files);
454
901
 
455
902
  if (!result.ok) {
@@ -476,6 +923,14 @@ const cmdInit = async (argv: readonly string[]): Promise<number> => {
476
923
  out(` state ${result.state.state}`);
477
924
  out(` files ${result.files.length} written to ${dir}`);
478
925
  out(` git ${repo.reason}${repo.sha ? ` (${repo.sha.slice(0, 7)})` : ''}`);
926
+
927
+ // ADR-0011: share the session from the Writ Drop, with the Speaker as this
928
+ // clone's seat. The session is open either way; a failed publish is reported.
929
+ if (values.remote !== undefined) {
930
+ const shared = await enableSync(dir, values.remote, { handle: values.speaker });
931
+ if (shared.ok) out(` shared ${shared.message}`);
932
+ else { err(` shared NOT shared — ${shared.message}. Retry with: politik remote ${values.remote}`); return EXIT.REFUSED; }
933
+ }
479
934
  return EXIT.OK;
480
935
  };
481
936
 
@@ -516,6 +971,135 @@ const loadSession = async (dir: string) => {
516
971
  return { state, hansard, charter: charter?.ok === true ? charter.charter : null };
517
972
  };
518
973
 
974
+ /** The Charter fingerprint recorded on the WRIT_DROP entry, or null if none. */
975
+ const writDropFingerprint = (hansard: string): string | null => {
976
+ for (const entry of parseEntries(hansard)) {
977
+ if (entry.type === RECORD_TYPES.WRIT_DROP) {
978
+ return entry.fields['Charter SHA256'] ?? null;
979
+ }
980
+ }
981
+ return null;
982
+ };
983
+
984
+ /**
985
+ * Refuse a governance act when an immutable-charter protocol's Charter has been
986
+ * edited since Writ Drop.
987
+ *
988
+ * A protocol whose mechanics forbid mid-session amendment (ADR-0007
989
+ * `immutable_charter` — adversarial-collaboration, elimination-tournament)
990
+ * commits its Charter at Writ Drop and records that text's fingerprint on the
991
+ * WRIT_DROP entry. If CHARTER.md no longer matches, the constitution was
992
+ * amended after the session opened, which this class of protocol exists to
993
+ * forbid. Returns an operator-facing refusal, or null when the act may proceed:
994
+ * a mutable protocol, a legacy session with no recorded fingerprint (cannot be
995
+ * enforced retroactively), or an intact Charter.
996
+ */
997
+ const immutableCharterViolation = async (
998
+ dir: string,
999
+ protocolName: string,
1000
+ ): Promise<string | null> => {
1001
+ const protocol = await sessionProtocol(protocolName);
1002
+ if (protocol === null || allowsCharterAmendment(protocol)) return null;
1003
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
1004
+ const recorded = writDropFingerprint(hansard);
1005
+ if (recorded === null) return null;
1006
+ const current = await readIfPresent(join(dir, 'CHARTER.md'));
1007
+ if (current === null) return null;
1008
+ const now = charterFingerprint(current);
1009
+ if (now === recorded) return null;
1010
+ return [
1011
+ `Refused: the ${protocol.name} protocol runs an immutable Charter — the`,
1012
+ 'Standing Orders are fixed at Writ Drop and cannot be amended mid-session,',
1013
+ 'yet CHARTER.md has changed since',
1014
+ `(${recorded.slice(0, 12)} → ${now.slice(0, 12)}).`,
1015
+ 'Revert CHARTER.md to its Writ Drop text, or prorogue this session and',
1016
+ 'convene a new one under the amended Charter.',
1017
+ ].join(' ');
1018
+ };
1019
+
1020
+ /** The instruction files present in a session directory (ADR-0010 §4). */
1021
+ const readInstructionFiles = async (
1022
+ dir: string,
1023
+ ): Promise<ReadonlyArray<{ readonly path: string; readonly content: string }>> => {
1024
+ const files: Array<{ path: string; content: string }> = [];
1025
+ for (const path of INSTRUCTION_FILES) {
1026
+ const content = await readIfPresent(join(dir, path));
1027
+ if (content !== null) files.push({ path, content });
1028
+ }
1029
+ return files;
1030
+ };
1031
+
1032
+ /**
1033
+ * Refuse governance when the session's instruction files have changed since Writ
1034
+ * Drop (ADR-0010 §4).
1035
+ *
1036
+ * These are the files the Speaker's own harness loads on entering the session. An
1037
+ * agent that rewrites — or plants — one has tried to reprogram the governor's
1038
+ * tool, so this applies under every protocol, not only immutable-charter ones.
1039
+ * Null when the act may proceed: an intact set, or a session sealed before
1040
+ * ADR-0010 (no fingerprint to compare against).
1041
+ */
1042
+ const instructionsViolation = async (dir: string): Promise<string | null> => {
1043
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
1044
+ let recorded: string | null = null;
1045
+ for (const entry of parseEntries(hansard)) {
1046
+ if (entry.type === RECORD_TYPES.WRIT_DROP) { recorded = entry.fields['Instructions SHA256'] ?? null; break; }
1047
+ }
1048
+ if (recorded === null) return null;
1049
+ const files = await readInstructionFiles(dir);
1050
+ const now = instructionsFingerprint(files);
1051
+ if (now === recorded) return null;
1052
+ return [
1053
+ `Refused: this session's instruction files (${INSTRUCTION_FILES.join(', ')}) have changed since`,
1054
+ `Writ Drop (${recorded.slice(0, 12)} → ${now.slice(0, 12)}). These are the instructions the Speaker's`,
1055
+ 'own AI harness loads here; an agent may have tried to rewrite them. Inspect with `git diff`',
1056
+ 'and restore them from the Writ Drop commit before continuing.',
1057
+ ].join(' ');
1058
+ };
1059
+
1060
+ /**
1061
+ * Commands that only read, or that set a session up before Writ Drop. Every other
1062
+ * command is governance and refuses to run while the instruction files are
1063
+ * tampered (ADR-0010 §4); these stay available so the Speaker can see what
1064
+ * happened and repair it.
1065
+ */
1066
+ const UNGUARDED_COMMANDS: ReadonlySet<string | undefined> = new Set([
1067
+ undefined, '-h', '--help', 'help', 'version', '--version',
1068
+ 'new', 'scaffold', 'init', 'doctor', 'protocol', 'validate',
1069
+ 'status', 'hansard', 'ledger', 'integrity', 'pending', 'reject',
1070
+ 'registry', 'cascade', 'standings',
1071
+ 'remote', 'join', 'sync',
1072
+ ]);
1073
+
1074
+ /** Read-only commands that catch up with a shared record first (ADR-0011 §2). */
1075
+ const REFRESH_BEFORE: ReadonlySet<string | undefined> = new Set([
1076
+ 'status', 'hansard', 'ledger', 'integrity', 'standings',
1077
+ ]);
1078
+
1079
+ /** Governance commands not retried on a rejected push: re-running them has effects. */
1080
+ const NOT_RETRIED: ReadonlySet<string | undefined> = new Set(['run']);
1081
+
1082
+ /** The `--dir` a command line targets, defaulting to the working directory. */
1083
+ const dirArg = (argv: readonly string[]): string => {
1084
+ for (let i = 0; i < argv.length; i += 1) {
1085
+ const a = argv[i] ?? '';
1086
+ if (a === '--dir') return argv[i + 1] ?? '.';
1087
+ if (a.startsWith('--dir=')) return a.slice('--dir='.length);
1088
+ }
1089
+ return '.';
1090
+ };
1091
+
1092
+ /**
1093
+ * Guard a governance write: prints the refusal and returns false if an
1094
+ * immutable Charter has been tampered with, true when the act may proceed.
1095
+ */
1096
+ const charterIsIntact = async (dir: string, protocolName: string): Promise<boolean> => {
1097
+ const violation = await immutableCharterViolation(dir, protocolName);
1098
+ if (violation === null) return true;
1099
+ err(violation);
1100
+ return false;
1101
+ };
1102
+
519
1103
  /**
520
1104
  * Atomic file write: land a complete temp file, then rename it over the target.
521
1105
  *
@@ -577,18 +1161,62 @@ const logAct = async (dir: string, actor: string, role: Role, item: string): Pro
577
1161
  * interrupt can never land between telling the operator "success" and the record
578
1162
  * actually existing: every command writes, commits, then reports.
579
1163
  */
580
- const commitAct = (
1164
+ /**
1165
+ * Provenance for the act in flight (ADR-0010 §3). Normally derived from this
1166
+ * process; `politik confirm` overrides it so a staged act records who originally
1167
+ * requested it and that the Speaker confirmed it.
1168
+ */
1169
+ let actProvenance: { readonly via: string; readonly confirmedBy: string | null } | null = null;
1170
+
1171
+ const currentProvenance = (): { readonly via: string; readonly confirmedBy: string | null } =>
1172
+ actProvenance ?? { via: requestedVia(process.env, process.stdin.isTTY === true), confirmedBy: null };
1173
+
1174
+ const commitAct = async (
581
1175
  dir: string,
582
1176
  message: string,
583
1177
  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
- ]);
1178
+ ): Promise<CommitResult> => {
1179
+ const { via, confirmedBy } = currentProvenance();
1180
+ const operator = await operatorIdentity(dir);
1181
+ // ADR-0011 §5: a confirmed act is signed with the confirming person's key when
1182
+ // the Charter requires it, so confirmation cannot be forged without that key.
1183
+ const sign = confirmedBy !== null && (await charterRequiresSignedConfirmations(dir));
1184
+ const paths = ['HANSARD.md', 'STATE.json', 'LEDGER.md', '.politik/LEDGER.md', ...extra];
1185
+ const result = await commitRecord(dir, `${message}\n\n${provenanceTrailers(via, confirmedBy, operator)}`, paths, undefined, { sign });
1186
+ if (sign && !result.committed && result.reason === 'signing failed') {
1187
+ // The act must not survive unsigned (ADR-0011 §5): put every record file back
1188
+ // as it was, so the working tree matches the last signed state, then refuse.
1189
+ for (const path of paths) {
1190
+ if ((await gitx(dir, ['ls-files', '--error-unmatch', '--', path])).code === 0) {
1191
+ await gitx(dir, ['checkout', 'HEAD', '--', path]);
1192
+ } else if (existsSync(join(dir, path))) {
1193
+ await rm(join(dir, path), { force: true });
1194
+ }
1195
+ }
1196
+ throw new Error('the confirmation could not be signed with your git signing key — nothing was recorded');
1197
+ }
1198
+ return result;
1199
+ };
1200
+
1201
+ /**
1202
+ * Commits in this session that record a Speaker confirmation but whose signature
1203
+ * does not verify (`%G?` other than G or U). Verification uses the clone's git
1204
+ * configuration — for SSH signatures, `gpg.ssh.allowedSignersFile`.
1205
+ */
1206
+ const unverifiedConfirmations = async (dir: string): Promise<readonly string[]> => {
1207
+ const log = await gitx(dir, ['log', '--format=%H%x09%G?%x09%(trailers:key=Politik-Confirmed-By,valueonly,separator=%x2C)', '--', '.']);
1208
+ if (log.code !== 0 || log.out === '') return [];
1209
+ return log.out.split('\n')
1210
+ .map((line) => line.split('\t'))
1211
+ .filter(([, status, confirmed]) => (confirmed ?? '').trim() !== '' && status !== 'G' && status !== 'U')
1212
+ .map(([sha]) => sha ?? '');
1213
+ };
1214
+
1215
+ const charterRequiresSignedConfirmations = async (dir: string): Promise<boolean> => {
1216
+ const raw = await readIfPresent(join(dir, 'CHARTER.md'));
1217
+ const parsed = raw === null ? null : parseCharter(raw);
1218
+ return parsed !== null && parsed.ok && parsed.charter.session.signed_confirmations === 'required';
1219
+ };
592
1220
 
593
1221
  /** Print a commit's outcome. Call only AFTER the commit, as part of the report. */
594
1222
  const reportCommit = (result: CommitResult): void => {
@@ -649,6 +1277,7 @@ const cmdDivision = async (argv: readonly string[]): Promise<number> => {
649
1277
  err(`division: ${dir} is not a session repo`);
650
1278
  return EXIT.USAGE;
651
1279
  }
1280
+ if (!(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
652
1281
  if (values.motion === undefined) {
653
1282
  err('division: --motion is required');
654
1283
  return EXIT.USAGE;
@@ -824,9 +1453,13 @@ const cmdAssent = async (argv: readonly string[]): Promise<number> => {
824
1453
  const dir = values.dir ?? '.';
825
1454
  const { state, hansard, charter } = await loadSession(dir);
826
1455
  if (state === null || charter === null) { err(`assent: ${dir} is not a session repo`); return EXIT.USAGE; }
1456
+ if (!(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
827
1457
  if (values.motion === undefined || values.actor === undefined) {
828
1458
  err('assent: --motion and --actor are required'); return EXIT.USAGE;
829
1459
  }
1460
+ const gated = await awaitSpeaker('assent', argv, dir,
1461
+ `Assent to motion "${values.motion}" as ${values.actor} — enact it`);
1462
+ if (gated !== null) return gated;
830
1463
 
831
1464
  try {
832
1465
  const outcome = tallyDivision(hansard, values.motion, charter.session.quorum);
@@ -1103,6 +1736,9 @@ const cmdActor = async (argv: readonly string[]): Promise<number> => {
1103
1736
  err(`actor: ${dir} is not a session repo`);
1104
1737
  return EXIT.USAGE;
1105
1738
  }
1739
+ if (verb !== 'list' && !(await charterIsIntact(dir, charter.protocol))) {
1740
+ return EXIT.REFUSED;
1741
+ }
1106
1742
 
1107
1743
  if (verb === 'list') {
1108
1744
  const protocol = await sessionProtocol(charter.protocol);
@@ -1225,6 +1861,7 @@ const cmdEscalate = async (argv: readonly string[]): Promise<number> => {
1225
1861
  const dir = values.dir ?? '.';
1226
1862
  const { state, charter } = await loadSession(dir);
1227
1863
  if (state === null) { err(`escalate: ${dir} is not a session repo`); return EXIT.USAGE; }
1864
+ if (charter !== null && !(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
1228
1865
  if (values.actor === undefined || values.title === undefined || values.body === undefined) {
1229
1866
  err('escalate: --actor, --title and --body are required');
1230
1867
  return EXIT.USAGE;
@@ -1303,6 +1940,9 @@ const cmdRule = async (argv: readonly string[]): Promise<number> => {
1303
1940
  return EXIT.USAGE;
1304
1941
  }
1305
1942
  if (badRole(values.role)) { err(`rule: "${values.role}" is not a CANON role`); return EXIT.USAGE; }
1943
+ const gated = await awaitSpeaker('rule', argv, dir,
1944
+ `Rule ${(values.outcome ?? 'UPHELD').toUpperCase()} on point of order #${values.seq ?? '1'} as ${values.actor}: "${values.body}"`);
1945
+ if (gated !== null) return gated;
1306
1946
 
1307
1947
  const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
1308
1948
 
@@ -1689,8 +2329,22 @@ const cmdIntegrity = async (argv: readonly string[]): Promise<number> => {
1689
2329
  const { state, hansard } = await loadSession(dir);
1690
2330
  if (state === null) { err(`integrity: ${dir} is not a session repo`); return EXIT.USAGE; }
1691
2331
 
2332
+ // ADR-0010 §4: a tampered instruction set is the most serious finding there is
2333
+ // — it targets the Speaker's own harness — so it leads, and fails the check.
2334
+ const tampered = await instructionsViolation(dir);
2335
+ if (tampered !== null) out(` [HIGH] instructions-tampered — ${tampered}`);
2336
+
2337
+ // ADR-0011 §5: under signed_confirmations, every confirmed act must carry a
2338
+ // signature that verifies. Report each one that does not.
2339
+ const unsigned = (await charterRequiresSignedConfirmations(dir)) ? await unverifiedConfirmations(dir) : [];
2340
+ for (const sha of unsigned) {
2341
+ out(` [HIGH] confirmation-unsigned — ${sha.slice(0, 8)} records a Speaker confirmation without a verifying signature`);
2342
+ }
2343
+ const failedSeal = tampered !== null || unsigned.length > 0;
2344
+
1692
2345
  const findings = reviewIntegrity(hansard);
1693
2346
  if (findings.length === 0) {
2347
+ if (failedSeal) return EXIT.REFUSED;
1694
2348
  out('no bad-faith patterns detected — the record is clean');
1695
2349
  return EXIT.OK;
1696
2350
  }
@@ -1701,7 +2355,7 @@ const cmdIntegrity = async (argv: readonly string[]): Promise<number> => {
1701
2355
  out('');
1702
2356
  out(`${vices.length} vice finding(s), ${virtues.length} virtue(s). Surfaced to the Speaker; no action taken — the Speaker rules.`);
1703
2357
  // 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;
2358
+ return failedSeal || vices.some((f) => f.severity === 'high') ? EXIT.REFUSED : EXIT.OK;
1705
2359
  };
1706
2360
 
1707
2361
  /** `politik hansard` — the record, rendered in the protocol's vocabulary. */
@@ -1725,7 +2379,7 @@ const cmdHansard = async (argv: readonly string[]): Promise<number> => {
1725
2379
  };
1726
2380
 
1727
2381
  const cmdStatus = async (argv: readonly string[]): Promise<number> => {
1728
- const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' } } });
2382
+ const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' }, json: { type: 'boolean' } } });
1729
2383
  const dir = values.dir ?? '.';
1730
2384
 
1731
2385
  const raw = await readIfPresent(join(dir, 'STATE.json'));
@@ -1740,6 +2394,31 @@ const cmdStatus = async (argv: readonly string[]): Promise<number> => {
1740
2394
  return EXIT.REFUSED;
1741
2395
  }
1742
2396
 
2397
+ const pending = await listPending(resolve(dir));
2398
+ const hansardRaw = await readIfPresent(join(dir, 'HANSARD.md'));
2399
+ const entries = hansardRaw === null ? [] : parseEntries(hansardRaw);
2400
+
2401
+ // ADR-0010: a stable machine-readable view, so a harness answering the Speaker
2402
+ // reads fields rather than scraping text.
2403
+ if (values.json === true) {
2404
+ const last = entries.at(-1);
2405
+ out(JSON.stringify({
2406
+ session: state.session_guid,
2407
+ protocol: state.protocol,
2408
+ state: state.state,
2409
+ suspension: state.suspension,
2410
+ quorum: state.quorum,
2411
+ updated_at: state.updated_at,
2412
+ updated_by: state.updated_by,
2413
+ record: {
2414
+ entries: entries.length,
2415
+ last: last === undefined ? null : { type: last.type, actor: last.actor, at: last.at },
2416
+ },
2417
+ pending: pending.map((p) => ({ id: p.id, act: p.act, summary: p.summary })),
2418
+ }, null, 2));
2419
+ return EXIT.OK;
2420
+ }
2421
+
1743
2422
  out(`session ${state.session_guid}`);
1744
2423
  out(`protocol ${state.protocol}`);
1745
2424
  out(`state ${state.state}`);
@@ -1749,13 +2428,14 @@ const cmdStatus = async (argv: readonly string[]): Promise<number> => {
1749
2428
  out(`quorum ${state.quorum.present} of ${state.quorum.required}`);
1750
2429
  out(`updated ${state.updated_at} by ${state.updated_by}`);
1751
2430
 
1752
- const hansard = await readIfPresent(join(dir, 'HANSARD.md'));
1753
- if (hansard !== null) {
1754
- const entries = parseEntries(hansard);
2431
+ if (hansardRaw !== null) {
1755
2432
  out(`record ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'}`);
1756
2433
  const last = entries.at(-1);
1757
2434
  if (last !== undefined) out(`last ${last.type} by ${last.actor} at ${last.at}`);
1758
2435
  }
2436
+ if (pending.length > 0) {
2437
+ out(`pending ${pending.length} act${pending.length === 1 ? '' : 's'} awaiting the Speaker — politik pending`);
2438
+ }
1759
2439
  return EXIT.OK;
1760
2440
  };
1761
2441
 
@@ -1787,6 +2467,9 @@ const cmdProrogue = async (argv: readonly string[]): Promise<number> => {
1787
2467
  err(`prorogue: no readable STATE.json in ${dir}`);
1788
2468
  return EXIT.USAGE;
1789
2469
  }
2470
+ const gated = await awaitSpeaker('prorogue', argv, dir,
2471
+ `Prorogue the session as ${values.actor} (trigger: ${values.trigger ?? 'TRIGGER_SPEAKER'}) — seal the Hansard`);
2472
+ if (gated !== null) return gated;
1790
2473
 
1791
2474
  const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
1792
2475
  const trigger = (values.trigger ?? 'TRIGGER_SPEAKER') as Trigger;
@@ -1850,6 +2533,7 @@ const cmdChallenge = async (argv: readonly string[]): Promise<number> => {
1850
2533
  const dir = values.dir ?? '.';
1851
2534
  const { hansard, charter } = await loadSession(dir);
1852
2535
  if (charter === null) { err(`challenge: ${dir} is not a session repo`); return EXIT.USAGE; }
2536
+ if (!(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
1853
2537
  if (values.actor === undefined || values.against === undefined || values.grounds === undefined) {
1854
2538
  err('challenge: --actor, --against and --grounds are required'); return EXIT.USAGE;
1855
2539
  }
@@ -1893,14 +2577,18 @@ const cmdStandings = async (argv: readonly string[]): Promise<number> => {
1893
2577
  if (table.length === 0) { out('no standings — no actor has taken part yet'); return EXIT.OK; }
1894
2578
 
1895
2579
  const protocol = await sessionProtocol(charter.protocol);
1896
- out(`STANDINGS — by ${by}`);
2580
+ // Buchholz only means something once matches have been played; show it when
2581
+ // any actor has a non-zero strength of schedule.
2582
+ const showBuchholz = by === 'win-loss' && table.some((r) => r.buchholz > 0);
2583
+ out(`STANDINGS — by ${by}${showBuchholz ? ' (ties broken on Buchholz)' : ''}`);
1897
2584
  let rankNo = 0;
1898
2585
  for (const row of table) {
1899
2586
  rankNo += 1;
1900
2587
  const seat = row.seat === null
1901
2588
  ? (row.eliminated ? 'eliminated' : 'out')
1902
2589
  : asRoleTerm(protocol, row.seat);
1903
- out(` ${String(rankNo).padStart(2)}. ${row.actor.padEnd(14)} ${row.wins}–${row.losses} · ${seat}`);
2590
+ const buch = showBuchholz ? ` · B ${row.buchholz}` : '';
2591
+ out(` ${String(rankNo).padStart(2)}. ${row.actor.padEnd(14)} ${row.wins}–${row.losses}${buch} · ${seat}`);
1904
2592
  }
1905
2593
  return EXIT.OK;
1906
2594
  };
@@ -1916,14 +2604,23 @@ const cmdStandings = async (argv: readonly string[]): Promise<number> => {
1916
2604
  const cmdPair = async (argv: readonly string[]): Promise<number> => {
1917
2605
  const { values } = parseArgs({
1918
2606
  args: [...argv],
1919
- options: { dir: { type: 'string' }, format: { type: 'string' }, actor: { type: 'string' }, round: { type: 'string' } },
2607
+ options: {
2608
+ dir: { type: 'string' }, format: { type: 'string' }, actor: { type: 'string' },
2609
+ round: { type: 'string' }, seed: { type: 'string' }, 'best-of': { type: 'string' },
2610
+ },
1920
2611
  });
1921
2612
  const dir = values.dir ?? '.';
1922
2613
  const { hansard, charter } = await loadSession(dir);
1923
2614
  if (charter === null) { err(`pair: ${dir} is not a session repo`); return EXIT.USAGE; }
2615
+ if (!(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
1924
2616
  if (!isPairingFormat(values.format)) {
1925
2617
  err('pair: --format must be swiss | round-robin | single-elim'); return EXIT.USAGE;
1926
2618
  }
2619
+ const bestOf = values['best-of'] === undefined ? 1 : Number(values['best-of']);
2620
+ if (!Number.isInteger(bestOf) || bestOf < 1 || bestOf % 2 === 0) {
2621
+ err('pair: --best-of must be a positive odd integer (1, 3, 5, …) — no draws'); return EXIT.USAGE;
2622
+ }
2623
+ const seed = (values.seed ?? '').split(',').map((s) => s.trim()).filter((s) => s.length > 0);
1927
2624
 
1928
2625
  const contestants = seats(hansard).map((s) => s.actor);
1929
2626
  if (contestants.length < 2) { err('pair: fewer than two contestants are seated'); return EXIT.REFUSED; }
@@ -1932,7 +2629,7 @@ const cmdPair = async (argv: readonly string[]): Promise<number> => {
1932
2629
  ? Number(values.round)
1933
2630
  : Math.max(0, ...played.map((m) => m.round)) + 1;
1934
2631
 
1935
- const pairings = pairRound(contestants, standings(hansard), values.format, round, played);
2632
+ const pairings = pairRound(contestants, standings(hansard), values.format, round, played, seed);
1936
2633
  if (pairings.length === 0) {
1937
2634
  out(`no pairings for round ${round} — the ${values.format} field is decided`);
1938
2635
  return EXIT.OK;
@@ -1940,7 +2637,7 @@ const cmdPair = async (argv: readonly string[]): Promise<number> => {
1940
2637
 
1941
2638
  let doc = hansard;
1942
2639
  for (const pairing of pairings) {
1943
- const created = matchCreatedEntry(pairing, round, nowStamp());
2640
+ const created = matchCreatedEntry(pairing, round, nowStamp(), bestOf);
1944
2641
  doc = appendEntry(doc, created);
1945
2642
  if (pairing.b === null) {
1946
2643
  // A bye advances unopposed — record it decided so standings count it.
@@ -1951,9 +2648,13 @@ const cmdPair = async (argv: readonly string[]): Promise<number> => {
1951
2648
  await writeHansard(dir, doc);
1952
2649
  await logAct(dir, values.actor ?? 'RECORD', 'OPERATOR' as never, `PAIRED round ${round} (${values.format})`);
1953
2650
  const rec = await commitAct(dir, `MATCH_PAIRING — round ${round} (${values.format})`);
1954
- out(`ROUND ${round} — ${values.format}`);
2651
+ const suffix = bestOf > 1 ? `, best of ${bestOf}` : '';
2652
+ const seededNote = seed.length > 0 && played.length === 0 ? ', seeded' : '';
2653
+ out(`ROUND ${round} — ${values.format}${suffix}${seededNote}`);
1955
2654
  for (const pairing of pairings) out(` ${pairing.a} vs ${pairing.b ?? 'BYE'}`);
1956
- out(' report each result: politik match report --match <id> --winner <contestant>');
2655
+ out(bestOf > 1
2656
+ ? ` report each game: politik match report --match <id> --winner <contestant> (first to ${Math.floor(bestOf / 2) + 1})`
2657
+ : ' report each result: politik match report --match <id> --winner <contestant>');
1957
2658
  reportCommit(rec);
1958
2659
  return EXIT.OK;
1959
2660
  };
@@ -1968,13 +2669,17 @@ const cmdMatch = async (argv: readonly string[]): Promise<number> => {
1968
2669
  const dir = values.dir ?? '.';
1969
2670
  const { hansard, charter } = await loadSession(dir);
1970
2671
  if (charter === null) { err(`match: ${dir} is not a session repo`); return EXIT.USAGE; }
2672
+ if (verb !== 'list' && !(await charterIsIntact(dir, charter.protocol))) {
2673
+ return EXIT.REFUSED;
2674
+ }
1971
2675
 
1972
2676
  if (verb === 'list') {
1973
2677
  const all = matches(hansard);
1974
2678
  if (all.length === 0) { out('no matches yet — pair a round first'); return EXIT.OK; }
1975
2679
  for (const m of all) {
1976
2680
  const status = m.winner === null ? 'open' : `${m.winner} won`;
1977
- out(` [${status.padEnd(12)}] ${m.id} · ${m.a} vs ${m.b ?? 'bye'}`);
2681
+ const tally = m.best_of > 1 ? ` (best of ${m.best_of}: ${m.games.a}–${m.games.b})` : '';
2682
+ out(` [${status.padEnd(12)}] ${m.id} · ${m.a} vs ${m.b ?? 'bye'}${tally}`);
1978
2683
  }
1979
2684
  return EXIT.OK;
1980
2685
  }
@@ -1986,9 +2691,16 @@ const cmdMatch = async (argv: readonly string[]): Promise<number> => {
1986
2691
  try {
1987
2692
  const result = reportMatch(values.match, values.winner, nowStamp(), values.actor ?? 'RECORD', hansard);
1988
2693
  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`);
2694
+ const kind = result.decided ? 'MATCH_DECIDED' : 'MATCH_GAME';
2695
+ await logAct(dir, values.actor ?? 'RECORD', 'AUTHORITY' as never, `${kind} ${values.match} -> ${values.winner}`);
2696
+ const rec = await commitAct(dir, `${kind} — ${values.match}: ${values.winner}`);
2697
+ if (result.decided) {
2698
+ const score = result.games.a + result.games.b > 0
2699
+ ? ` (${result.games.a}–${result.games.b})` : '';
2700
+ out(`MATCH ${values.match} — ${values.winner} won${score}`);
2701
+ } else {
2702
+ out(`GAME to ${values.winner} — ${values.match} stands at ${result.games.a}–${result.games.b}`);
2703
+ }
1992
2704
  reportCommit(rec);
1993
2705
  return EXIT.OK;
1994
2706
  } catch (error) {
@@ -2097,6 +2809,23 @@ const cmdCascade = async (argv: readonly string[]): Promise<number> => {
2097
2809
  export const run = async (argv: readonly string[]): Promise<number> => {
2098
2810
  const [command, ...rest] = argv;
2099
2811
 
2812
+ if (!UNGUARDED_COMMANDS.has(command)) {
2813
+ const violation = await instructionsViolation(dirArg(rest));
2814
+ if (violation !== null) { err(violation); return EXIT.REFUSED; }
2815
+ }
2816
+
2817
+ // ADR-0011: governance on a shared session syncs around the act. `confirm`
2818
+ // syncs around its own replay (after the Speaker has typed the id), so it is
2819
+ // not wrapped here.
2820
+ if (REFRESH_BEFORE.has(command)) await refreshForRead(dirArg(rest));
2821
+ if (!UNGUARDED_COMMANDS.has(command) && command !== 'confirm') {
2822
+ return withSync(dirArg(rest), () => dispatch(command, rest), { retry: !NOT_RETRIED.has(command) });
2823
+ }
2824
+ return dispatch(command, rest);
2825
+ };
2826
+
2827
+ const dispatch = async (command: string | undefined, rest: readonly string[]): Promise<number> => {
2828
+
2100
2829
  switch (command) {
2101
2830
  case undefined:
2102
2831
  case '-h':
@@ -2108,6 +2837,20 @@ export const run = async (argv: readonly string[]): Promise<number> => {
2108
2837
  case '--version':
2109
2838
  out(VERSION);
2110
2839
  return EXIT.OK;
2840
+ case 'new':
2841
+ return cmdNew(rest);
2842
+ case 'pending':
2843
+ return cmdPending(rest);
2844
+ case 'confirm':
2845
+ return cmdConfirm(rest);
2846
+ case 'reject':
2847
+ return cmdReject(rest);
2848
+ case 'remote':
2849
+ return cmdRemote(rest);
2850
+ case 'join':
2851
+ return cmdJoin(rest);
2852
+ case 'sync':
2853
+ return cmdSync(rest);
2111
2854
  case 'scaffold':
2112
2855
  return cmdScaffold(rest);
2113
2856
  case 'doctor':