@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
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Heartbeat, staleness and resumption.
3
+ *
4
+ * A proceeding that goes quiet is not the same as one that was paused. RUNTIME
5
+ * originally modelled both as `suspended: true`; ADR-0003 separated them,
6
+ * because "a human stopped this" and "the agents went away" call for different
7
+ * responses and a boolean cannot tell you which happened.
8
+ *
9
+ * So STALE is its own CANON state and carries no `suspension` — a stale session
10
+ * has no cause to record, only an absence.
11
+ *
12
+ * The heartbeat is the **last Hansard commit**, not a liveness ping. Nothing
13
+ * separate has to be running: if the record has not moved, nothing happened,
14
+ * and a proceeding in which nothing happens is by definition not proceeding.
15
+ *
16
+ * Attribution: Steve Krisjanovs, Cordfuse
17
+ */
18
+
19
+ import { appendEntry, parseEntries, type HansardEntry } from './hansard.ts';
20
+ import { createState, type SessionStateFile } from './state.ts';
21
+
22
+ /* -------------------------------------------------------------------------- */
23
+ /* Staleness */
24
+ /* -------------------------------------------------------------------------- */
25
+
26
+ export interface HeartbeatCheck {
27
+ readonly stale: boolean;
28
+ /** Last Hansard entry timestamp, or null for an empty record. */
29
+ readonly last_beat: string | null;
30
+ readonly hours_since: number | null;
31
+ readonly timeout_hours: number;
32
+ readonly reason: string;
33
+ }
34
+
35
+ /**
36
+ * Has the proceeding gone quiet?
37
+ *
38
+ * `now` is supplied by the caller — this module reads no clock, so a check is
39
+ * reproducible and a test does not have to wait four hours.
40
+ *
41
+ * A session with an empty Hansard is never stale: it has not gone quiet, it has
42
+ * not started. Treating "no record yet" as staleness would suspend every
43
+ * session at the moment of its Writ Drop.
44
+ */
45
+ export const checkHeartbeat = (
46
+ hansard: string,
47
+ timeoutHours: number,
48
+ now: string,
49
+ ): HeartbeatCheck => {
50
+ const entries = parseEntries(hansard);
51
+ const last = entries.at(-1);
52
+
53
+ if (last === undefined) {
54
+ return {
55
+ stale: false,
56
+ last_beat: null,
57
+ hours_since: null,
58
+ timeout_hours: timeoutHours,
59
+ reason: 'no Hansard entries yet — the proceeding has not started',
60
+ };
61
+ }
62
+
63
+ const beat = Date.parse(last.at);
64
+ const current = Date.parse(now);
65
+ if (Number.isNaN(beat) || Number.isNaN(current)) {
66
+ return {
67
+ stale: false,
68
+ last_beat: last.at,
69
+ hours_since: null,
70
+ timeout_hours: timeoutHours,
71
+ reason: 'timestamps unreadable — declining to declare staleness on bad data',
72
+ };
73
+ }
74
+
75
+ const hours = (current - beat) / 3_600_000;
76
+ const stale = hours >= timeoutHours;
77
+
78
+ return {
79
+ stale,
80
+ last_beat: last.at,
81
+ hours_since: hours,
82
+ timeout_hours: timeoutHours,
83
+ reason: stale
84
+ ? `no Hansard commit in ${hours.toFixed(1)}h (timeout ${timeoutHours}h)`
85
+ : `last beat ${hours.toFixed(1)}h ago, within the ${timeoutHours}h window`,
86
+ };
87
+ };
88
+
89
+ export class HeartbeatError extends Error {
90
+ constructor(message: string) {
91
+ super(message);
92
+ this.name = 'HeartbeatError';
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Mark a quiet proceeding STALE.
98
+ *
99
+ * Suspends rather than dissolves (`stale_action: suspend`). Silence is not a
100
+ * decision to end anything — the operator may simply have gone offline, and
101
+ * dissolving on their behalf would destroy a resumable proceeding.
102
+ *
103
+ * Every actor reads STATE.json before acting, so agents stop as soon as this
104
+ * commits. No separate stop signal is needed.
105
+ */
106
+ export const markStale = (
107
+ check: HeartbeatCheck,
108
+ at: string,
109
+ state: SessionStateFile,
110
+ hansard: string,
111
+ ): {
112
+ readonly entry: HansardEntry;
113
+ readonly hansard: string;
114
+ readonly state: SessionStateFile;
115
+ } => {
116
+ if (!check.stale) throw new HeartbeatError(`not stale — ${check.reason}`);
117
+ if (state.state !== 'CONVENED') {
118
+ throw new HeartbeatError(`only a CONVENED proceeding can go stale — this is ${state.state}`);
119
+ }
120
+
121
+ const entry: HansardEntry = {
122
+ type: 'SESSION_STALE',
123
+ at,
124
+ actor: 'RECORD',
125
+ role: 'OPERATOR',
126
+ fields: {
127
+ 'Last beat': check.last_beat ?? 'none',
128
+ Elapsed: check.hours_since === null ? 'unknown' : `${check.hours_since.toFixed(1)}h`,
129
+ Timeout: `${check.timeout_hours}h`,
130
+ 'Session status': 'STALE — auto-suspended, resumable',
131
+ },
132
+ body: 'No Hansard commit within the heartbeat window. The proceeding is resumable: nothing is lost, and committed work stands.',
133
+ };
134
+
135
+ return {
136
+ entry,
137
+ hansard: appendEntry(hansard, entry),
138
+ state: createState({
139
+ session_guid: state.session_guid,
140
+ protocol: state.protocol,
141
+ // STALE is a state, not a suspension cause — hence no `suspension` here.
142
+ state: 'STALE',
143
+ quorum: state.quorum,
144
+ hansard_head: state.hansard_head,
145
+ updated_at: at,
146
+ }),
147
+ };
148
+ };
149
+
150
+ /* -------------------------------------------------------------------------- */
151
+ /* Snapshots */
152
+ /* -------------------------------------------------------------------------- */
153
+
154
+ export interface Snapshot {
155
+ readonly completed: readonly string[];
156
+ readonly in_flight: readonly string[];
157
+ readonly pending: readonly string[];
158
+ readonly blocked: readonly string[];
159
+ readonly cost_usd: number;
160
+ readonly max_cost_usd: number | null;
161
+ readonly motions: number;
162
+ readonly max_motions: number | null;
163
+ }
164
+
165
+ /**
166
+ * Sections inside an entry body use H3.
167
+ *
168
+ * ADR-0005 ruling 1 reserves H2 for entry delimiters. A body that used H2 would
169
+ * split its own entry in two when the record is read back — which is exactly
170
+ * what happened before this was fixed.
171
+ */
172
+ const section = (title: string, items: readonly string[]): string[] =>
173
+ items.length === 0 ? [] : [`### ${title}`, '', ...items.map((i) => `- ${i}`), ''];
174
+
175
+ /**
176
+ * Commit a STATE_SNAPSHOT — a complete picture of where the proceeding stands.
177
+ *
178
+ * This is what makes a proceeding survivable. Agents are stateless and
179
+ * disposable; the snapshot is what a *new* agent is given so it can continue
180
+ * work it never started. The Hansard is the session, not the agent process.
181
+ */
182
+ export const snapshot = (
183
+ data: Snapshot,
184
+ at: string,
185
+ state: SessionStateFile,
186
+ hansard: string,
187
+ ): { readonly entry: HansardEntry; readonly hansard: string } => {
188
+ const body = [
189
+ ...section('Completed', data.completed),
190
+ ...section('In flight', data.in_flight),
191
+ ...section('Pending', data.pending),
192
+ ...section('Blocked', data.blocked),
193
+ '### Cost at snapshot',
194
+ '',
195
+ `- Spent: $${data.cost_usd.toFixed(4)}${
196
+ data.max_cost_usd === null ? '' : ` of $${data.max_cost_usd.toFixed(2)} ceiling`
197
+ }`,
198
+ `- Motions: ${data.motions}${data.max_motions === null ? '' : ` of ${data.max_motions}`}`,
199
+ ].join('\n');
200
+
201
+ const entry: HansardEntry = {
202
+ type: 'STATE_SNAPSHOT',
203
+ at,
204
+ actor: 'RECORD',
205
+ role: 'OPERATOR',
206
+ fields: {
207
+ Completed: String(data.completed.length),
208
+ 'In flight': String(data.in_flight.length),
209
+ Pending: String(data.pending.length),
210
+ Blocked: String(data.blocked.length),
211
+ Spent: `$${data.cost_usd.toFixed(4)}`,
212
+ },
213
+ body,
214
+ };
215
+
216
+ return { entry, hansard: appendEntry(hansard, entry) };
217
+ };
218
+
219
+ /** The most recent STATE_SNAPSHOT, as raw markdown. Null if none exists. */
220
+ export const lastSnapshot = (hansard: string): string | null => {
221
+ const blocks = hansard.split(/^## /m).slice(1);
222
+ const snapshots = blocks.filter((b) => b.includes('— STATE_SNAPSHOT'));
223
+ const latest = snapshots.at(-1);
224
+ return latest === undefined ? null : `## ${latest.trim()}`;
225
+ };
226
+
227
+ /* -------------------------------------------------------------------------- */
228
+ /* Resume */
229
+ /* -------------------------------------------------------------------------- */
230
+
231
+ /**
232
+ * Resume a stale proceeding.
233
+ *
234
+ * Only STALE resumes this way. A SUSPENDED session was stopped by a decision —
235
+ * a Point of Order, a Speaker order, a constitutional crisis — and each of
236
+ * those has its own resolution path. Letting `resume` lift them would route
237
+ * around the governance that stopped the session in the first place, which is
238
+ * the single most dangerous shortcut this codebase could offer.
239
+ */
240
+ export const resume = (
241
+ at: string,
242
+ actor: string,
243
+ state: SessionStateFile,
244
+ hansard: string,
245
+ ): {
246
+ readonly entry: HansardEntry;
247
+ readonly hansard: string;
248
+ readonly state: SessionStateFile;
249
+ } => {
250
+ if (state.state !== 'STALE') {
251
+ throw new HeartbeatError(
252
+ state.state === 'SUSPENDED'
253
+ ? `this proceeding was suspended (${state.suspension?.cause ?? 'unknown cause'}) — resolve that, do not resume around it`
254
+ : `only a STALE proceeding can be resumed — this is ${state.state}`,
255
+ );
256
+ }
257
+
258
+ const entry: HansardEntry = {
259
+ type: 'SESSION_RESUMED',
260
+ at,
261
+ actor,
262
+ role: 'AUTHORITY',
263
+ fields: {
264
+ 'Session status': 'CONVENED — the sitting resumes',
265
+ 'Resumed from': lastSnapshot(hansard) === null ? 'the Hansard' : 'the last STATE_SNAPSHOT',
266
+ },
267
+ body: 'Agents are stateless; the record is the context. Committed work stands.',
268
+ };
269
+
270
+ return {
271
+ entry,
272
+ hansard: appendEntry(hansard, entry),
273
+ state: createState({
274
+ session_guid: state.session_guid,
275
+ protocol: state.protocol,
276
+ state: 'CONVENED',
277
+ quorum: state.quorum,
278
+ hansard_head: state.hansard_head,
279
+ updated_at: at,
280
+ }),
281
+ };
282
+ };
package/src/index.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @cordfuse/politik — public entry point.
3
+ *
4
+ * Attribution: Steve Krisjanovs, Cordfuse
5
+ */
6
+
7
+ export * from './actors.ts';
8
+ export * from './agents.ts';
9
+ export * from './canon.ts';
10
+ export * from './capability.ts';
11
+ export * from './conflict.ts';
12
+ export * from './containment.ts';
13
+ export * from './division.ts';
14
+ export * from './doctor.ts';
15
+ export * from './escalation.ts';
16
+ export * from './protocol.ts';
17
+ export * from './protocol-sdk.ts';
18
+ export * from './runner.ts';
19
+ export * from './projection.ts';
20
+ export * from './prorogation.ts';
21
+ export * from './templates/parliamentary.ts';
22
+ export * from './quorum.ts';
23
+ export * from './integrity.ts';
24
+ export * from './election.ts';
25
+ export * from './envelope.ts';
26
+ export * from './fault.ts';
27
+ export * from './git.ts';
28
+ export * from './hansard.ts';
29
+ export * from './heartbeat.ts';
30
+ export * from './lockfs.ts';
31
+ export * from './charter.ts';
32
+ export * from './crisis.ts';
33
+ export * from './init.ts';
34
+ export * from './ledger.ts';
35
+ export * from './scm.ts';
36
+ export * from './spawn.ts';
37
+ export * from './state.ts';
38
+ export * from './transport.ts';
39
+ export * from './tree.ts';
40
+ export * from './federation.ts';
41
+ export * from './standings.ts';
42
+ export * from './tournament.ts';
43
+ export * from './providers/github.ts';