@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/scm.ts ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * SCM Provider Interface.
3
+ *
4
+ * GitHub is the reference implementation; the framework only ever speaks to
5
+ * this interface. POLITIK-ARCHITECTURE.md names the methods but leaves return
6
+ * types unspecified — Phase 1 ruled that a signature exercise to be settled in
7
+ * the scaffold. This module settles it.
8
+ *
9
+ * Design rules applied here:
10
+ * - Every call is async. Every provider is a network boundary.
11
+ * - Nothing returns a bare string. Each mutation returns a typed handle so the
12
+ * Hansard writer has something attributable to record.
13
+ * - Provider-native identifiers stay opaque (`id`), with `url` carried
14
+ * alongside for the human-readable record.
15
+ *
16
+ * Attribution: Steve Krisjanovs, Cordfuse
17
+ */
18
+
19
+ import type { MergeStrategy, Role } from './canon.ts';
20
+
21
+ /* -------------------------------------------------------------------------- */
22
+ /* Handles */
23
+ /* -------------------------------------------------------------------------- */
24
+
25
+ /** A provider-native reference to a created or mutated object. */
26
+ export interface Ref {
27
+ /** Opaque provider identifier. Never parsed by the engine. */
28
+ readonly id: string;
29
+ /** Human-readable location, recorded in the Hansard. */
30
+ readonly url: string;
31
+ }
32
+
33
+ /** Result of a commit — a MOTION's underlying write. */
34
+ export interface CommitRef extends Ref {
35
+ readonly sha: string;
36
+ }
37
+
38
+ /** A tabled MOTION. */
39
+ export interface MotionRef extends Ref {
40
+ readonly number: number;
41
+ readonly branch: string;
42
+ }
43
+
44
+ /** An ESCALATION — a Point of Order. */
45
+ export interface EscalationRef extends Ref {
46
+ readonly number: number;
47
+ }
48
+
49
+ /** A DIVISION requested against a MOTION. */
50
+ export interface DivisionRef extends Ref {
51
+ readonly motion: number;
52
+ readonly reviewers: readonly string[];
53
+ }
54
+
55
+ /** The enactment of a carried MOTION. */
56
+ export interface AssentResult extends Ref {
57
+ readonly motion: number;
58
+ readonly strategy: MergeStrategy;
59
+ readonly merged: boolean;
60
+ readonly sha: string;
61
+ }
62
+
63
+ /* -------------------------------------------------------------------------- */
64
+ /* Inputs */
65
+ /* -------------------------------------------------------------------------- */
66
+
67
+ /** A file written as part of a commit. Content is UTF-8 text. */
68
+ export interface FileWrite {
69
+ readonly path: string;
70
+ readonly content: string;
71
+ }
72
+
73
+ /** Permission granted to a collaborator, expressed in CANON terms. */
74
+ export interface CollaboratorGrant {
75
+ readonly handle: string;
76
+ readonly role: Role;
77
+ }
78
+
79
+ /* -------------------------------------------------------------------------- */
80
+ /* Provider */
81
+ /* -------------------------------------------------------------------------- */
82
+
83
+ /**
84
+ * The full surface the engine requires of an SCM. A provider that implements
85
+ * these eleven methods can host a Politik session.
86
+ *
87
+ * Note: POLITIK-ARCHITECTURE.md § SCM PROVIDER ABSTRACTION lists eleven method
88
+ * names while EXECUTION.md § Phase 1 refers to "ten methods". The interface
89
+ * below implements all eleven as listed in the architecture document.
90
+ */
91
+ export interface ScmProvider {
92
+ /** Provider identifier, e.g. `github`. Recorded in the Hansard header. */
93
+ readonly name: string;
94
+
95
+ /** Write files to the session repo. The underlying act of every MOTION. */
96
+ commit(message: string, files: readonly FileWrite[]): Promise<CommitRef>;
97
+
98
+ /** Table a MOTION. */
99
+ openPR(title: string, body: string, branch: string): Promise<MotionRef>;
100
+
101
+ /** Call a DIVISION on a tabled MOTION. */
102
+ requestReview(pr: number, actors: readonly string[]): Promise<DivisionRef>;
103
+
104
+ /**
105
+ * ASSENT — enact a carried MOTION. The Division decides; this enacts.
106
+ * Callers must verify the Motion carried before invoking; providers reject
107
+ * strategies the Charter did not permit.
108
+ */
109
+ merge(pr: number, strategy: MergeStrategy): Promise<AssentResult>;
110
+
111
+ /** File an ESCALATION — a Point of Order. */
112
+ openIssue(
113
+ title: string,
114
+ body: string,
115
+ labels: readonly string[],
116
+ ): Promise<EscalationRef>;
117
+
118
+ /** Open a discussion thread for non-binding deliberation. */
119
+ openDiscussion(
120
+ title: string,
121
+ body: string,
122
+ category: string,
123
+ ): Promise<Ref>;
124
+
125
+ /** Close a milestone — used by the prorogation workflow. */
126
+ closeMilestone(id: string): Promise<void>;
127
+
128
+ /** Notify an actor out of band. Speaker email notification rides this. */
129
+ notify(actor: string, message: string): Promise<void>;
130
+
131
+ /** Trigger provider-side automation — the Clerk. */
132
+ triggerWorkflow(
133
+ name: string,
134
+ inputs: Readonly<Record<string, string>>,
135
+ ): Promise<Ref>;
136
+
137
+ /** Create a label in the provider's taxonomy. */
138
+ createLabel(name: string, color: string): Promise<Ref>;
139
+
140
+ /** Admit an actor to the session repo at a CANON role. */
141
+ addCollaborator(grant: CollaboratorGrant): Promise<void>;
142
+ }
package/src/spawn.ts ADDED
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Agent spawning.
3
+ *
4
+ * The stateless worker cycle: spawn, execute prompt, capture result, dispose.
5
+ * No agent outlives its turn, and no state lives in the process — the Hansard
6
+ * is the session.
7
+ *
8
+ * Kept separate from `agents.ts` so the registry, invocation shapes and prompt
9
+ * composition stay pure and testable with no CLI installed. This module is the
10
+ * only place a child process is created.
11
+ *
12
+ * Attribution: Steve Krisjanovs, Cordfuse
13
+ */
14
+
15
+ import { spawn as nodeSpawn } from 'node:child_process';
16
+
17
+ import { buildInvocation, type AgentSpec } from './agents.ts';
18
+
19
+ /* -------------------------------------------------------------------------- */
20
+ /* Result */
21
+ /* -------------------------------------------------------------------------- */
22
+
23
+ export interface SpawnResult {
24
+ readonly agent: string;
25
+ readonly ok: boolean;
26
+ readonly exit_code: number | null;
27
+ readonly stdout: string;
28
+ readonly stderr: string;
29
+ /** Wall-clock milliseconds, for the LEDGER. */
30
+ readonly elapsed_ms: number;
31
+ /** True when the agent was killed for exceeding its timeout. */
32
+ readonly timed_out: boolean;
33
+ }
34
+
35
+ export interface SpawnOptions {
36
+ /** Working directory. Agents may never traverse above it. */
37
+ readonly cwd: string;
38
+ /** Hard ceiling. An agent that hangs must not hang the proceeding. */
39
+ readonly timeout_ms?: number;
40
+ /**
41
+ * Environment for the child. Defaults to the parent environment.
42
+ * Callers running untrusted agents should pass a minimal env explicitly.
43
+ */
44
+ readonly env?: NodeJS.ProcessEnv;
45
+ readonly extraArgs?: readonly string[];
46
+ /** Injectable for tests. */
47
+ readonly spawnFn?: typeof nodeSpawn;
48
+ /** Supplies elapsed time. Injectable so tests stay deterministic. */
49
+ readonly clock?: () => number;
50
+ }
51
+
52
+ const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
53
+
54
+ /* -------------------------------------------------------------------------- */
55
+ /* Spawn */
56
+ /* -------------------------------------------------------------------------- */
57
+
58
+ /**
59
+ * Spawn an agent and capture its result.
60
+ *
61
+ * Never uses a shell. The prompt carries Charter text, Hansard excerpts and
62
+ * arbitrary session content; passing that through a shell would make every
63
+ * spawn an injection site. Args go to the child directly.
64
+ *
65
+ * Rejects only on a spawn failure the OS reports (command not found, permission
66
+ * denied). A non-zero exit is a *result*, not an exception — an agent that
67
+ * fails its task has still participated, and the Hansard records the outcome
68
+ * either way.
69
+ */
70
+ export const spawnAgent = async (
71
+ agent: AgentSpec,
72
+ prompt: string,
73
+ options: SpawnOptions,
74
+ ): Promise<SpawnResult> => {
75
+ const invocation = buildInvocation(agent, prompt, options.extraArgs ?? []);
76
+ const spawnFn = options.spawnFn ?? nodeSpawn;
77
+ const clock = options.clock ?? (() => Date.now());
78
+ const timeout = options.timeout_ms ?? DEFAULT_TIMEOUT_MS;
79
+ const started = clock();
80
+
81
+ return new Promise<SpawnResult>((resolve, reject) => {
82
+ const child = spawnFn(invocation.command, [...invocation.args], {
83
+ cwd: options.cwd,
84
+ env: options.env ?? process.env,
85
+ shell: false,
86
+ stdio: ['ignore', 'pipe', 'pipe'],
87
+ });
88
+
89
+ let stdout = '';
90
+ let stderr = '';
91
+ let timedOut = false;
92
+ let settled = false;
93
+
94
+ const timer =
95
+ timeout > 0
96
+ ? setTimeout(() => {
97
+ timedOut = true;
98
+ child.kill('SIGTERM');
99
+ }, timeout)
100
+ : null;
101
+
102
+ child.stdout?.on('data', (chunk: Buffer) => {
103
+ stdout += chunk.toString();
104
+ });
105
+ child.stderr?.on('data', (chunk: Buffer) => {
106
+ stderr += chunk.toString();
107
+ });
108
+
109
+ const finish = (code: number | null) => {
110
+ if (settled) return;
111
+ settled = true;
112
+ if (timer !== null) clearTimeout(timer);
113
+ resolve({
114
+ agent: agent.id,
115
+ ok: code === 0 && !timedOut,
116
+ exit_code: code,
117
+ stdout,
118
+ stderr,
119
+ elapsed_ms: clock() - started,
120
+ timed_out: timedOut,
121
+ });
122
+ };
123
+
124
+ child.on('close', finish);
125
+
126
+ child.on('error', (error) => {
127
+ if (settled) return;
128
+ settled = true;
129
+ if (timer !== null) clearTimeout(timer);
130
+ reject(error);
131
+ });
132
+ });
133
+ };
134
+
135
+ /* -------------------------------------------------------------------------- */
136
+ /* Availability */
137
+ /* -------------------------------------------------------------------------- */
138
+
139
+ /**
140
+ * Is this agent's command present on PATH?
141
+ *
142
+ * Used at Writ Drop to fail fast: a Charter naming a constituency whose agent
143
+ * is not installed should be caught before the session opens, not when the
144
+ * first broadcast goes unanswered.
145
+ */
146
+ export const isAvailable = async (
147
+ agent: AgentSpec,
148
+ spawnFn: typeof nodeSpawn = nodeSpawn,
149
+ ): Promise<boolean> =>
150
+ new Promise((resolve) => {
151
+ // `which` directly rather than `sh -c command -v`: passing args alongside
152
+ // shell:true concatenates instead of escaping them (Node DEP0190), which is
153
+ // an injection surface for no benefit.
154
+ const probe = spawnFn('which', [agent.command], {
155
+ shell: false,
156
+ stdio: 'ignore',
157
+ });
158
+ probe.on('close', (code) => resolve(code === 0));
159
+ probe.on('error', () => resolve(false));
160
+ });
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Standings — scoring a competitive protocol from the record.
3
+ *
4
+ * A tournament or league protocol runs as a series of Divisions; who fared how
5
+ * is already in the Hansard, so — like `integrity.ts` and `federation.ts` — this
6
+ * is a pure read over the record, not new state. A "win" is voting with the side
7
+ * a Division carried; elimination is the cull an `exit: elimination` protocol
8
+ * records (ADR-0007). Two rankings, because two questions get asked of a
9
+ * tournament: who won the most (win-loss) and who lasted longest (survival).
10
+ *
11
+ * On `pairing`: Swiss / round-robin / single-elimination are 1v1-match formats,
12
+ * and a Politik Division is an N-actor vote on a Motion — there is no match to
13
+ * pair. Matchmaking needs a *match primitive* the Division model does not have;
14
+ * that is an additive design, not a scoring read, and is deliberately not faked
15
+ * here.
16
+ *
17
+ * Attribution: Steve Krisjanovs, Cordfuse
18
+ */
19
+
20
+ import { parseEntries } from './hansard.ts';
21
+ import { seats } from './actors.ts';
22
+
23
+ export interface Standing {
24
+ readonly actor: string;
25
+ /** Current role, or null if the actor is no longer seated. */
26
+ readonly seat: string | null;
27
+ /** Divisions won: voted with the side that carried (or lost, for rejected). */
28
+ readonly wins: number;
29
+ readonly losses: number;
30
+ readonly eliminated: boolean;
31
+ /** When the actor was removed, for survival ranking. Null if still standing. */
32
+ readonly eliminated_at: string | null;
33
+ }
34
+
35
+ export type RankBy = 'win-loss' | 'survival';
36
+
37
+ /**
38
+ * Score every actor who took part. A win is a vote on the carrying side of a
39
+ * decided Division; a loss is a vote on the other side; an abstention is neither.
40
+ * Elimination and current seat come from the actor record.
41
+ */
42
+ export const standings = (hansard: string, by: RankBy = 'win-loss'): readonly Standing[] => {
43
+ const entries = parseEntries(hansard);
44
+
45
+ // motion -> voter -> vote, and motion -> carried?
46
+ const votes = new Map<string, Map<string, string>>();
47
+ const carried = new Map<string, boolean>();
48
+ const wins = new Map<string, number>();
49
+ const losses = new Map<string, number>();
50
+ const eliminatedAt = new Map<string, string>();
51
+ const participants = new Set<string>();
52
+
53
+ const bump = (map: Map<string, number>, key: string): void => {
54
+ map.set(key, (map.get(key) ?? 0) + 1);
55
+ };
56
+
57
+ for (const entry of entries) {
58
+ const motion = entry.fields['Motion'];
59
+ const subject = entry.fields['Actor affected'];
60
+
61
+ switch (entry.type) {
62
+ case 'VOTE_CAST': {
63
+ if (motion === undefined) break;
64
+ const cast = votes.get(motion) ?? new Map<string, string>();
65
+ cast.set(entry.actor, entry.fields['Vote'] ?? 'ABSTAIN');
66
+ votes.set(motion, cast);
67
+ participants.add(entry.actor);
68
+ break;
69
+ }
70
+ case 'MOTION_CARRIED':
71
+ if (motion !== undefined) carried.set(motion, true);
72
+ break;
73
+ case 'MOTION_REJECTED':
74
+ if (motion !== undefined) carried.set(motion, false);
75
+ break;
76
+ case 'MATCH_DECIDED': {
77
+ // A tournament (ADR-0009) scores the same table: the winner takes a win,
78
+ // the loser a loss. A bye ('bye') gives its winner a win and no one a loss.
79
+ const winner = entry.fields['Winner'];
80
+ const loser = entry.fields['Loser'];
81
+ if (winner !== undefined) { bump(wins, winner); participants.add(winner); }
82
+ if (loser !== undefined && loser !== 'bye') { bump(losses, loser); participants.add(loser); }
83
+ break;
84
+ }
85
+ case 'ACTOR_HIRED':
86
+ if (subject !== undefined) participants.add(subject);
87
+ break;
88
+ case 'ACTOR_EXITED':
89
+ // A re-seating (reinstatement) clears the elimination; seats() is the
90
+ // authority on who is currently out, so only stamp the time here.
91
+ if (subject !== undefined) eliminatedAt.set(subject, entry.at);
92
+ break;
93
+ default:
94
+ break;
95
+ }
96
+ }
97
+
98
+ // Score decided Divisions.
99
+ for (const [motion, decided] of carried) {
100
+ const cast = votes.get(motion);
101
+ if (cast === undefined) continue;
102
+ for (const [actor, vote] of cast) {
103
+ if (vote === 'ABSTAIN') continue;
104
+ const wonSide = (vote === 'AYE' && decided) || (vote === 'NO' && !decided);
105
+ bump(wonSide ? wins : losses, actor);
106
+ }
107
+ }
108
+
109
+ const seated = new Map(seats(hansard).map((s) => [s.actor, s.role]));
110
+
111
+ const rows: Standing[] = [...participants].map((actor) => ({
112
+ actor,
113
+ seat: seated.get(actor) ?? null,
114
+ wins: wins.get(actor) ?? 0,
115
+ losses: losses.get(actor) ?? 0,
116
+ // Eliminated = has an exit on the record and is not currently seated (a
117
+ // reinstated actor is back in, not eliminated).
118
+ eliminated: eliminatedAt.has(actor) && !seated.has(actor),
119
+ eliminated_at: seated.has(actor) ? null : (eliminatedAt.get(actor) ?? null),
120
+ }));
121
+
122
+ return rank(rows, by);
123
+ };
124
+
125
+ /** Order the table. Ties break on the other metric, then the name, for stability. */
126
+ const rank = (rows: readonly Standing[], by: RankBy): readonly Standing[] => {
127
+ const sorted = [...rows];
128
+ if (by === 'survival') {
129
+ // Still standing first; among the eliminated, the last one out ranks highest.
130
+ sorted.sort((a, b) => {
131
+ if (a.eliminated !== b.eliminated) return a.eliminated ? 1 : -1;
132
+ if (a.eliminated && b.eliminated) {
133
+ const t = (b.eliminated_at ?? '').localeCompare(a.eliminated_at ?? '');
134
+ if (t !== 0) return t;
135
+ }
136
+ return (b.wins - a.wins) || a.actor.localeCompare(b.actor);
137
+ });
138
+ } else {
139
+ sorted.sort((a, b) =>
140
+ (b.wins - a.wins) || (a.losses - b.losses) || a.actor.localeCompare(b.actor));
141
+ }
142
+ return sorted;
143
+ };
package/src/state.ts ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * STATE.json — current session state.
3
+ *
4
+ * Schema is fixed by ADR-0003. One `state` field, CANON-valued; cause carried
5
+ * separately. The RECORD agent is the sole writer; every actor reads this file
6
+ * before every action, because a suspended session must stop agents at once.
7
+ *
8
+ * Note on representation: CANON codes are `STATE_*` (POLITIK-ARCHITECTURE.md
9
+ * § Session States) while ADR-0003's JSON carries the bare form (`CONVENED`).
10
+ * Both are the same five states. This module owns the mapping so the wire
11
+ * format stays exactly as the ADR specifies.
12
+ *
13
+ * Attribution: Steve Krisjanovs, Cordfuse
14
+ */
15
+
16
+ import {
17
+ isSuspensionCause,
18
+ type State,
19
+ type SuspensionCause,
20
+ } from './canon.ts';
21
+
22
+ /* -------------------------------------------------------------------------- */
23
+ /* Wire form */
24
+ /* -------------------------------------------------------------------------- */
25
+
26
+ /** The bare state values as written to STATE.json. */
27
+ export const SESSION_STATES = [
28
+ 'CONVENED',
29
+ 'SUSPENDED',
30
+ 'PROROGUED',
31
+ 'STALE',
32
+ 'INVALID',
33
+ ] as const;
34
+
35
+ export type SessionState = (typeof SESSION_STATES)[number];
36
+
37
+ export const isSessionState = (v: unknown): v is SessionState =>
38
+ typeof v === 'string' && (SESSION_STATES as readonly string[]).includes(v);
39
+
40
+ /** CANON code -> STATE.json wire value. */
41
+ export const toSessionState = (state: State): SessionState =>
42
+ state.replace(/^STATE_/, '') as SessionState;
43
+
44
+ /** STATE.json wire value -> CANON code. */
45
+ export const toCanonState = (state: SessionState): State =>
46
+ `STATE_${state}` as State;
47
+
48
+ /**
49
+ * Every state except CONVENED means stop. Agents check this before acting.
50
+ */
51
+ export const halts = (state: SessionState): boolean => state !== 'CONVENED';
52
+
53
+ /* -------------------------------------------------------------------------- */
54
+ /* Schema */
55
+ /* -------------------------------------------------------------------------- */
56
+
57
+ export const STATE_SCHEMA_VERSION = '1.0.0';
58
+
59
+ export interface Suspension {
60
+ readonly cause: SuspensionCause;
61
+ readonly since: string;
62
+ /** Hansard anchor, e.g. `HANSARD.md#L482`. */
63
+ readonly record_ref: string | null;
64
+ /** Escalation file, e.g. `escalations/2026-04-08-001.md`. */
65
+ readonly escalation_ref: string | null;
66
+ }
67
+
68
+ export interface QuorumState {
69
+ readonly required: number;
70
+ readonly present: number;
71
+ }
72
+
73
+ export interface SessionStateFile {
74
+ readonly schema_version: string;
75
+ readonly session_guid: string;
76
+ readonly protocol: string;
77
+ readonly state: SessionState;
78
+ readonly suspension: Suspension | null;
79
+ readonly quorum: QuorumState;
80
+ /** Last Hansard commit this state reflects. Null before the first record. */
81
+ readonly hansard_head: string | null;
82
+ readonly updated_at: string;
83
+ readonly updated_by: string;
84
+ }
85
+
86
+ /* -------------------------------------------------------------------------- */
87
+ /* Construction */
88
+ /* -------------------------------------------------------------------------- */
89
+
90
+ export interface CreateStateInput {
91
+ readonly session_guid: string;
92
+ readonly protocol: string;
93
+ readonly state: SessionState;
94
+ readonly quorum: QuorumState;
95
+ readonly updated_at: string;
96
+ readonly suspension?: Suspension | null;
97
+ readonly hansard_head?: string | null;
98
+ readonly updated_by?: string;
99
+ }
100
+
101
+ /**
102
+ * Build a STATE.json document. `updated_by` defaults to RECORD, the only actor
103
+ * constitutionally permitted to write this file.
104
+ */
105
+ export const createState = (input: CreateStateInput): SessionStateFile => ({
106
+ schema_version: STATE_SCHEMA_VERSION,
107
+ session_guid: input.session_guid,
108
+ protocol: input.protocol,
109
+ state: input.state,
110
+ suspension: input.suspension ?? null,
111
+ quorum: input.quorum,
112
+ hansard_head: input.hansard_head ?? null,
113
+ updated_at: input.updated_at,
114
+ updated_by: input.updated_by ?? 'RECORD',
115
+ });
116
+
117
+ /** Serialize for commit. Trailing newline so the file is diff-friendly. */
118
+ export const serializeState = (state: SessionStateFile): string =>
119
+ `${JSON.stringify(state, null, 2)}\n`;
120
+
121
+ /* -------------------------------------------------------------------------- */
122
+ /* Validation */
123
+ /* -------------------------------------------------------------------------- */
124
+
125
+ export interface StateIssue {
126
+ readonly field: string;
127
+ readonly message: string;
128
+ }
129
+
130
+ /**
131
+ * Check a STATE.json document for internal consistency.
132
+ *
133
+ * The invariant that matters: `suspension` is populated when and only when the
134
+ * state is SUSPENDED. A SUSPENDED session with no cause is unresolvable, and a
135
+ * cause attached to a running session is a contradiction.
136
+ */
137
+ export const validateState = (state: SessionStateFile): readonly StateIssue[] => {
138
+ const issues: StateIssue[] = [];
139
+
140
+ if (!isSessionState(state.state)) {
141
+ issues.push({ field: 'state', message: `not a CANON state: ${String(state.state)}` });
142
+ }
143
+
144
+ if (state.state === 'SUSPENDED') {
145
+ if (state.suspension === null) {
146
+ issues.push({
147
+ field: 'suspension',
148
+ message: 'must be populated when state is SUSPENDED',
149
+ });
150
+ } else if (!isSuspensionCause(state.suspension.cause)) {
151
+ issues.push({
152
+ field: 'suspension.cause',
153
+ message: `not a CANON suspension cause: ${String(state.suspension.cause)}`,
154
+ });
155
+ }
156
+ } else if (state.suspension !== null) {
157
+ issues.push({
158
+ field: 'suspension',
159
+ message: `must be null unless state is SUSPENDED (state is ${state.state})`,
160
+ });
161
+ }
162
+
163
+ if (state.quorum.present < 0 || state.quorum.required < 0) {
164
+ issues.push({ field: 'quorum', message: 'counts must be non-negative' });
165
+ }
166
+
167
+ return issues;
168
+ };
169
+
170
+ /** Parse STATE.json text. Returns null when the document is unreadable. */
171
+ export const parseState = (source: string): SessionStateFile | null => {
172
+ try {
173
+ const raw: unknown = JSON.parse(source);
174
+ if (typeof raw !== 'object' || raw === null) return null;
175
+ return raw as SessionStateFile;
176
+ } catch {
177
+ return null;
178
+ }
179
+ };