@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/doctor.ts ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Environment probe.
3
+ *
4
+ * Reports whether this host can run a Politik session, and how. Exists because
5
+ * the platform matrix (EXECUTION.md § Phase 6) is otherwise a list of claims
6
+ * nobody can reproduce — a Speaker on an unknown machine should be able to ask
7
+ * the tool rather than trust a table written on someone else's laptop.
8
+ *
9
+ * Probing only. Nothing here mutates anything, and a failed check is reported,
10
+ * never thrown.
11
+ *
12
+ * Attribution: Steve Krisjanovs, Cordfuse
13
+ */
14
+
15
+ import { spawn } from 'node:child_process';
16
+ import { platform, release } from 'node:os';
17
+
18
+ import { AGENTS, type AgentSpec } from './agents.ts';
19
+ import { isAvailable } from './spawn.ts';
20
+
21
+ /* -------------------------------------------------------------------------- */
22
+ /* Findings */
23
+ /* -------------------------------------------------------------------------- */
24
+
25
+ export type CheckStatus = 'ok' | 'warn' | 'fail';
26
+
27
+ export interface Check {
28
+ readonly name: string;
29
+ readonly status: CheckStatus;
30
+ readonly detail: string;
31
+ }
32
+
33
+ export interface Diagnosis {
34
+ /** False when something required is missing. */
35
+ readonly ready: boolean;
36
+ readonly platform: string;
37
+ readonly checks: readonly Check[];
38
+ /** Agents installed and therefore usable as constituencies here. */
39
+ readonly agents: readonly string[];
40
+ }
41
+
42
+ /* -------------------------------------------------------------------------- */
43
+ /* Probes */
44
+ /* -------------------------------------------------------------------------- */
45
+
46
+ const run = (command: string, args: readonly string[]): Promise<string | null> =>
47
+ new Promise((resolve) => {
48
+ const child = spawn(command, [...args], { shell: false, stdio: ['ignore', 'pipe', 'ignore'] });
49
+ let output = '';
50
+ child.stdout?.on('data', (c: Buffer) => {
51
+ output += c.toString();
52
+ });
53
+ child.on('close', (code) => resolve(code === 0 ? output.trim() : null));
54
+ child.on('error', () => resolve(null));
55
+ });
56
+
57
+ /**
58
+ * Identify the environment.
59
+ *
60
+ * WSL is reported distinctly from Linux: it is a documented platform row of its
61
+ * own, its auth story differs (API key rather than OAuth in the common setup),
62
+ * and conflating the two would make the matrix lie.
63
+ */
64
+ export const detectPlatform = (): string => {
65
+ const os = platform();
66
+ if (os === 'linux' && /microsoft|wsl/i.test(release())) return 'wsl2';
67
+ if (os === 'linux') return 'linux';
68
+ if (os === 'darwin') return 'macos';
69
+ if (os === 'win32') return 'windows';
70
+ return os;
71
+ };
72
+
73
+ /** True when the process is running inside a container. */
74
+ export const inContainer = async (): Promise<boolean> => {
75
+ if (process.env['POLITIK_IN_CONTAINER'] === '1') return true;
76
+ const cgroup = await run('cat', ['/proc/1/cgroup']);
77
+ if (cgroup !== null && /docker|containerd|kubepods/.test(cgroup)) return true;
78
+ return (await run('test', ['-f', '/.dockerenv'])) !== null;
79
+ };
80
+
81
+ /* -------------------------------------------------------------------------- */
82
+ /* Diagnosis */
83
+ /* -------------------------------------------------------------------------- */
84
+
85
+ const NODE_MINIMUM = 20;
86
+
87
+ /**
88
+ * Diagnose this host.
89
+ *
90
+ * Requirements are deliberately few: Node and git. Everything else is a
91
+ * capability report, because a session with one agent on a laptop is as valid
92
+ * as one with six on a VPS.
93
+ */
94
+ export const diagnose = async (): Promise<Diagnosis> => {
95
+ const checks: Check[] = [];
96
+
97
+ const nodeMajor = Number.parseInt(process.versions.node.split('.')[0] ?? '0', 10);
98
+ checks.push({
99
+ name: 'node',
100
+ status: nodeMajor >= NODE_MINIMUM ? 'ok' : 'fail',
101
+ detail:
102
+ nodeMajor >= NODE_MINIMUM
103
+ ? `v${process.versions.node}`
104
+ : `v${process.versions.node} — Politik requires Node >= ${NODE_MINIMUM}`,
105
+ });
106
+
107
+ const git = await run('git', ['--version']);
108
+ checks.push({
109
+ name: 'git',
110
+ status: git === null ? 'fail' : 'ok',
111
+ // Git is not optional: the repository *is* the session.
112
+ detail: git ?? 'not found — the session repo is the substrate, git is required',
113
+ });
114
+
115
+ const container = await inContainer();
116
+ checks.push({
117
+ name: 'container',
118
+ status: 'ok',
119
+ detail: container ? 'running inside a container' : 'bare metal',
120
+ });
121
+
122
+ // Agents authenticated by OAuth generally cannot complete an interactive
123
+ // login in a headless container; an API key is the documented path there.
124
+ const installed: string[] = [];
125
+ for (const agent of AGENTS) {
126
+ if (await isAvailable(agent)) installed.push(agent.id);
127
+ }
128
+
129
+ checks.push({
130
+ name: 'agents',
131
+ status: installed.length > 0 ? 'ok' : 'warn',
132
+ detail:
133
+ installed.length > 0
134
+ ? `${installed.length} installed: ${installed.join(', ')}`
135
+ : 'none installed — a session needs at least one agent to seat a constituency',
136
+ });
137
+
138
+ if (container && installed.length > 0) {
139
+ const oauthOnly = AGENTS.filter(
140
+ (a: AgentSpec) => installed.includes(a.id) && a.auth_local === 'oauth',
141
+ );
142
+ if (oauthOnly.length > 0) {
143
+ checks.push({
144
+ name: 'auth',
145
+ status: 'warn',
146
+ detail: `in a container, prefer API keys — ${oauthOnly
147
+ .map((a) => a.id)
148
+ .join(', ')} default to OAuth, which cannot complete a browser login headlessly`,
149
+ });
150
+ }
151
+ }
152
+
153
+ const ollama = await run('ollama', ['--version']);
154
+ if (ollama !== null) {
155
+ checks.push({
156
+ name: 'ollama',
157
+ status: 'ok',
158
+ detail: `${ollama} — local inference available, zero cost and zero auth`,
159
+ });
160
+ }
161
+
162
+ return {
163
+ ready: !checks.some((c) => c.status === 'fail'),
164
+ platform: detectPlatform(),
165
+ checks,
166
+ agents: installed,
167
+ };
168
+ };
@@ -0,0 +1,233 @@
1
+ /**
2
+ * First-actor-per-constituency election.
3
+ *
4
+ * Implements the Self-Organization Protocol steps 4-5 and the
5
+ * First-Actor-Per-Constituency Rule (POLITIK-ARCHITECTURE.md).
6
+ *
7
+ * ## Two mechanisms, deliberately not conflated
8
+ *
9
+ * The architecture describes contention at two scopes, and they are different
10
+ * problems with different answers:
11
+ *
12
+ * - **Local (this module):** "On a single machine with multiple agents —
13
+ * local mutex via lockfile." Several agents share a filesystem and would
14
+ * otherwise race to represent the same constituency. First to acquire the
15
+ * lock becomes the Constituency broadcaster; the rest defer.
16
+ *
17
+ * - **Global (not this module):** "Slot claimed atomically via Hansard
18
+ * commit." Across machines, the Hansard is the arbiter — a commit either
19
+ * lands or it does not.
20
+ *
21
+ * Winning the local lock therefore grants the right to *attempt* a claim. It is
22
+ * not the claim. A broadcaster that wins the mutex can still lose the Hansard
23
+ * commit to an agent on another machine, and that is correct.
24
+ *
25
+ * Attribution: Steve Krisjanovs, Cordfuse
26
+ */
27
+
28
+ import { type Role } from './canon.ts';
29
+ import { isEligible, type Envelope } from './envelope.ts';
30
+
31
+ /* -------------------------------------------------------------------------- */
32
+ /* Mutex */
33
+ /* -------------------------------------------------------------------------- */
34
+
35
+ /**
36
+ * The filesystem operations a lockfile mutex needs. Narrow by design so tests
37
+ * can supply an in-memory double and so a caller may substitute a different
38
+ * substrate.
39
+ *
40
+ * `createExclusive` MUST be atomic: it creates the file and fails if it already
41
+ * exists, in one operation. On POSIX this is `open(2)` with `O_CREAT|O_EXCL`
42
+ * (Node's `wx` flag). An implementation that checks-then-writes reintroduces
43
+ * the race this module exists to prevent.
44
+ */
45
+ export interface LockFs {
46
+ /** Create exclusively. Resolves true on success, false if it already exists. */
47
+ createExclusive(path: string, contents: string): Promise<boolean>;
48
+ readFile(path: string): Promise<string | null>;
49
+ remove(path: string): Promise<void>;
50
+ }
51
+
52
+ export interface LockHolder {
53
+ readonly agent: string;
54
+ readonly role: Role;
55
+ readonly session_guid: string;
56
+ readonly acquired_at: string;
57
+ }
58
+
59
+ export interface ElectionOptions {
60
+ readonly fs: LockFs;
61
+ /** Directory holding lockfiles. One per session+constituency. */
62
+ readonly lockDir: string;
63
+ /**
64
+ * A lock older than this is treated as abandoned — the "broadcaster bow-out"
65
+ * case where an agent died without releasing. Null disables reclamation.
66
+ */
67
+ readonly staleAfterMs?: number | null;
68
+ }
69
+
70
+ /** Lockfile path for a session/constituency pair. */
71
+ export const lockPath = (dir: string, sessionGuid: string, role: Role): string =>
72
+ `${dir}/${sessionGuid}.${role}.lock`;
73
+
74
+ /* -------------------------------------------------------------------------- */
75
+ /* Results */
76
+ /* -------------------------------------------------------------------------- */
77
+
78
+ export type ElectionOutcome =
79
+ /** This agent is the Constituency broadcaster. It may attempt the Hansard claim. */
80
+ | { readonly elected: true; readonly holder: LockHolder }
81
+ /** Another agent on this machine holds the constituency. */
82
+ | { readonly elected: false; readonly reason: 'DEFERRED'; readonly holder: LockHolder | null }
83
+ /** This agent does not match the target constituency. */
84
+ | { readonly elected: false; readonly reason: 'NOT_TARGETED' }
85
+ /** The broadcast has no slots left. */
86
+ | { readonly elected: false; readonly reason: 'NO_SLOTS' };
87
+
88
+ /* -------------------------------------------------------------------------- */
89
+ /* Election */
90
+ /* -------------------------------------------------------------------------- */
91
+
92
+ /**
93
+ * Stand for election as this constituency's broadcaster.
94
+ *
95
+ * Order matters: eligibility (steps 2-3) is checked before the lock is touched,
96
+ * so an agent of the wrong constituency never contends for a mutex it has no
97
+ * business holding.
98
+ */
99
+ export const standForElection = async (
100
+ envelope: Envelope,
101
+ agent: string,
102
+ role: Role,
103
+ options: ElectionOptions,
104
+ now: string,
105
+ ): Promise<ElectionOutcome> => {
106
+ if (envelope.target_actor !== role) {
107
+ return { elected: false, reason: 'NOT_TARGETED' };
108
+ }
109
+ if (!isEligible(envelope, role)) {
110
+ return { elected: false, reason: 'NO_SLOTS' };
111
+ }
112
+
113
+ const path = lockPath(options.lockDir, envelope.session_guid, role);
114
+ const holder: LockHolder = {
115
+ agent,
116
+ role,
117
+ session_guid: envelope.session_guid,
118
+ acquired_at: now,
119
+ };
120
+
121
+ if (await options.fs.createExclusive(path, JSON.stringify(holder, null, 2))) {
122
+ return { elected: true, holder };
123
+ }
124
+
125
+ // The lock exists. Three cases: a live broadcaster, one that died, or a
126
+ // lockfile we cannot read at all.
127
+ const existing = await inspectLock(options.fs, path);
128
+
129
+ const reclaimable =
130
+ // A lock nobody can parse must not strand the constituency permanently.
131
+ existing.kind === 'CORRUPT' ||
132
+ // The file vanished between our failed create and this read.
133
+ existing.kind === 'ABSENT' ||
134
+ (existing.kind === 'HELD' && isStale(existing.holder, now, options.staleAfterMs ?? null));
135
+
136
+ if (reclaimable) {
137
+ // Broadcaster bow-out: reclaim. Remove then re-create exclusively, so a
138
+ // third agent racing the same reclamation still loses to whoever wins the
139
+ // atomic create.
140
+ await options.fs.remove(path);
141
+ if (await options.fs.createExclusive(path, JSON.stringify(holder, null, 2))) {
142
+ return { elected: true, holder };
143
+ }
144
+ const after = await inspectLock(options.fs, path);
145
+ return {
146
+ elected: false,
147
+ reason: 'DEFERRED',
148
+ holder: after.kind === 'HELD' ? after.holder : null,
149
+ };
150
+ }
151
+
152
+ return {
153
+ elected: false,
154
+ reason: 'DEFERRED',
155
+ holder: existing.kind === 'HELD' ? existing.holder : null,
156
+ };
157
+ };
158
+
159
+ /**
160
+ * Release the constituency lock — the explicit bow-out.
161
+ *
162
+ * Only the holding agent may release: an agent that releases a lock it does not
163
+ * hold would hand the constituency to a third party mid-work. Returns false if
164
+ * the lock is absent or held by someone else.
165
+ */
166
+ export const bowOut = async (
167
+ envelope: Envelope,
168
+ agent: string,
169
+ role: Role,
170
+ options: ElectionOptions,
171
+ ): Promise<boolean> => {
172
+ const path = lockPath(options.lockDir, envelope.session_guid, role);
173
+ const holder = await readHolder(options.fs, path);
174
+ if (holder === null || holder.agent !== agent) return false;
175
+ await options.fs.remove(path);
176
+ return true;
177
+ };
178
+
179
+ /** Who currently holds this constituency, if anyone. */
180
+ export const currentHolder = async (
181
+ envelope: Envelope,
182
+ role: Role,
183
+ options: ElectionOptions,
184
+ ): Promise<LockHolder | null> =>
185
+ readHolder(options.fs, lockPath(options.lockDir, envelope.session_guid, role));
186
+
187
+ /* -------------------------------------------------------------------------- */
188
+ /* Internals */
189
+ /* -------------------------------------------------------------------------- */
190
+
191
+ /**
192
+ * The three distinguishable states of a lockfile.
193
+ *
194
+ * ABSENT and CORRUPT must not collapse into one "null holder" value: a caller
195
+ * that cannot tell them apart cannot tell "nobody holds this" from "somebody
196
+ * holds this and I cannot read who", and the second case would otherwise block
197
+ * the constituency permanently.
198
+ */
199
+ type LockInspection =
200
+ | { readonly kind: 'HELD'; readonly holder: LockHolder }
201
+ | { readonly kind: 'ABSENT' }
202
+ | { readonly kind: 'CORRUPT' };
203
+
204
+ const inspectLock = async (fs: LockFs, path: string): Promise<LockInspection> => {
205
+ const raw = await fs.readFile(path);
206
+ if (raw === null) return { kind: 'ABSENT' };
207
+ try {
208
+ const parsed: unknown = JSON.parse(raw);
209
+ if (typeof parsed !== 'object' || parsed === null) return { kind: 'CORRUPT' };
210
+ const holder = parsed as LockHolder;
211
+ if (typeof holder.agent !== 'string' || holder.agent === '') return { kind: 'CORRUPT' };
212
+ return { kind: 'HELD', holder };
213
+ } catch {
214
+ return { kind: 'CORRUPT' };
215
+ }
216
+ };
217
+
218
+ const readHolder = async (fs: LockFs, path: string): Promise<LockHolder | null> => {
219
+ const inspection = await inspectLock(fs, path);
220
+ return inspection.kind === 'HELD' ? inspection.holder : null;
221
+ };
222
+
223
+ const isStale = (
224
+ holder: LockHolder,
225
+ now: string,
226
+ staleAfterMs: number | null,
227
+ ): boolean => {
228
+ if (staleAfterMs === null) return false;
229
+ const acquired = Date.parse(holder.acquired_at);
230
+ const current = Date.parse(now);
231
+ if (Number.isNaN(acquired) || Number.isNaN(current)) return false;
232
+ return current - acquired > staleAfterMs;
233
+ };
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Broadcast envelope — parser and serializer.
3
+ *
4
+ * The self-describing motion packet that travels the transport
5
+ * (POLITIK-ARCHITECTURE.md § BROADCAST ENVELOPE):
6
+ *
7
+ * # [SESSION-GUID]
8
+ * ## target-actor: OPERATOR
9
+ * ## slots-remaining: 3
10
+ * ## protocol: parliamentary
11
+ * ## prompt: |
12
+ * Review the authentication refactor in motion-003
13
+ * and file your assessment as a PR review.
14
+ *
15
+ * The format is markdown with heading-keys, not YAML — an H1 carrying the
16
+ * session GUID, then `## key: value` lines, with `|` introducing an indented
17
+ * block scalar. This module implements that shape and nothing more.
18
+ *
19
+ * The envelope is an *ephemeral nudge*. Transport may drop it with no loss:
20
+ * the Hansard in the session repo is the durable, ordered truth, and peers
21
+ * fall back to reading the repo. Nothing here is authoritative.
22
+ *
23
+ * Attribution: Steve Krisjanovs, Cordfuse
24
+ */
25
+
26
+ import { isRole, type Role } from './canon.ts';
27
+
28
+ /* -------------------------------------------------------------------------- */
29
+ /* Shape */
30
+ /* -------------------------------------------------------------------------- */
31
+
32
+ export interface Envelope {
33
+ /** Session GUID from the H1. Identifies which proceeding this belongs to. */
34
+ readonly session_guid: string;
35
+ /** Constituency the broadcast addresses. */
36
+ readonly target_actor: Role;
37
+ /** Remaining slots. An agent stands down at zero. */
38
+ readonly slots_remaining: number;
39
+ /** Protocol name, for the agent's vocabulary translation. */
40
+ readonly protocol: string;
41
+ /** The instruction the spawned agent executes. */
42
+ readonly prompt: string;
43
+ /**
44
+ * Any `## key: value` the spec does not name, preserved verbatim.
45
+ * The architecture shows four fields but does not declare the set closed, so
46
+ * unknown keys are carried rather than dropped or rejected.
47
+ */
48
+ readonly extensions: Readonly<Record<string, string>>;
49
+ }
50
+
51
+ export interface EnvelopeIssue {
52
+ readonly field: string;
53
+ readonly message: string;
54
+ }
55
+
56
+ export type EnvelopeParseResult =
57
+ | { readonly ok: true; readonly envelope: Envelope }
58
+ | { readonly ok: false; readonly issues: readonly EnvelopeIssue[] };
59
+
60
+ /* -------------------------------------------------------------------------- */
61
+ /* Parse */
62
+ /* -------------------------------------------------------------------------- */
63
+
64
+ const H1 = /^#\s+(?:\[(.+?)\]|(\S.*?))\s*$/;
65
+ const FIELD = /^##\s+([A-Za-z0-9_-]+)\s*:\s*(.*)$/;
66
+
67
+ /** Canonical field keys, normalised from the hyphenated wire form. */
68
+ const normalise = (key: string): string => key.toLowerCase().replace(/-/g, '_');
69
+
70
+ /**
71
+ * Parse a broadcast envelope.
72
+ *
73
+ * Block scalars (`key: |`) consume every subsequent line more indented than the
74
+ * `##` marker, stopping at the next field or heading. Common indentation is
75
+ * stripped so the prompt reads as written.
76
+ */
77
+ export const parseEnvelope = (source: string): EnvelopeParseResult => {
78
+ const issues: EnvelopeIssue[] = [];
79
+ const lines = source.replace(/\r\n/g, '\n').split('\n');
80
+
81
+ let guid = '';
82
+ const fields = new Map<string, string>();
83
+
84
+ for (let i = 0; i < lines.length; i += 1) {
85
+ const line = lines[i] ?? '';
86
+
87
+ if (guid === '' && H1.test(line)) {
88
+ const match = H1.exec(line);
89
+ guid = (match?.[1] ?? match?.[2] ?? '').trim();
90
+ continue;
91
+ }
92
+
93
+ const field = FIELD.exec(line);
94
+ if (!field) continue;
95
+
96
+ const key = normalise(field[1] ?? '');
97
+ const inline = (field[2] ?? '').trim();
98
+
99
+ if (inline !== '|') {
100
+ fields.set(key, inline);
101
+ continue;
102
+ }
103
+
104
+ // Block scalar: gather following lines until the next field or heading.
105
+ const block: string[] = [];
106
+ let j = i + 1;
107
+ for (; j < lines.length; j += 1) {
108
+ const next = lines[j] ?? '';
109
+ if (FIELD.test(next) || H1.test(next)) break;
110
+ if (next.trim() === '' && block.length === 0) continue;
111
+ block.push(next);
112
+ }
113
+ while (block.length > 0 && (block.at(-1) ?? '').trim() === '') block.pop();
114
+
115
+ const indents = block
116
+ .filter((l) => l.trim() !== '')
117
+ .map((l) => (/^(\s*)/.exec(l)?.[1] ?? '').length);
118
+ const strip = indents.length > 0 ? Math.min(...indents) : 0;
119
+
120
+ fields.set(key, block.map((l) => l.slice(strip)).join('\n'));
121
+ i = j - 1;
122
+ }
123
+
124
+ if (guid === '') {
125
+ issues.push({
126
+ field: 'session_guid',
127
+ message: 'envelope must open with an H1 carrying the session GUID',
128
+ });
129
+ }
130
+
131
+ const target = fields.get('target_actor') ?? '';
132
+ if (target === '') {
133
+ issues.push({ field: 'target_actor', message: 'required' });
134
+ } else if (!isRole(target)) {
135
+ issues.push({
136
+ field: 'target_actor',
137
+ message: `not a CANON role: ${target}`,
138
+ });
139
+ }
140
+
141
+ const slotsRaw = fields.get('slots_remaining') ?? '';
142
+ const slots = Number(slotsRaw);
143
+ if (slotsRaw === '') {
144
+ issues.push({ field: 'slots_remaining', message: 'required' });
145
+ } else if (!Number.isInteger(slots) || slots < 0) {
146
+ issues.push({
147
+ field: 'slots_remaining',
148
+ message: `must be a non-negative integer, got "${slotsRaw}"`,
149
+ });
150
+ }
151
+
152
+ const protocol = fields.get('protocol') ?? '';
153
+ if (protocol === '') issues.push({ field: 'protocol', message: 'required' });
154
+
155
+ const prompt = fields.get('prompt') ?? '';
156
+ if (prompt.trim() === '') issues.push({ field: 'prompt', message: 'required' });
157
+
158
+ if (issues.length > 0) return { ok: false, issues };
159
+
160
+ const known = new Set(['target_actor', 'slots_remaining', 'protocol', 'prompt']);
161
+ const extensions: Record<string, string> = {};
162
+ for (const [key, value] of fields) {
163
+ if (!known.has(key)) extensions[key] = value;
164
+ }
165
+
166
+ return {
167
+ ok: true,
168
+ envelope: {
169
+ session_guid: guid,
170
+ target_actor: target as Role,
171
+ slots_remaining: slots,
172
+ protocol,
173
+ prompt,
174
+ extensions,
175
+ },
176
+ };
177
+ };
178
+
179
+ /* -------------------------------------------------------------------------- */
180
+ /* Serialize */
181
+ /* -------------------------------------------------------------------------- */
182
+
183
+ /** Render an envelope in the wire format. Round-trips with `parseEnvelope`. */
184
+ export const serializeEnvelope = (envelope: Envelope): string => {
185
+ const lines = [
186
+ `# [${envelope.session_guid}]`,
187
+ `## target-actor: ${envelope.target_actor}`,
188
+ `## slots-remaining: ${envelope.slots_remaining}`,
189
+ `## protocol: ${envelope.protocol}`,
190
+ ];
191
+
192
+ for (const [key, value] of Object.entries(envelope.extensions)) {
193
+ lines.push(`## ${key.replace(/_/g, '-')}: ${value}`);
194
+ }
195
+
196
+ lines.push('## prompt: |');
197
+ for (const line of envelope.prompt.split('\n')) {
198
+ lines.push(line === '' ? '' : ` ${line}`);
199
+ }
200
+
201
+ return `${lines.join('\n')}\n`;
202
+ };
203
+
204
+ /* -------------------------------------------------------------------------- */
205
+ /* Self-organization */
206
+ /* -------------------------------------------------------------------------- */
207
+
208
+ /**
209
+ * Steps 2 and 3 of the Self-Organization Protocol: does this agent match the
210
+ * target constituency, and are slots available?
211
+ *
212
+ * A true result only makes the agent *eligible*. The slot is not held until it
213
+ * is claimed atomically via a Hansard commit (step 5) — this function performs
214
+ * no claim and grants no exclusivity.
215
+ */
216
+ export const isEligible = (envelope: Envelope, actorRole: Role): boolean =>
217
+ envelope.target_actor === actorRole && envelope.slots_remaining > 0;
218
+
219
+ /** Decrement the slot count after a claim is committed (step 7). */
220
+ export const claimSlot = (envelope: Envelope): Envelope => ({
221
+ ...envelope,
222
+ slots_remaining: Math.max(0, envelope.slots_remaining - 1),
223
+ });