@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/charter.ts ADDED
@@ -0,0 +1,545 @@
1
+ /**
2
+ * CHARTER.md — parser and Writ Drop validator.
3
+ *
4
+ * The Charter is the sovereign law of a session: markdown with a single YAML
5
+ * frontmatter block. The frontmatter carries every machine-read field; the
6
+ * markdown body carries human-readable Standing Orders which the engine never
7
+ * parses.
8
+ *
9
+ * Schema and the eight validation rules are fixed by ADR-0002 (with rules 5-7
10
+ * refined by ADR-0004). This module implements them and invents nothing.
11
+ *
12
+ * Attribution: Steve Krisjanovs, Cordfuse
13
+ */
14
+
15
+ import { parse as parseYaml } from 'yaml';
16
+
17
+ import {
18
+ isMergeStrategy,
19
+ isRole,
20
+ type MergeStrategy,
21
+ type Role,
22
+ } from './canon.ts';
23
+ import type { ProtocolRecordMode } from './protocol.ts';
24
+ import { isResolution, isExitPolicy, type Resolution, type ExitPolicy } from './division.ts';
25
+ import { isTerminationPolicy, type TerminationPolicy } from './prorogation.ts';
26
+
27
+ /* -------------------------------------------------------------------------- */
28
+ /* Schema */
29
+ /* -------------------------------------------------------------------------- */
30
+
31
+ export type EscalationSetting = 'enabled' | 'disabled';
32
+ export type LedgerVisibility = 'public' | 'private';
33
+
34
+ /**
35
+ * Record mode of the resolved protocol.
36
+ *
37
+ * Re-exported from the protocol layer rather than redeclared. This module
38
+ * previously declared its own `'centralised' | 'distributed'` — a vocabulary
39
+ * that existed nowhere else, and which could not represent `anchored`, the mode
40
+ * 8 of the 10 shipped protocols declare. Rule 5 was therefore checking a value
41
+ * most real protocols could not express.
42
+ */
43
+ export type RecordMode = ProtocolRecordMode;
44
+
45
+ export interface Endurance {
46
+ readonly max_motions: number | null;
47
+ readonly max_cost_usd: number | null;
48
+ /**
49
+ * Spend at which the Speaker is warned, before the ceiling stops the session.
50
+ * The low-fuel light: a proceeding that dies at its ceiling with no warning
51
+ * gives nobody the chance to extend the budget or wind down gracefully.
52
+ */
53
+ readonly cost_warning_usd: number | null;
54
+ /** What a breached ceiling does. */
55
+ readonly deadline_action: 'escalate' | 'suspend' | 'dissolve';
56
+ }
57
+
58
+ export interface SessionBlock {
59
+ readonly quorum: number;
60
+ readonly escalation: EscalationSetting;
61
+ readonly heartbeat_timeout_hours: number;
62
+ /** What a stale heartbeat does. RUNTIME.md § Session Heartbeat. */
63
+ readonly stale_action: 'suspend' | 'dissolve';
64
+ /** Hours between STATE_SNAPSHOT commits, or null for none. */
65
+ readonly checkpoint_interval_hours: number | null;
66
+ readonly deadline: string | null;
67
+ readonly merge_strategy: MergeStrategy;
68
+ readonly assent: Role;
69
+ readonly endurance: Endurance;
70
+ }
71
+
72
+ export interface LedgerBlock {
73
+ readonly enabled: boolean;
74
+ readonly visibility: LedgerVisibility;
75
+ readonly path: string;
76
+ }
77
+
78
+ export interface ModelRequirement {
79
+ readonly required: string | null;
80
+ readonly preferred: string | null;
81
+ readonly knowledge_cutoff_minimum: string | null;
82
+ }
83
+
84
+ export interface HardSkills {
85
+ readonly required: readonly string[];
86
+ readonly excluded: readonly string[];
87
+ }
88
+
89
+ export interface Constituency {
90
+ readonly role: Role;
91
+ /**
92
+ * Registry id of the agent seated here, when the seat is machine-filled.
93
+ *
94
+ * Absent means the seat is human-filled. This is the field that makes the
95
+ * AUTHORITY-is-human rule checkable at all: without somewhere for a Charter
96
+ * to declare a machine, the rule could not be enforced and was — for the
97
+ * whole of Phases 2-7 — a comment asserting a check that did not exist.
98
+ */
99
+ readonly agent: string | null;
100
+ readonly slots: number;
101
+ readonly auto_demotion: boolean;
102
+ readonly hard_skills: HardSkills;
103
+ readonly model: ModelRequirement;
104
+ readonly mandate_alignment: string | null;
105
+ }
106
+
107
+ /**
108
+ * Constitutional-capture mitigations (RUNTIME.md § Constitutional Capture).
109
+ *
110
+ * These were implemented in `src/crisis.ts` but never parsed, so the YAML the
111
+ * documentation shows was inert — a Speaker could declare a Witness Council and
112
+ * get nothing. Parsed here so the declaration has effect.
113
+ */
114
+ export interface Governance {
115
+ readonly witness_council: {
116
+ readonly enabled: boolean;
117
+ readonly roles: readonly Role[];
118
+ };
119
+ readonly consensus_suspension: {
120
+ readonly enabled: boolean;
121
+ readonly threshold: number;
122
+ };
123
+ }
124
+
125
+ export interface Charter {
126
+ readonly charter_version: string;
127
+ readonly protocol: string;
128
+ readonly inherits_from: string | null;
129
+ readonly session: SessionBlock;
130
+ readonly ledger: LedgerBlock;
131
+ readonly minimum_cast: Readonly<Partial<Record<Role, number>>>;
132
+ readonly domain_veto: readonly Role[];
133
+ /** Protocol override points (ADR-0007). Absent selections default to the
134
+ * parliamentary behavior, so an older Charter is unchanged. */
135
+ readonly mechanics: {
136
+ readonly resolution: Resolution;
137
+ readonly exit: ExitPolicy;
138
+ readonly termination: TerminationPolicy;
139
+ };
140
+ readonly governance: Governance;
141
+ /** PATH_A auto-recovery policy (RUNTIME.md § Three Resolution Paths). */
142
+ readonly fault_handling: {
143
+ readonly auto_retry_max: number;
144
+ readonly auto_retry_delay_minutes: number;
145
+ };
146
+ readonly constituencies: readonly Constituency[];
147
+ /** Unparsed Standing Orders prose. Carried, never interpreted. */
148
+ readonly body: string;
149
+ }
150
+
151
+ /* -------------------------------------------------------------------------- */
152
+ /* Results */
153
+ /* -------------------------------------------------------------------------- */
154
+
155
+ export interface CharterIssue {
156
+ /** Dotted path to the offending field, or `frontmatter` for structural faults. */
157
+ readonly field: string;
158
+ readonly message: string;
159
+ /** ADR rule number this enforces, when it maps to one. */
160
+ readonly rule?: number;
161
+ }
162
+
163
+ export type ParseResult =
164
+ | { readonly ok: true; readonly charter: Charter }
165
+ | { readonly ok: false; readonly issues: readonly CharterIssue[] };
166
+
167
+ export interface ValidationResult {
168
+ /** False means SESSION_INVALID — the session never opens. */
169
+ readonly valid: boolean;
170
+ readonly issues: readonly CharterIssue[];
171
+ }
172
+
173
+ /** Facts about the resolved protocol needed by rules 2 and 5. */
174
+ export interface ProtocolContext {
175
+ readonly name: string;
176
+ readonly record_mode?: RecordMode;
177
+ }
178
+
179
+ /* -------------------------------------------------------------------------- */
180
+ /* Frontmatter */
181
+ /* -------------------------------------------------------------------------- */
182
+
183
+ const FRONTMATTER = /^?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/;
184
+
185
+ /** Split a CHARTER.md into its YAML frontmatter and prose body. */
186
+ export const splitFrontmatter = (
187
+ source: string,
188
+ ): { yaml: string; body: string } | null => {
189
+ const match = FRONTMATTER.exec(source);
190
+ if (!match) return null;
191
+ return { yaml: match[1] ?? '', body: (match[2] ?? '').trim() };
192
+ };
193
+
194
+ /* -------------------------------------------------------------------------- */
195
+ /* Coercion helpers */
196
+ /* -------------------------------------------------------------------------- */
197
+
198
+ const isObject = (v: unknown): v is Record<string, unknown> =>
199
+ typeof v === 'object' && v !== null && !Array.isArray(v);
200
+
201
+ const asStringArray = (v: unknown): string[] =>
202
+ Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
203
+
204
+ const asNumberOrNull = (v: unknown): number | null =>
205
+ typeof v === 'number' && Number.isFinite(v) ? v : null;
206
+
207
+ const asStringOrNull = (v: unknown): string | null =>
208
+ typeof v === 'string' && v.length > 0 ? v : null;
209
+
210
+ /* -------------------------------------------------------------------------- */
211
+ /* Parse */
212
+ /* -------------------------------------------------------------------------- */
213
+
214
+ /**
215
+ * Parse CHARTER.md source into a Charter.
216
+ *
217
+ * Rule 1: malformed YAML or a missing frontmatter block is a structural fault —
218
+ * the caller must treat it as SESSION_INVALID. Parsing applies documented
219
+ * defaults but performs no governance validation; call `validateCharter` for
220
+ * that.
221
+ */
222
+ export const parseCharter = (source: string): ParseResult => {
223
+ const split = splitFrontmatter(source);
224
+ if (!split) {
225
+ return {
226
+ ok: false,
227
+ issues: [
228
+ {
229
+ field: 'frontmatter',
230
+ message: 'CHARTER.md must open with a YAML frontmatter block delimited by ---',
231
+ rule: 1,
232
+ },
233
+ ],
234
+ };
235
+ }
236
+
237
+ let raw: unknown;
238
+ try {
239
+ raw = parseYaml(split.yaml);
240
+ } catch (err) {
241
+ return {
242
+ ok: false,
243
+ issues: [
244
+ {
245
+ field: 'frontmatter',
246
+ message: `malformed YAML: ${err instanceof Error ? err.message : String(err)}`,
247
+ rule: 1,
248
+ },
249
+ ],
250
+ };
251
+ }
252
+
253
+ if (!isObject(raw)) {
254
+ return {
255
+ ok: false,
256
+ issues: [
257
+ { field: 'frontmatter', message: 'frontmatter must be a YAML mapping', rule: 1 },
258
+ ],
259
+ };
260
+ }
261
+
262
+ const session = isObject(raw['session']) ? raw['session'] : {};
263
+ const endurance = isObject(session['endurance']) ? session['endurance'] : {};
264
+ const ledger = isObject(raw['ledger']) ? raw['ledger'] : {};
265
+
266
+ const minimum_cast: Partial<Record<Role, number>> = {};
267
+ if (isObject(raw['minimum_cast'])) {
268
+ for (const [key, value] of Object.entries(raw['minimum_cast'])) {
269
+ if (isRole(key) && typeof value === 'number') minimum_cast[key] = value;
270
+ }
271
+ }
272
+
273
+ const constituencies: Constituency[] = [];
274
+ if (Array.isArray(raw['constituencies'])) {
275
+ for (const entry of raw['constituencies']) {
276
+ if (!isObject(entry)) continue;
277
+ const hard = isObject(entry['hard_skills']) ? entry['hard_skills'] : {};
278
+ const model = isObject(entry['model']) ? entry['model'] : {};
279
+ constituencies.push({
280
+ role: (isRole(entry['role']) ? entry['role'] : 'MEMBER') as Role,
281
+ agent: asStringOrNull(entry['agent']),
282
+ slots: typeof entry['slots'] === 'number' ? entry['slots'] : 1,
283
+ auto_demotion: entry['auto_demotion'] === true,
284
+ hard_skills: {
285
+ required: asStringArray(hard['required']),
286
+ excluded: asStringArray(hard['excluded']),
287
+ },
288
+ model: {
289
+ required: asStringOrNull(model['required']),
290
+ preferred: asStringOrNull(model['preferred']),
291
+ knowledge_cutoff_minimum: asStringOrNull(model['knowledge_cutoff_minimum']),
292
+ },
293
+ mandate_alignment: asStringOrNull(entry['mandate_alignment']),
294
+ });
295
+ }
296
+ }
297
+
298
+ const visibility: LedgerVisibility =
299
+ ledger['visibility'] === 'private' ? 'private' : 'public';
300
+
301
+ const charter: Charter = {
302
+ charter_version: typeof raw['charter_version'] === 'string' ? raw['charter_version'] : '',
303
+ protocol: typeof raw['protocol'] === 'string' ? raw['protocol'] : '',
304
+ inherits_from: asStringOrNull(raw['inherits_from']),
305
+ session: {
306
+ quorum: typeof session['quorum'] === 'number' ? session['quorum'] : 1,
307
+ escalation: session['escalation'] === 'disabled' ? 'disabled' : 'enabled',
308
+ heartbeat_timeout_hours:
309
+ typeof session['heartbeat_timeout_hours'] === 'number'
310
+ ? session['heartbeat_timeout_hours']
311
+ : 4,
312
+ deadline: asStringOrNull(session['deadline']),
313
+ // Defaults per ADR-0002 frontmatter comments.
314
+ merge_strategy: isMergeStrategy(session['merge_strategy'])
315
+ ? session['merge_strategy']
316
+ : 'merge_commit',
317
+ // Default only when absent. A present-but-invalid value is preserved so
318
+ // Writ Drop rule 7 can reject it — coercing it to AUTHORITY here masked the
319
+ // rule and let a bad assent silently open a session (AUDIT #8).
320
+ assent: session['assent'] === undefined ? 'AUTHORITY' : (session['assent'] as Role),
321
+ stale_action: session['stale_action'] === 'dissolve' ? 'dissolve' : 'suspend',
322
+ checkpoint_interval_hours: asNumberOrNull(session['checkpoint_interval_hours']),
323
+ endurance: {
324
+ max_motions: asNumberOrNull(endurance['max_motions']),
325
+ max_cost_usd: asNumberOrNull(endurance['max_cost_usd']),
326
+ // RUNTIME.md shows these under `session:` as well as under
327
+ // `session.endurance:`. Read both, because a Charter written from the
328
+ // documentation should work rather than be silently ignored.
329
+ cost_warning_usd:
330
+ asNumberOrNull(endurance['cost_warning_usd']) ??
331
+ asNumberOrNull(session['cost_warning_usd']),
332
+ deadline_action:
333
+ session['deadline_action'] === 'dissolve'
334
+ ? 'dissolve'
335
+ : session['deadline_action'] === 'suspend'
336
+ ? 'suspend'
337
+ : 'escalate',
338
+ },
339
+ },
340
+ ledger: {
341
+ enabled: ledger['enabled'] !== false,
342
+ visibility,
343
+ path:
344
+ typeof ledger['path'] === 'string'
345
+ ? ledger['path']
346
+ : visibility === 'private'
347
+ ? '.politik/LEDGER.md'
348
+ : 'LEDGER.md',
349
+ },
350
+ minimum_cast,
351
+ domain_veto: asStringArray(raw['domain_veto']).filter(isRole),
352
+ mechanics: (() => {
353
+ const m = isObject(raw['mechanics']) ? raw['mechanics'] : {};
354
+ return {
355
+ resolution: isResolution(m['resolution']) ? m['resolution'] : 'majority',
356
+ exit: isExitPolicy(m['exit']) ? m['exit'] : 'division',
357
+ termination: isTerminationPolicy(m['termination']) ? m['termination'] : 'objective',
358
+ };
359
+ })(),
360
+ fault_handling: (() => {
361
+ const f = isObject(raw['fault_handling']) ? raw['fault_handling'] : {};
362
+ const max = asNumberOrNull(f['auto_retry_max']);
363
+ const delay = asNumberOrNull(f['auto_retry_delay_minutes']);
364
+ return {
365
+ // RUNTIME.md's documented defaults. A Charter that says nothing gets
366
+ // retry rather than an immediate escalation, because a rate limit is
367
+ // not something to wake a Speaker for.
368
+ auto_retry_max: max !== null && max >= 0 ? max : 3,
369
+ auto_retry_delay_minutes: delay !== null && delay >= 0 ? delay : 5,
370
+ };
371
+ })(),
372
+ governance: (() => {
373
+ const g = isObject(raw['governance']) ? raw['governance'] : {};
374
+ const witness = isObject(g['witness_council']) ? g['witness_council'] : {};
375
+ const consensus = isObject(g['consensus_suspension']) ? g['consensus_suspension'] : {};
376
+ const roles = asStringArray(witness['roles']).filter(isRole);
377
+ return {
378
+ witness_council: {
379
+ enabled: witness['enabled'] === true && roles.length > 0,
380
+ roles,
381
+ },
382
+ consensus_suspension: {
383
+ // Defaults to enabled: a constitutional protocol that silently had no
384
+ // capture mechanism would be worse than one that declares it off.
385
+ enabled: consensus['enabled'] !== false,
386
+ threshold:
387
+ typeof consensus['threshold'] === 'number' &&
388
+ consensus['threshold'] > 0 &&
389
+ consensus['threshold'] <= 1
390
+ ? consensus['threshold']
391
+ : 0.75,
392
+ },
393
+ };
394
+ })(),
395
+ constituencies,
396
+ body: split.body,
397
+ };
398
+
399
+ return { ok: true, charter };
400
+ };
401
+
402
+ /* -------------------------------------------------------------------------- */
403
+ /* Validate — Writ Drop */
404
+ /* -------------------------------------------------------------------------- */
405
+
406
+ /**
407
+ * Apply the Writ Drop validation rules (ADR-0002 § Validation rules).
408
+ *
409
+ * A failing result means SESSION_INVALID: the session never opens and the
410
+ * issues are committed to the Hansard naming what failed.
411
+ *
412
+ * `protocol` is optional. Rule 2 (protocol resolution) and rule 5 (squash vs
413
+ * distributed record mode) are only enforced when the resolved protocol is
414
+ * supplied — the caller resolves `.politik/protocol.yml`, not this module.
415
+ */
416
+ export const validateCharter = (
417
+ charter: Charter,
418
+ protocol?: ProtocolContext,
419
+ ): ValidationResult => {
420
+ const issues: CharterIssue[] = [];
421
+
422
+ if (charter.charter_version.length === 0) {
423
+ issues.push({ field: 'charter_version', message: 'required' });
424
+ }
425
+
426
+ // Rule 2 — resolve protocol.
427
+ if (charter.protocol.length === 0) {
428
+ issues.push({ field: 'protocol', message: 'required', rule: 2 });
429
+ } else if (protocol && protocol.name !== charter.protocol) {
430
+ issues.push({
431
+ field: 'protocol',
432
+ message: `does not resolve: charter declares "${charter.protocol}", resolved protocol is "${protocol.name}"`,
433
+ rule: 2,
434
+ });
435
+ }
436
+
437
+ if (!Number.isInteger(charter.session.quorum) || charter.session.quorum < 1) {
438
+ issues.push({ field: 'session.quorum', message: 'must be an integer >= 1' });
439
+ }
440
+
441
+ // Rule 4 — AUTHORITY can never be dialled to zero.
442
+ const requiredAuthority = charter.minimum_cast.AUTHORITY;
443
+ if (requiredAuthority !== undefined && requiredAuthority < 1) {
444
+ issues.push({
445
+ field: 'minimum_cast.AUTHORITY',
446
+ message: 'may never be overridden to 0 — a session with no Speaker cannot proceed',
447
+ rule: 4,
448
+ });
449
+ }
450
+
451
+ // The one hard constitutional rule (POLITIK-ARCHITECTURE.md § Roles):
452
+ // AUTHORITY is always human. A Charter declaring a machine as AUTHORITY is
453
+ // invalid and the session must never open.
454
+ //
455
+ // The rationale is accountability, not capability: a machine that captures a
456
+ // session cannot be held responsible for it, and every other safeguard in the
457
+ // framework assumes someone can be.
458
+ for (const [i, c] of charter.constituencies.entries()) {
459
+ if (c.role === 'AUTHORITY' && c.agent !== null) {
460
+ issues.push({
461
+ field: `constituencies[${i}].agent`,
462
+ message: `AUTHORITY is always human — this Charter seats the agent "${c.agent}" as Speaker`,
463
+ });
464
+ }
465
+ }
466
+
467
+ // Rule 3 — declared constituencies must satisfy minimum_cast.
468
+ //
469
+ // ADR-0002 says "assigned constituencies", which reads ambiguously. It means
470
+ // the seats this Charter assigns, not actors sitting in them: Writ Drop runs
471
+ // *before* the session opens, so no actor has been seated yet and the other
472
+ // reading would make the rule uncheckable at the only moment it runs.
473
+ // Whether seats are actually filled is a runtime question, and quorum answers
474
+ // it at Division time.
475
+ const slotsByRole = new Map<Role, number>();
476
+ for (const c of charter.constituencies) {
477
+ slotsByRole.set(c.role, (slotsByRole.get(c.role) ?? 0) + c.slots);
478
+ }
479
+ for (const [role, required] of Object.entries(charter.minimum_cast) as [Role, number][]) {
480
+ const assigned = slotsByRole.get(role) ?? 0;
481
+ if (assigned < required) {
482
+ issues.push({
483
+ field: `minimum_cast.${role}`,
484
+ message: `shortfall: requires ${required}, constituencies declare ${assigned}`,
485
+ rule: 3,
486
+ });
487
+ }
488
+ }
489
+
490
+ // Rule 5 — squash destroys per-commit attribution that distributed guarantees.
491
+ if (
492
+ charter.session.merge_strategy === 'squash' &&
493
+ protocol?.record_mode === 'distributed'
494
+ ) {
495
+ issues.push({
496
+ field: 'session.merge_strategy',
497
+ message: 'squash is rejected when protocol.record_mode is distributed — it destroys per-commit attribution',
498
+ rule: 5,
499
+ });
500
+ }
501
+
502
+ // Rule 6 — fast_forward leaves no merge node, so no evidence of a Division.
503
+ if (charter.session.merge_strategy === 'fast_forward' && charter.session.quorum !== 1) {
504
+ issues.push({
505
+ field: 'session.merge_strategy',
506
+ message: `fast_forward requires session.quorum: 1 (declared ${charter.session.quorum}) — it leaves no merge node to evidence a Division`,
507
+ rule: 6,
508
+ });
509
+ }
510
+
511
+ // Rule 7 — assent must name a CANON role. Parsing now defaults only when the
512
+ // key is absent, so a present-but-invalid value reaches here and is rejected.
513
+ if (!isRole(charter.session.assent)) {
514
+ issues.push({
515
+ field: 'session.assent',
516
+ message: 'must name a CANON role',
517
+ rule: 7,
518
+ });
519
+ }
520
+
521
+ for (const [i, c] of charter.constituencies.entries()) {
522
+ if (!Number.isInteger(c.slots) || c.slots < 1) {
523
+ issues.push({
524
+ field: `constituencies[${i}].slots`,
525
+ message: 'must be an integer >= 1',
526
+ });
527
+ }
528
+ }
529
+
530
+ return { valid: issues.length === 0, issues };
531
+ };
532
+
533
+ /**
534
+ * Parse and validate in one step — the Writ Drop entry point.
535
+ * Rule 8: on pass, the caller sets `STATE.json.state = CONVENED`.
536
+ */
537
+ export const writDrop = (
538
+ source: string,
539
+ protocol?: ProtocolContext,
540
+ ): ValidationResult & { readonly charter?: Charter } => {
541
+ const parsed = parseCharter(source);
542
+ if (!parsed.ok) return { valid: false, issues: parsed.issues };
543
+ const result = validateCharter(parsed.charter, protocol);
544
+ return { ...result, charter: parsed.charter };
545
+ };