@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,190 @@
1
+ /**
2
+ * Chamber transport — carrying the broadcast.
3
+ *
4
+ * Transport is a pluggable hook, not a fixed dependency (ADR-0001). The durable
5
+ * substrate is always the session repo: the Hansard is the ordered, attributable
6
+ * source of truth, and slot claims commit there atomically.
7
+ *
8
+ * Transport carries only the **ephemeral nudge** — "a motion is live". A dropped
9
+ * message loses nothing, because a peer that hears nothing falls back to reading
10
+ * the repo. That property is what lets the default transport be git itself, with
11
+ * no broker and nothing new to run.
12
+ *
13
+ * The design consequence worth stating plainly: **nothing here is authoritative.**
14
+ * If this module and the Hansard disagree, the Hansard is right. A transport that
15
+ * could decide anything would be a second source of truth, and a governance
16
+ * framework with two records has none.
17
+ *
18
+ * Attribution: Steve Krisjanovs, Cordfuse
19
+ */
20
+
21
+ import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
22
+ import { join } from 'node:path';
23
+
24
+ import { parseEnvelope, serializeEnvelope, type Envelope } from './envelope.ts';
25
+
26
+ /* -------------------------------------------------------------------------- */
27
+ /* Interface */
28
+ /* -------------------------------------------------------------------------- */
29
+
30
+ export interface Transport {
31
+ /** Implementation name, recorded in the Hansard header. */
32
+ readonly name: string;
33
+ /** Put a broadcast on the bus. */
34
+ publish(envelope: Envelope): Promise<PublishResult>;
35
+ /** Broadcasts visible to this peer, oldest first. */
36
+ poll(sessionGuid: string): Promise<readonly Envelope[]>;
37
+ /** Mark a broadcast consumed by this peer. Best-effort. */
38
+ ack(envelope: Envelope, peer: string): Promise<void>;
39
+ }
40
+
41
+ export interface PublishResult {
42
+ /** Where the broadcast landed — a path, subject, or id. */
43
+ readonly ref: string;
44
+ readonly delivered: boolean;
45
+ }
46
+
47
+ /* -------------------------------------------------------------------------- */
48
+ /* Git transport — the reference */
49
+ /* -------------------------------------------------------------------------- */
50
+
51
+ export interface GitTransportOptions {
52
+ /** Session repo root. */
53
+ readonly dir: string;
54
+ /**
55
+ * Directory for broadcasts, relative to the repo.
56
+ *
57
+ * Under `.politik/` rather than at the root: broadcasts are engine plumbing,
58
+ * not part of the governance record, and a reader browsing the repo should
59
+ * not mistake a transient nudge for a Motion.
60
+ */
61
+ readonly channel?: string;
62
+ }
63
+
64
+ const BROADCAST = /^broadcast-(\d+)-([\w-]+)\.md$/;
65
+
66
+ /**
67
+ * Git-based transport — zero infrastructure.
68
+ *
69
+ * The SCM repository that already *is* the session is also the bus. A broadcast
70
+ * is a file; publishing is a commit; polling is a read. Latency is the poll and
71
+ * commit cadence, which is entirely adequate for proceedings that deliberate in
72
+ * minutes rather than milliseconds.
73
+ *
74
+ * Crosstalk is one such git-based transport; this is the plain-filesystem
75
+ * reference that keeps the "git already built it" promise literal.
76
+ */
77
+ export class GitTransport implements Transport {
78
+ readonly name = 'git';
79
+
80
+ readonly #dir: string;
81
+ readonly #channel: string;
82
+ /** Monotonic counter so two broadcasts in the same millisecond stay ordered. */
83
+ #sequence = 0;
84
+
85
+ constructor(options: GitTransportOptions) {
86
+ this.#dir = options.dir;
87
+ this.#channel = options.channel ?? join('.politik', 'broadcast');
88
+ }
89
+
90
+ get #channelDir(): string {
91
+ return join(this.#dir, this.#channel);
92
+ }
93
+
94
+ /**
95
+ * Publish a broadcast.
96
+ *
97
+ * The filename carries the sequence and session so ordering and routing need
98
+ * no index — the directory listing is the queue. The caller commits; this
99
+ * module writes, because committing is a governance act and belongs to the
100
+ * layer that owns the record.
101
+ */
102
+ async publish(envelope: Envelope): Promise<PublishResult> {
103
+ await mkdir(this.#channelDir, { recursive: true });
104
+ this.#sequence += 1;
105
+ const name = `broadcast-${String(this.#sequence).padStart(6, '0')}-${envelope.session_guid}.md`;
106
+ const path = join(this.#channelDir, name);
107
+ await writeFile(path, serializeEnvelope(envelope), 'utf8');
108
+ return { ref: join(this.#channel, name), delivered: true };
109
+ }
110
+
111
+ /**
112
+ * Read broadcasts for a session, oldest first.
113
+ *
114
+ * An unreadable or malformed broadcast is skipped rather than thrown. A peer
115
+ * must never be stopped by a corrupt nudge: the repo is still readable, and
116
+ * falling back to it is the whole reason transport is allowed to be lossy.
117
+ */
118
+ async poll(sessionGuid: string): Promise<readonly Envelope[]> {
119
+ let names: string[];
120
+ try {
121
+ names = await readdir(this.#channelDir);
122
+ } catch {
123
+ return [];
124
+ }
125
+
126
+ const ordered = names
127
+ .map((n) => ({ n, m: BROADCAST.exec(n) }))
128
+ .filter((x): x is { n: string; m: RegExpExecArray } => x.m !== null)
129
+ .filter((x) => x.m[2] === sessionGuid)
130
+ .sort((a, b) => Number(a.m[1]) - Number(b.m[1]));
131
+
132
+ const envelopes: Envelope[] = [];
133
+ for (const { n } of ordered) {
134
+ try {
135
+ const source = await readFile(join(this.#channelDir, n), 'utf8');
136
+ const parsed = parseEnvelope(source);
137
+ if (parsed.ok) envelopes.push(parsed.envelope);
138
+ } catch {
139
+ continue;
140
+ }
141
+ }
142
+ return envelopes;
143
+ }
144
+
145
+ /**
146
+ * Record that a peer consumed a broadcast.
147
+ *
148
+ * Advisory only. Acks help an operator see who heard what; they never gate
149
+ * participation, because a peer that never acked may still have done the work
150
+ * and committed it — and the Hansard, not the ack, is the evidence.
151
+ */
152
+ async ack(envelope: Envelope, peer: string): Promise<void> {
153
+ const dir = join(this.#channelDir, 'acks');
154
+ await mkdir(dir, { recursive: true });
155
+ await writeFile(
156
+ join(dir, `${envelope.session_guid}-${peer}.ack`),
157
+ `${envelope.session_guid} ${peer}\n`,
158
+ 'utf8',
159
+ );
160
+ }
161
+ }
162
+
163
+ /* -------------------------------------------------------------------------- */
164
+ /* Null transport */
165
+ /* -------------------------------------------------------------------------- */
166
+
167
+ /**
168
+ * A transport that carries nothing.
169
+ *
170
+ * Not a stub for tests — a legitimate configuration. A single-machine session
171
+ * whose runner is invoked directly needs no bus at all, and the architecture's
172
+ * claim that a dropped broadcast loses nothing has to hold when *every*
173
+ * broadcast is dropped. If a session cannot run over this transport, something
174
+ * has quietly become dependent on the nudge.
175
+ */
176
+ export class NullTransport implements Transport {
177
+ readonly name = 'none';
178
+
179
+ async publish(): Promise<PublishResult> {
180
+ return { ref: 'none', delivered: false };
181
+ }
182
+
183
+ async poll(): Promise<readonly Envelope[]> {
184
+ return [];
185
+ }
186
+
187
+ async ack(): Promise<void> {
188
+ // Nothing to record.
189
+ }
190
+ }
package/src/tree.ts ADDED
@@ -0,0 +1,371 @@
1
+ /**
2
+ * The Politik Tree — hierarchical inheritance and cascade.
3
+ *
4
+ * Every node is a Proceeding. A leaf is a session; a node with children governs
5
+ * them. There is no fixed depth and no special migration when a leaf gains a
6
+ * child — just a new repo whose Charter names its parent in `inherits_from`.
7
+ *
8
+ * The rule that governs everything here (EXECUTION.md § The Politik Tree):
9
+ *
10
+ * Settings inherit downward. Restrictions compound. Nothing overrides upward.
11
+ *
12
+ * A child may bind itself more tightly than its parent. It may never loosen
13
+ * what the parent set. That single asymmetry is what makes a constraint at the
14
+ * root mean something: without it, any node could opt out of governance by
15
+ * declaring a laxer Charter one level down, and the tree would be advisory.
16
+ *
17
+ * Attribution: Steve Krisjanovs, Cordfuse
18
+ */
19
+
20
+ import type { Charter } from './charter.ts';
21
+ import { appendEntry, parseEntries, type HansardEntry } from './hansard.ts';
22
+ import type { Role } from './canon.ts';
23
+
24
+ /* -------------------------------------------------------------------------- */
25
+ /* Inheritance */
26
+ /* -------------------------------------------------------------------------- */
27
+
28
+ export interface InheritanceViolation {
29
+ readonly field: string;
30
+ readonly message: string;
31
+ }
32
+
33
+ export interface ResolvedCharter {
34
+ readonly charter: Charter;
35
+ /** Fields the child tightened relative to its parent. */
36
+ readonly tightened: readonly string[];
37
+ /** Attempts to loosen a parent constraint. Always rejected. */
38
+ readonly violations: readonly InheritanceViolation[];
39
+ }
40
+
41
+ /** The tighter of two ceilings, treating null as "no ceiling". */
42
+ const tighterCeiling = (parent: number | null, child: number | null): number | null => {
43
+ if (parent === null) return child;
44
+ if (child === null) return parent;
45
+ return Math.min(parent, child);
46
+ };
47
+
48
+ /**
49
+ * Resolve a child Charter against its parent.
50
+ *
51
+ * Returns the effective Charter the child actually runs under — which is not
52
+ * necessarily the one it declared. A child that tries to loosen a parent
53
+ * constraint does not fail to load; it runs under the parent's value, and the
54
+ * attempt is reported so it can be recorded rather than silently corrected.
55
+ *
56
+ * Silent correction would be the worse failure: a Speaker would believe their
57
+ * Charter was in force when it was not.
58
+ */
59
+ export const resolveInheritance = (parent: Charter, child: Charter): ResolvedCharter => {
60
+ const tightened: string[] = [];
61
+ const violations: InheritanceViolation[] = [];
62
+
63
+ // Quorum: a child may require more actors, never fewer.
64
+ let quorum = child.session.quorum;
65
+ if (child.session.quorum < parent.session.quorum) {
66
+ violations.push({
67
+ field: 'session.quorum',
68
+ message: `child declares ${child.session.quorum}, parent requires ${parent.session.quorum} — the parent value stands`,
69
+ });
70
+ quorum = parent.session.quorum;
71
+ } else if (child.session.quorum > parent.session.quorum) {
72
+ tightened.push('session.quorum');
73
+ }
74
+
75
+ // Escalation: a parent that permits appeals cannot have them removed below.
76
+ let escalation = child.session.escalation;
77
+ if (parent.session.escalation === 'enabled' && child.session.escalation === 'disabled') {
78
+ violations.push({
79
+ field: 'session.escalation',
80
+ message: 'a child may not disable escalation its parent permits — the parent value stands',
81
+ });
82
+ escalation = 'enabled';
83
+ }
84
+
85
+ // Ceilings: the tighter of the two always wins, from either side.
86
+ const maxCost = tighterCeiling(
87
+ parent.session.endurance.max_cost_usd,
88
+ child.session.endurance.max_cost_usd,
89
+ );
90
+ if (maxCost !== child.session.endurance.max_cost_usd) tightened.push('session.endurance.max_cost_usd');
91
+
92
+ const maxMotions = tighterCeiling(
93
+ parent.session.endurance.max_motions,
94
+ child.session.endurance.max_motions,
95
+ );
96
+ if (maxMotions !== child.session.endurance.max_motions) tightened.push('session.endurance.max_motions');
97
+
98
+ const heartbeat = Math.min(
99
+ parent.session.heartbeat_timeout_hours,
100
+ child.session.heartbeat_timeout_hours,
101
+ );
102
+ if (heartbeat !== child.session.heartbeat_timeout_hours) tightened.push('session.heartbeat_timeout_hours');
103
+
104
+ // minimum_cast: a child may require more of a role, never fewer.
105
+ const minimumCast: Partial<Record<Role, number>> = { ...child.minimum_cast };
106
+ for (const [role, required] of Object.entries(parent.minimum_cast) as [Role, number][]) {
107
+ const declared = minimumCast[role];
108
+ if (declared === undefined || declared < required) {
109
+ if (declared !== undefined && declared < required) {
110
+ violations.push({
111
+ field: `minimum_cast.${role}`,
112
+ message: `child declares ${declared}, parent requires ${required} — the parent value stands`,
113
+ });
114
+ }
115
+ minimumCast[role] = required;
116
+ }
117
+ }
118
+
119
+ // A parent's domain vetoes always carry down, and a child may add its own.
120
+ //
121
+ // Omission is not revocation. A child that simply does not restate a parent
122
+ // grant has not tried to remove it — and since the schema offers no way to
123
+ // express revocation, the two are indistinguishable. Treating silence as an
124
+ // attempted override would flag almost every child Charter ever written.
125
+ const domainVeto = [...new Set([...parent.domain_veto, ...child.domain_veto])];
126
+ if (domainVeto.length > child.domain_veto.length) {
127
+ tightened.push('domain_veto');
128
+ }
129
+
130
+ return {
131
+ charter: {
132
+ ...child,
133
+ session: {
134
+ ...child.session,
135
+ quorum,
136
+ escalation,
137
+ heartbeat_timeout_hours: heartbeat,
138
+ endurance: {
139
+ max_cost_usd: maxCost,
140
+ max_motions: maxMotions,
141
+ // A warning line only means something below its ceiling.
142
+ cost_warning_usd: tighterCeiling(
143
+ parent.session.endurance.cost_warning_usd,
144
+ child.session.endurance.cost_warning_usd,
145
+ ),
146
+ deadline_action: child.session.endurance.deadline_action,
147
+ },
148
+ },
149
+ minimum_cast: minimumCast,
150
+ domain_veto: domainVeto,
151
+ },
152
+ tightened,
153
+ violations,
154
+ };
155
+ };
156
+
157
+ /**
158
+ * Record an inheritance resolution.
159
+ *
160
+ * Committed at the child's Writ Drop so the node's own Hansard states what it
161
+ * actually runs under — including any constraint it tried to loosen and did
162
+ * not get.
163
+ */
164
+ export const inheritanceEntry = (
165
+ resolved: ResolvedCharter,
166
+ parent: string,
167
+ at: string,
168
+ ): HansardEntry => ({
169
+ type: 'CHARTER_INHERITED',
170
+ at,
171
+ actor: 'RECORD',
172
+ role: 'OPERATOR',
173
+ fields: {
174
+ Parent: parent,
175
+ Tightened: resolved.tightened.length > 0 ? resolved.tightened.join(', ') : 'nothing',
176
+ Overridden:
177
+ resolved.violations.length > 0
178
+ ? resolved.violations.map((v) => v.field).join(', ')
179
+ : 'nothing',
180
+ },
181
+ body:
182
+ resolved.violations.length === 0
183
+ ? 'The child Charter is consistent with its parent.'
184
+ : [
185
+ 'The following were declared more loosely than the parent permits and',
186
+ 'do not take effect. The parent value stands:',
187
+ '',
188
+ ...resolved.violations.map((v) => `- \`${v.field}\` — ${v.message}`),
189
+ ].join('\n'),
190
+ });
191
+
192
+ /* -------------------------------------------------------------------------- */
193
+ /* Cascade */
194
+ /* -------------------------------------------------------------------------- */
195
+
196
+ export interface SiblingFault {
197
+ /** Session GUID of the sibling node. */
198
+ readonly node: string;
199
+ /** Fault signature — the thing being matched across siblings. */
200
+ readonly signature: string;
201
+ readonly at: string;
202
+ }
203
+
204
+ export interface CascadeConfig {
205
+ /** Filings of the same signature across siblings needed to alert. */
206
+ readonly trigger: number;
207
+ readonly window_days: number;
208
+ }
209
+
210
+ export const DEFAULT_CASCADE: CascadeConfig = Object.freeze({
211
+ trigger: 2,
212
+ window_days: 30,
213
+ });
214
+
215
+ export interface CascadeAlert {
216
+ readonly triggered: boolean;
217
+ readonly signature: string | null;
218
+ readonly nodes: readonly string[];
219
+ readonly reason: string;
220
+ }
221
+
222
+ /**
223
+ * Detect a fault pattern repeating across sibling nodes.
224
+ *
225
+ * The architecture frames this as an epidemiological measure: if one failure is
226
+ * producing more than one downstream failure across siblings, the pattern is
227
+ * self-sustaining and needs intervention before it reaches the parent.
228
+ *
229
+ * Distinct *nodes* are counted, not filings. Ten faults in one unlucky session
230
+ * are that session's problem; the same fault in two sessions is a pattern, and
231
+ * conflating them would make every noisy node look like a systemic failure.
232
+ */
233
+ export const checkCascade = (
234
+ faults: readonly SiblingFault[],
235
+ now: string,
236
+ config: CascadeConfig = DEFAULT_CASCADE,
237
+ ): CascadeAlert => {
238
+ const current = Date.parse(now);
239
+ const windowMs = config.window_days * 86_400_000;
240
+
241
+ const bySignature = new Map<string, Set<string>>();
242
+ for (const fault of faults) {
243
+ const at = Date.parse(fault.at);
244
+ if (Number.isNaN(at) || Number.isNaN(current)) continue;
245
+ if (current - at > windowMs) continue;
246
+ const nodes = bySignature.get(fault.signature) ?? new Set<string>();
247
+ nodes.add(fault.node);
248
+ bySignature.set(fault.signature, nodes);
249
+ }
250
+
251
+ for (const [signature, nodes] of bySignature) {
252
+ if (nodes.size >= config.trigger) {
253
+ return {
254
+ triggered: true,
255
+ signature,
256
+ nodes: [...nodes],
257
+ reason: `${signature} observed in ${nodes.size} sibling nodes within ${config.window_days} days`,
258
+ };
259
+ }
260
+ }
261
+
262
+ return {
263
+ triggered: false,
264
+ signature: null,
265
+ nodes: [],
266
+ reason: `no fault signature repeated across ${config.trigger} or more siblings`,
267
+ };
268
+ };
269
+
270
+ /**
271
+ * Record a CASCADE_ALERT on the parent node.
272
+ *
273
+ * Warns; does not block. Future sessions chartering the flagged configuration
274
+ * receive the warning at Writ Drop and the Speaker may still proceed — but the
275
+ * risk is documented and attributed, which is the difference between an
276
+ * informed decision and an unlucky one.
277
+ */
278
+ export const cascadeEntry = (alert: CascadeAlert, at: string): HansardEntry => {
279
+ if (!alert.triggered) {
280
+ throw new Error(`no cascade to record — ${alert.reason}`);
281
+ }
282
+ return {
283
+ type: 'CASCADE_ALERT',
284
+ at,
285
+ actor: 'RECORD',
286
+ role: 'OPERATOR',
287
+ fields: {
288
+ Signature: alert.signature ?? 'unknown',
289
+ Nodes: alert.nodes.join(', '),
290
+ Action: 'warn at Writ Drop for this configuration',
291
+ Notify: 'AUTHORITY',
292
+ },
293
+ body: `${alert.reason}. Sessions chartering this configuration will carry this warning. The Speaker may proceed; the risk is on the record.`,
294
+ };
295
+ };
296
+
297
+ /* -------------------------------------------------------------------------- */
298
+ /* Scope mobility */
299
+ /* -------------------------------------------------------------------------- */
300
+
301
+ export interface ScopeMoveInput {
302
+ readonly at: string;
303
+ readonly actor: string;
304
+ readonly role: Role;
305
+ readonly subject: string;
306
+ /** Node the actor is being scoped to. */
307
+ readonly to_node: string;
308
+ readonly reason: string;
309
+ }
310
+
311
+ /**
312
+ * Move an actor's scope up or down the tree.
313
+ *
314
+ * Recorded at the node where the decision was made — the level that had the
315
+ * authority to make it. A promotion decided at the sprint node belongs in the
316
+ * sprint node's Hansard, not the leaf's, because that is where the
317
+ * accountability sits.
318
+ */
319
+ export const scopeMove = (
320
+ input: ScopeMoveInput,
321
+ direction: 'PROMOTE_SCOPE' | 'DEMOTE_SCOPE',
322
+ ): HansardEntry => ({
323
+ type: direction,
324
+ at: input.at,
325
+ actor: input.actor,
326
+ role: input.role,
327
+ fields: {
328
+ 'Actor affected': input.subject,
329
+ 'Scoped to': input.to_node,
330
+ Reason: input.reason,
331
+ },
332
+ });
333
+
334
+ /* -------------------------------------------------------------------------- */
335
+ /* Quarantine */
336
+ /* -------------------------------------------------------------------------- */
337
+
338
+ /**
339
+ * Quarantine a branch.
340
+ *
341
+ * The parent's response when a cascade cannot be contained at the child level.
342
+ * Recorded on the parent, because a branch cannot quarantine itself — the whole
343
+ * point is that the decision comes from above the failure.
344
+ */
345
+ export const quarantineEntry = (
346
+ node: string,
347
+ at: string,
348
+ actor: string,
349
+ reason: string,
350
+ ): HansardEntry => ({
351
+ type: 'QUARANTINE',
352
+ at,
353
+ actor,
354
+ role: 'AUTHORITY',
355
+ fields: {
356
+ Node: node,
357
+ Effect: 'no further sessions convene under this node until released',
358
+ Reason: reason,
359
+ },
360
+ });
361
+
362
+ /** Every cascade alert already on a node's record. */
363
+ export const cascadeAlerts = (hansard: string): readonly string[] =>
364
+ parseEntries(hansard)
365
+ .filter((e) => e.type === 'CASCADE_ALERT')
366
+ .map((e) => e.fields['Signature'] ?? '')
367
+ .filter((s) => s.length > 0);
368
+
369
+ /** Append an entry to a node's Hansard. */
370
+ export const recordOnNode = (hansard: string, entry: HansardEntry): string =>
371
+ appendEntry(hansard, entry);