@cordfuse/politik 0.3.0 → 0.3.1

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
@@ -15,11 +15,11 @@ 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, 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 { scaffoldTemplates } from './templates/parliamentary.ts';
23
23
  import { generateProtocol, lintSource } from './protocol-sdk.ts';
24
24
  import { diagnose } from './doctor.ts';
25
25
  import { runTurn } from './runner.ts';
@@ -53,11 +53,12 @@ import {
53
53
  isExitPolicy, isResolution, recordOutcome, suspendForDeadlock, tallyDivision, type Vote,
54
54
  } from './division.ts';
55
55
  import {
56
- PROTOCOL_MODES, parseProtocol, roleTerm, term, type Protocol, type ProtocolMode,
56
+ PROTOCOL_MODES, allowsCharterAmendment, parseProtocol, roleTerm, term,
57
+ type Protocol, type ProtocolMode,
57
58
  } from './protocol.ts';
58
59
  import { reviewIntegrity } from './integrity.ts';
59
60
  import { checkTermination, isTerminationPolicy, lastStanding, prorogue, type Trigger } from './prorogation.ts';
60
- import { appendEntry, parseEntries } from './hansard.ts';
61
+ import { RECORD_TYPES, appendEntry, parseEntries } from './hansard.ts';
61
62
  import type { FileWrite } from './scm.ts';
62
63
 
63
64
  /**
@@ -270,7 +271,7 @@ const cmdScaffold = async (argv: readonly string[]): Promise<number> => {
270
271
  // the lineage resolves from within the session's own directory. init detects
271
272
  // the enclosing repo and commits the writ drop there rather than nesting a repo.
272
273
  const inherits_from = values.parent === undefined ? null : (relative(dir, values.parent) || '.');
273
- const files = parliamentaryTemplates({
274
+ const files = scaffoldTemplates(manifest.protocol, {
274
275
  protocol,
275
276
  ...(inherits_from === null ? {} : { inherits_from }),
276
277
  ...(quorum === undefined ? {} : { quorum }),
@@ -516,6 +517,63 @@ const loadSession = async (dir: string) => {
516
517
  return { state, hansard, charter: charter?.ok === true ? charter.charter : null };
517
518
  };
518
519
 
520
+ /** The Charter fingerprint recorded on the WRIT_DROP entry, or null if none. */
521
+ const writDropFingerprint = (hansard: string): string | null => {
522
+ for (const entry of parseEntries(hansard)) {
523
+ if (entry.type === RECORD_TYPES.WRIT_DROP) {
524
+ return entry.fields['Charter SHA256'] ?? null;
525
+ }
526
+ }
527
+ return null;
528
+ };
529
+
530
+ /**
531
+ * Refuse a governance act when an immutable-charter protocol's Charter has been
532
+ * edited since Writ Drop.
533
+ *
534
+ * A protocol whose mechanics forbid mid-session amendment (ADR-0007
535
+ * `immutable_charter` — adversarial-collaboration, elimination-tournament)
536
+ * commits its Charter at Writ Drop and records that text's fingerprint on the
537
+ * WRIT_DROP entry. If CHARTER.md no longer matches, the constitution was
538
+ * amended after the session opened, which this class of protocol exists to
539
+ * forbid. Returns an operator-facing refusal, or null when the act may proceed:
540
+ * a mutable protocol, a legacy session with no recorded fingerprint (cannot be
541
+ * enforced retroactively), or an intact Charter.
542
+ */
543
+ const immutableCharterViolation = async (
544
+ dir: string,
545
+ protocolName: string,
546
+ ): Promise<string | null> => {
547
+ const protocol = await sessionProtocol(protocolName);
548
+ if (protocol === null || allowsCharterAmendment(protocol)) return null;
549
+ const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
550
+ const recorded = writDropFingerprint(hansard);
551
+ if (recorded === null) return null;
552
+ const current = await readIfPresent(join(dir, 'CHARTER.md'));
553
+ if (current === null) return null;
554
+ const now = charterFingerprint(current);
555
+ if (now === recorded) return null;
556
+ return [
557
+ `Refused: the ${protocol.name} protocol runs an immutable Charter — the`,
558
+ 'Standing Orders are fixed at Writ Drop and cannot be amended mid-session,',
559
+ 'yet CHARTER.md has changed since',
560
+ `(${recorded.slice(0, 12)} → ${now.slice(0, 12)}).`,
561
+ 'Revert CHARTER.md to its Writ Drop text, or prorogue this session and',
562
+ 'convene a new one under the amended Charter.',
563
+ ].join(' ');
564
+ };
565
+
566
+ /**
567
+ * Guard a governance write: prints the refusal and returns false if an
568
+ * immutable Charter has been tampered with, true when the act may proceed.
569
+ */
570
+ const charterIsIntact = async (dir: string, protocolName: string): Promise<boolean> => {
571
+ const violation = await immutableCharterViolation(dir, protocolName);
572
+ if (violation === null) return true;
573
+ err(violation);
574
+ return false;
575
+ };
576
+
519
577
  /**
520
578
  * Atomic file write: land a complete temp file, then rename it over the target.
521
579
  *
@@ -649,6 +707,7 @@ const cmdDivision = async (argv: readonly string[]): Promise<number> => {
649
707
  err(`division: ${dir} is not a session repo`);
650
708
  return EXIT.USAGE;
651
709
  }
710
+ if (!(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
652
711
  if (values.motion === undefined) {
653
712
  err('division: --motion is required');
654
713
  return EXIT.USAGE;
@@ -824,6 +883,7 @@ const cmdAssent = async (argv: readonly string[]): Promise<number> => {
824
883
  const dir = values.dir ?? '.';
825
884
  const { state, hansard, charter } = await loadSession(dir);
826
885
  if (state === null || charter === null) { err(`assent: ${dir} is not a session repo`); return EXIT.USAGE; }
886
+ if (!(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
827
887
  if (values.motion === undefined || values.actor === undefined) {
828
888
  err('assent: --motion and --actor are required'); return EXIT.USAGE;
829
889
  }
@@ -1103,6 +1163,9 @@ const cmdActor = async (argv: readonly string[]): Promise<number> => {
1103
1163
  err(`actor: ${dir} is not a session repo`);
1104
1164
  return EXIT.USAGE;
1105
1165
  }
1166
+ if (verb !== 'list' && !(await charterIsIntact(dir, charter.protocol))) {
1167
+ return EXIT.REFUSED;
1168
+ }
1106
1169
 
1107
1170
  if (verb === 'list') {
1108
1171
  const protocol = await sessionProtocol(charter.protocol);
@@ -1225,6 +1288,7 @@ const cmdEscalate = async (argv: readonly string[]): Promise<number> => {
1225
1288
  const dir = values.dir ?? '.';
1226
1289
  const { state, charter } = await loadSession(dir);
1227
1290
  if (state === null) { err(`escalate: ${dir} is not a session repo`); return EXIT.USAGE; }
1291
+ if (charter !== null && !(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
1228
1292
  if (values.actor === undefined || values.title === undefined || values.body === undefined) {
1229
1293
  err('escalate: --actor, --title and --body are required');
1230
1294
  return EXIT.USAGE;
@@ -1850,6 +1914,7 @@ const cmdChallenge = async (argv: readonly string[]): Promise<number> => {
1850
1914
  const dir = values.dir ?? '.';
1851
1915
  const { hansard, charter } = await loadSession(dir);
1852
1916
  if (charter === null) { err(`challenge: ${dir} is not a session repo`); return EXIT.USAGE; }
1917
+ if (!(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
1853
1918
  if (values.actor === undefined || values.against === undefined || values.grounds === undefined) {
1854
1919
  err('challenge: --actor, --against and --grounds are required'); return EXIT.USAGE;
1855
1920
  }
@@ -1893,14 +1958,18 @@ const cmdStandings = async (argv: readonly string[]): Promise<number> => {
1893
1958
  if (table.length === 0) { out('no standings — no actor has taken part yet'); return EXIT.OK; }
1894
1959
 
1895
1960
  const protocol = await sessionProtocol(charter.protocol);
1896
- out(`STANDINGS — by ${by}`);
1961
+ // Buchholz only means something once matches have been played; show it when
1962
+ // any actor has a non-zero strength of schedule.
1963
+ const showBuchholz = by === 'win-loss' && table.some((r) => r.buchholz > 0);
1964
+ out(`STANDINGS — by ${by}${showBuchholz ? ' (ties broken on Buchholz)' : ''}`);
1897
1965
  let rankNo = 0;
1898
1966
  for (const row of table) {
1899
1967
  rankNo += 1;
1900
1968
  const seat = row.seat === null
1901
1969
  ? (row.eliminated ? 'eliminated' : 'out')
1902
1970
  : asRoleTerm(protocol, row.seat);
1903
- out(` ${String(rankNo).padStart(2)}. ${row.actor.padEnd(14)} ${row.wins}–${row.losses} · ${seat}`);
1971
+ const buch = showBuchholz ? ` · B ${row.buchholz}` : '';
1972
+ out(` ${String(rankNo).padStart(2)}. ${row.actor.padEnd(14)} ${row.wins}–${row.losses}${buch} · ${seat}`);
1904
1973
  }
1905
1974
  return EXIT.OK;
1906
1975
  };
@@ -1916,14 +1985,23 @@ const cmdStandings = async (argv: readonly string[]): Promise<number> => {
1916
1985
  const cmdPair = async (argv: readonly string[]): Promise<number> => {
1917
1986
  const { values } = parseArgs({
1918
1987
  args: [...argv],
1919
- options: { dir: { type: 'string' }, format: { type: 'string' }, actor: { type: 'string' }, round: { type: 'string' } },
1988
+ options: {
1989
+ dir: { type: 'string' }, format: { type: 'string' }, actor: { type: 'string' },
1990
+ round: { type: 'string' }, seed: { type: 'string' }, 'best-of': { type: 'string' },
1991
+ },
1920
1992
  });
1921
1993
  const dir = values.dir ?? '.';
1922
1994
  const { hansard, charter } = await loadSession(dir);
1923
1995
  if (charter === null) { err(`pair: ${dir} is not a session repo`); return EXIT.USAGE; }
1996
+ if (!(await charterIsIntact(dir, charter.protocol))) return EXIT.REFUSED;
1924
1997
  if (!isPairingFormat(values.format)) {
1925
1998
  err('pair: --format must be swiss | round-robin | single-elim'); return EXIT.USAGE;
1926
1999
  }
2000
+ const bestOf = values['best-of'] === undefined ? 1 : Number(values['best-of']);
2001
+ if (!Number.isInteger(bestOf) || bestOf < 1 || bestOf % 2 === 0) {
2002
+ err('pair: --best-of must be a positive odd integer (1, 3, 5, …) — no draws'); return EXIT.USAGE;
2003
+ }
2004
+ const seed = (values.seed ?? '').split(',').map((s) => s.trim()).filter((s) => s.length > 0);
1927
2005
 
1928
2006
  const contestants = seats(hansard).map((s) => s.actor);
1929
2007
  if (contestants.length < 2) { err('pair: fewer than two contestants are seated'); return EXIT.REFUSED; }
@@ -1932,7 +2010,7 @@ const cmdPair = async (argv: readonly string[]): Promise<number> => {
1932
2010
  ? Number(values.round)
1933
2011
  : Math.max(0, ...played.map((m) => m.round)) + 1;
1934
2012
 
1935
- const pairings = pairRound(contestants, standings(hansard), values.format, round, played);
2013
+ const pairings = pairRound(contestants, standings(hansard), values.format, round, played, seed);
1936
2014
  if (pairings.length === 0) {
1937
2015
  out(`no pairings for round ${round} — the ${values.format} field is decided`);
1938
2016
  return EXIT.OK;
@@ -1940,7 +2018,7 @@ const cmdPair = async (argv: readonly string[]): Promise<number> => {
1940
2018
 
1941
2019
  let doc = hansard;
1942
2020
  for (const pairing of pairings) {
1943
- const created = matchCreatedEntry(pairing, round, nowStamp());
2021
+ const created = matchCreatedEntry(pairing, round, nowStamp(), bestOf);
1944
2022
  doc = appendEntry(doc, created);
1945
2023
  if (pairing.b === null) {
1946
2024
  // A bye advances unopposed — record it decided so standings count it.
@@ -1951,9 +2029,13 @@ const cmdPair = async (argv: readonly string[]): Promise<number> => {
1951
2029
  await writeHansard(dir, doc);
1952
2030
  await logAct(dir, values.actor ?? 'RECORD', 'OPERATOR' as never, `PAIRED round ${round} (${values.format})`);
1953
2031
  const rec = await commitAct(dir, `MATCH_PAIRING — round ${round} (${values.format})`);
1954
- out(`ROUND ${round} — ${values.format}`);
2032
+ const suffix = bestOf > 1 ? `, best of ${bestOf}` : '';
2033
+ const seededNote = seed.length > 0 && played.length === 0 ? ', seeded' : '';
2034
+ out(`ROUND ${round} — ${values.format}${suffix}${seededNote}`);
1955
2035
  for (const pairing of pairings) out(` ${pairing.a} vs ${pairing.b ?? 'BYE'}`);
1956
- out(' report each result: politik match report --match <id> --winner <contestant>');
2036
+ out(bestOf > 1
2037
+ ? ` report each game: politik match report --match <id> --winner <contestant> (first to ${Math.floor(bestOf / 2) + 1})`
2038
+ : ' report each result: politik match report --match <id> --winner <contestant>');
1957
2039
  reportCommit(rec);
1958
2040
  return EXIT.OK;
1959
2041
  };
@@ -1968,13 +2050,17 @@ const cmdMatch = async (argv: readonly string[]): Promise<number> => {
1968
2050
  const dir = values.dir ?? '.';
1969
2051
  const { hansard, charter } = await loadSession(dir);
1970
2052
  if (charter === null) { err(`match: ${dir} is not a session repo`); return EXIT.USAGE; }
2053
+ if (verb !== 'list' && !(await charterIsIntact(dir, charter.protocol))) {
2054
+ return EXIT.REFUSED;
2055
+ }
1971
2056
 
1972
2057
  if (verb === 'list') {
1973
2058
  const all = matches(hansard);
1974
2059
  if (all.length === 0) { out('no matches yet — pair a round first'); return EXIT.OK; }
1975
2060
  for (const m of all) {
1976
2061
  const status = m.winner === null ? 'open' : `${m.winner} won`;
1977
- out(` [${status.padEnd(12)}] ${m.id} · ${m.a} vs ${m.b ?? 'bye'}`);
2062
+ const tally = m.best_of > 1 ? ` (best of ${m.best_of}: ${m.games.a}–${m.games.b})` : '';
2063
+ out(` [${status.padEnd(12)}] ${m.id} · ${m.a} vs ${m.b ?? 'bye'}${tally}`);
1978
2064
  }
1979
2065
  return EXIT.OK;
1980
2066
  }
@@ -1986,9 +2072,16 @@ const cmdMatch = async (argv: readonly string[]): Promise<number> => {
1986
2072
  try {
1987
2073
  const result = reportMatch(values.match, values.winner, nowStamp(), values.actor ?? 'RECORD', hansard);
1988
2074
  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`);
2075
+ const kind = result.decided ? 'MATCH_DECIDED' : 'MATCH_GAME';
2076
+ await logAct(dir, values.actor ?? 'RECORD', 'AUTHORITY' as never, `${kind} ${values.match} -> ${values.winner}`);
2077
+ const rec = await commitAct(dir, `${kind} — ${values.match}: ${values.winner}`);
2078
+ if (result.decided) {
2079
+ const score = result.games.a + result.games.b > 0
2080
+ ? ` (${result.games.a}–${result.games.b})` : '';
2081
+ out(`MATCH ${values.match} — ${values.winner} won${score}`);
2082
+ } else {
2083
+ out(`GAME to ${values.winner} — ${values.match} stands at ${result.games.a}–${result.games.b}`);
2084
+ }
1992
2085
  reportCommit(rec);
1993
2086
  return EXIT.OK;
1994
2087
  } catch (error) {
package/src/init.ts CHANGED
@@ -17,6 +17,7 @@
17
17
  import {
18
18
  validateCharter,
19
19
  parseCharter,
20
+ charterFingerprint,
20
21
  type Charter,
21
22
  type CharterIssue,
22
23
  type ProtocolContext,
@@ -94,6 +95,7 @@ const hansard = (input: WritDropInput, guid: string): string =>
94
95
  at: input.now,
95
96
  actor: input.speaker,
96
97
  role: 'AUTHORITY',
98
+ fields: { 'Charter SHA256': charterFingerprint(input.charter_source) },
97
99
  body: `Writ dropped. Session ${guid} convened under the attached Charter.`,
98
100
  });
99
101
 
package/src/standings.ts CHANGED
@@ -30,6 +30,12 @@ export interface Standing {
30
30
  readonly eliminated: boolean;
31
31
  /** When the actor was removed, for survival ranking. Null if still standing. */
32
32
  readonly eliminated_at: string | null;
33
+ /**
34
+ * Buchholz score — the sum of this actor's match opponents' win totals, i.e.
35
+ * strength of schedule. Zero for a session with no MATCHes. Breaks win-loss
36
+ * ties: on equal record, whoever beat the tougher field ranks higher.
37
+ */
38
+ readonly buchholz: number;
33
39
  }
34
40
 
35
41
  export type RankBy = 'win-loss' | 'survival';
@@ -49,10 +55,15 @@ export const standings = (hansard: string, by: RankBy = 'win-loss'): readonly St
49
55
  const losses = new Map<string, number>();
50
56
  const eliminatedAt = new Map<string, string>();
51
57
  const participants = new Set<string>();
58
+ // Match opponents, for Buchholz (strength of schedule).
59
+ const opponents = new Map<string, string[]>();
52
60
 
53
61
  const bump = (map: Map<string, number>, key: string): void => {
54
62
  map.set(key, (map.get(key) ?? 0) + 1);
55
63
  };
64
+ const faced = (x: string, y: string): void => {
65
+ opponents.set(x, [...(opponents.get(x) ?? []), y]);
66
+ };
56
67
 
57
68
  for (const entry of entries) {
58
69
  const motion = entry.fields['Motion'];
@@ -80,6 +91,10 @@ export const standings = (hansard: string, by: RankBy = 'win-loss'): readonly St
80
91
  const loser = entry.fields['Loser'];
81
92
  if (winner !== undefined) { bump(wins, winner); participants.add(winner); }
82
93
  if (loser !== undefined && loser !== 'bye') { bump(losses, loser); participants.add(loser); }
94
+ if (winner !== undefined && loser !== undefined && loser !== 'bye') {
95
+ faced(winner, loser);
96
+ faced(loser, winner);
97
+ }
83
98
  break;
84
99
  }
85
100
  case 'ACTOR_HIRED':
@@ -117,6 +132,8 @@ export const standings = (hansard: string, by: RankBy = 'win-loss'): readonly St
117
132
  // reinstated actor is back in, not eliminated).
118
133
  eliminated: eliminatedAt.has(actor) && !seated.has(actor),
119
134
  eliminated_at: seated.has(actor) ? null : (eliminatedAt.get(actor) ?? null),
135
+ // Strength of schedule: the total wins of everyone this actor faced.
136
+ buchholz: (opponents.get(actor) ?? []).reduce((sum, opp) => sum + (wins.get(opp) ?? 0), 0),
120
137
  }));
121
138
 
122
139
  return rank(rows, by);
@@ -136,8 +153,11 @@ const rank = (rows: readonly Standing[], by: RankBy): readonly Standing[] => {
136
153
  return (b.wins - a.wins) || a.actor.localeCompare(b.actor);
137
154
  });
138
155
  } else {
156
+ // Win-loss, then Buchholz (tougher schedule ranks higher on an equal
157
+ // record), then name for a stable order.
139
158
  sorted.sort((a, b) =>
140
- (b.wins - a.wins) || (a.losses - b.losses) || a.actor.localeCompare(b.actor));
159
+ (b.wins - a.wins) || (a.losses - b.losses)
160
+ || (b.buchholz - a.buchholz) || a.actor.localeCompare(b.actor));
141
161
  }
142
162
  return sorted;
143
163
  };
@@ -1,18 +1,22 @@
1
1
  /**
2
- * Parliamentary protocol templates.
2
+ * Scaffold templates.
3
3
  *
4
- * Charter, role definitions, Standing Orders and the GitHub label taxonomy for
5
- * protocol #1. These are what a Speaker starts from — editable prose, not
6
- * engine configuration.
4
+ * Charter, role definitions, Order Paper and the GitHub label taxonomy a Speaker
5
+ * starts from — editable prose, not engine configuration. Parliamentary (protocol
6
+ * #1) keeps its hand-written constituency prose; every other protocol renders its
7
+ * role docs and Order Paper in its *own* vocabulary via `roleTemplates(protocol)`
8
+ * and `orderPaperTemplate(protocol)`, so `scaffold --protocol monarchy` produces a
9
+ * monarchy session, not a parliamentary one wearing a monarchy Charter.
7
10
  *
8
- * Role files describe a *constituency* in Parliamentary vocabulary while naming
9
- * the CANON role they map to. The engine reads the CANON role; the human reads
10
- * the title. That separation is the whole point of the protocol layer.
11
+ * Role files name the CANON role they map to: the engine reads the CANON role;
12
+ * the human reads the title. That separation is the whole point of the protocol
13
+ * layer.
11
14
  *
12
15
  * Attribution: Steve Krisjanovs, Cordfuse
13
16
  */
14
17
 
15
- import type { Role } from '../canon.ts';
18
+ import { ROLE_PRECEDENCE, type Role } from '../canon.ts';
19
+ import { roleTerm, term, type Protocol } from '../protocol.ts';
16
20
  import type { FileWrite } from '../scm.ts';
17
21
 
18
22
  /* -------------------------------------------------------------------------- */
@@ -267,7 +271,7 @@ outside it.
267
271
  ];
268
272
 
269
273
  /** Role definition files for a Parliamentary session repo. */
270
- export const roleTemplates = (): readonly FileWrite[] =>
274
+ const parliamentaryRoleTemplates = (): readonly FileWrite[] =>
271
275
  ROLE_TEMPLATES.map((role) => ({
272
276
  path: `roles/${role.file}`,
273
277
  content: `# ${role.title}
@@ -279,6 +283,61 @@ ${role.body}
279
283
  `,
280
284
  }));
281
285
 
286
+ /**
287
+ * Generic CANON-role descriptions — the protocol-independent truth of what each
288
+ * role *is*. A protocol supplies only the vocabulary (the title); the powers of
289
+ * an AUTHORITY or an OPERATOR hold across every protocol, so these are written
290
+ * once and rendered under each protocol's term.
291
+ */
292
+ const CANON_ROLE_BODY: Readonly<Record<Role, string>> = {
293
+ AUTHORITY: `The constitutional authority of this session — **always human**. The Charter cannot declare a machine here, and one that does fails Writ Drop validation. Present, not operational: defines the Standing Orders, rules on escalations, grants Assent to carried Motions, and prorogues the session. Does not do the substantive work.
294
+
295
+ **Verbs:** all, including ASSENT, VETO, PROMOTE, DEMOTE, HIRE, FIRE, EXPEL, SUSPEND, DISSOLVE.
296
+
297
+ **Why human.** A corrupt authority requires accountability only a person can bear; a machine that captures a session cannot be held responsible for it.`,
298
+ DELEGATE: `A pre-delegated proxy for the authority — human or machine. Acts with the authority the Charter grants, and only there. May formally challenge an AUTHORITY action (\`politik challenge\`): the dissent is recorded and attributable, though the authority still prevails — which is what makes bad faith visible.
299
+
300
+ **Verbs:** as granted by the Charter; typically all but DISSOLVE.`,
301
+ OPERATOR: `Elevated trust, broad portfolio — human or machine. Does the substantive work of the session: tables business, carries out the Order Paper, and votes in Divisions. Raise a Point of Order rather than act beyond your verbs.
302
+
303
+ **Verbs:** READ, WRITE, VOTE, ESCALATE, SPAWN. Not ASSENT — the Division decides, the authority enacts.`,
304
+ MEMBER: `The base participant — human or machine. Votes and speaks; does not table business unless the Charter grants it. Raise a Point of Order rather than act beyond your verbs.
305
+
306
+ **Verbs:** READ, VOTE, ESCALATE.`,
307
+ OBSERVER: `Present but non-voting — human or machine. Reads the record and follows the proceeding; does not vote or table business.
308
+
309
+ **Verbs:** READ.`,
310
+ };
311
+
312
+ /** A filesystem-safe slug from a protocol's role term (e.g. "The Crown" -> "the-crown"). */
313
+ const slug = (title: string): string =>
314
+ title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'role';
315
+
316
+ /**
317
+ * Role definition files in the protocol's own vocabulary. Parliamentary keeps its
318
+ * hand-written constituency prose; every other protocol gets one role doc per
319
+ * CANON role it names, titled with the protocol's term and carrying the generic
320
+ * CANON body — so `scaffold --protocol monarchy` no longer drops Speaker/Minister.
321
+ */
322
+ export const roleTemplates = (protocol: Protocol): readonly FileWrite[] => {
323
+ if (protocol.name === 'parliamentary') return parliamentaryRoleTemplates();
324
+ return ROLE_PRECEDENCE
325
+ .filter((role) => protocol.roles[role] !== undefined)
326
+ .map((role) => {
327
+ const title = roleTerm(protocol, role);
328
+ return {
329
+ path: `roles/${slug(title)}.md`,
330
+ content: `# ${title}
331
+
332
+ **CANON role:** \`${role}\`
333
+ **Protocol:** ${protocol.name}
334
+
335
+ ${CANON_ROLE_BODY[role]}
336
+ `,
337
+ };
338
+ });
339
+ };
340
+
282
341
  /* -------------------------------------------------------------------------- */
283
342
  /* Label taxonomy */
284
343
  /* -------------------------------------------------------------------------- */
@@ -318,42 +377,111 @@ export const LABEL_TAXONOMY: readonly LabelSpec[] = Object.freeze([
318
377
  * A Milestone is a sitting: the business intended for one continuous stretch of
319
378
  * the proceeding. Closing the Milestone is part of prorogation.
320
379
  */
321
- export const orderPaperTemplate = (): string => `# ORDER PAPER
322
-
323
- The business before this Parliament, in the order it is to be taken.
324
-
325
- Mirrored as a GitHub Project board. Columns map to Motion state:
326
-
327
- | Column | Meaning | CANON |
380
+ export const orderPaperTemplate = (protocol: Protocol): string => {
381
+ const session = term(protocol, 'SESSION');
382
+ const motion = term(protocol, 'MOTION');
383
+ const division = term(protocol, 'DIVISION');
384
+ const escalation = term(protocol, 'ESCALATION');
385
+ return `# ORDER PAPER
386
+
387
+ The business before this ${session}, in the order it is to be taken. Mirrored as
388
+ a GitHub Project board — columns map to CANON Motion state, shown in this
389
+ protocol's vocabulary.
390
+
391
+ | Column | CANON | This protocol |
328
392
  |---|---|---|
329
- | Notice Paper | Proposed, not yet tabled | — |
330
- | Tabled | Motion open | MOTION |
331
- | In Division | Review requested | DIVISION |
332
- | Awaiting Assent | Carried, not yet enacted | ASSENT pending |
333
- | Enacted | Merged | ASSENT |
334
- | Withdrawn | Closed without enactment | — |
335
- | Point of Order | Suspended pending a ruling | ESCALATION |
393
+ | Proposed | — (not yet tabled) | — |
394
+ | Tabled | MOTION open | ${motion} |
395
+ | In Division | DIVISION requested | ${division} |
396
+ | Awaiting Assent | carried, not yet enacted | ASSENT pending |
397
+ | Enacted | ASSENT | enacted |
398
+ | Withdrawn | closed without enactment | — |
399
+ | Point of Order | ESCALATION — suspended pending a ruling | ${escalation} |
336
400
 
337
- A **Milestone** is a sitting. Its closure is part of prorogation, and the
338
- prorogation workflow surfaces the milestone id for the caller to close.
401
+ A **Milestone** is a sitting; its closure is part of prorogation, and the
402
+ prorogation flow surfaces the milestone id for the caller to close.
339
403
 
340
404
  ## Business
341
405
 
342
406
  1. _Add the first item of business here._
343
407
  `;
408
+ };
344
409
 
345
410
  /* -------------------------------------------------------------------------- */
346
411
  /* Bundle */
347
412
  /* -------------------------------------------------------------------------- */
348
413
 
414
+ /**
415
+ * Onboarding for any agent that lands in the session directory.
416
+ *
417
+ * The workflow this exists for: `cd` into a session, launch an agent, prompt it
418
+ * in natural language. The agent should become fluent immediately rather than
419
+ * inferring that this is Politik and discovering the CLI. AGENTS.md is the
420
+ * cross-agent convention; a one-line CLAUDE.md points Claude Code at it.
421
+ */
422
+ export const agentsTemplate = (options: CharterTemplateOptions = {}): string => {
423
+ const protocol = options.protocol ?? 'parliamentary';
424
+ return `# Agent guide — this is a Politik session
425
+
426
+ You are inside a **Politik** governance session: a git-tracked directory that *is*
427
+ the proceeding. \`CHARTER.md\` is the constitution, \`HANSARD.md\` is the immutable
428
+ record, \`STATE.json\` is the live state — and the **git history is the Hansard**:
429
+ every governance act is one commit.
430
+
431
+ This session runs the **${protocol}** protocol. Drive it with the \`politik\` CLI
432
+ (\`npm i -g @cordfuse/politik\`, or \`npx @cordfuse/politik\`). Never hand-edit
433
+ \`HANSARD.md\` or \`STATE.json\` — the record owns them; editing outside the CLI is a
434
+ Standing Orders violation and corrupts the record.
435
+
436
+ ## Read the state before acting
437
+
438
+ \`\`\`sh
439
+ politik status # protocol, state, quorum — the live picture
440
+ politik hansard # the record, in this protocol's own vocabulary
441
+ \`\`\`
442
+
443
+ ## The core loop
444
+
445
+ \`\`\`sh
446
+ politik division call --motion <id> --actor <you> --role AUTHORITY # put a question
447
+ politik division vote --motion <id> --actor <a> --role MEMBER --vote AYE|NO|ABSTAIN
448
+ politik division tally --motion <id> # decide it
449
+ politik assent --motion <id> --actor <you> --role AUTHORITY # enact a carried motion
450
+ \`\`\`
451
+
452
+ Seat a working agent instead of a human vote:
453
+
454
+ \`\`\`sh
455
+ politik run --agent claude-code --actor <a> --role OPERATOR --task "..."
456
+ \`\`\`
457
+
458
+ More verbs: \`actor hire|promote|demote|exit|dispute|reinstate\`, \`escalate\` /
459
+ \`rule\` (Points of Order), \`crisis\`, \`conflict\`, \`challenge\`, \`pair\` / \`match\`
460
+ (tournaments), \`prorogue\` (seal the session). \`politik --help\` lists everything,
461
+ and the CLI's own errors name the flags each command needs.
462
+
463
+ ## The one rule that matters
464
+
465
+ \`AUTHORITY\` acts — \`init\`, \`assent\`, \`rule\`, \`veto\`, breaking a deadlock —
466
+ exercise the **human Speaker's** constitutional authority. **Confirm with the human
467
+ before running them.** Draft and propose freely; ratifying is theirs.
468
+ `;
469
+ };
470
+
471
+ const claudePointerTemplate = (): string =>
472
+ `# This is a Politik session\n\nSee [AGENTS.md](AGENTS.md) — how to drive this governed session with the \`politik\` CLI.\n`;
473
+
349
474
  /**
350
475
  * The full Parliamentary template set, ready to commit into a session repo
351
476
  * alongside the files the initializer already writes.
352
477
  */
353
- export const parliamentaryTemplates = (
478
+ export const scaffoldTemplates = (
479
+ protocol: Protocol,
354
480
  options: CharterTemplateOptions = {},
355
481
  ): readonly FileWrite[] => [
356
482
  { path: 'CHARTER.md', content: charterTemplate(options) },
357
- { path: 'ORDER-PAPER.md', content: orderPaperTemplate() },
358
- ...roleTemplates(),
483
+ { path: 'ORDER-PAPER.md', content: orderPaperTemplate(protocol) },
484
+ { path: 'AGENTS.md', content: agentsTemplate(options) },
485
+ { path: 'CLAUDE.md', content: claudePointerTemplate() },
486
+ ...roleTemplates(protocol),
359
487
  ];