@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,211 @@
1
+ /**
2
+ * CONFLICT — two Motions touching the same lines.
3
+ *
4
+ * The primitive exists to draw one line, and the whole module is built around
5
+ * keeping it (POLITIK-ARCHITECTURE.md § Session Primitives, ADR-0004
6
+ * Proposal 3):
7
+ *
8
+ * CONFLICT — mechanical, routine, resolved by any actor holding WRITE.
9
+ * **Not a governance failure.**
10
+ * DEADLOCK — no valid Division outcome. A governance failure.
11
+ *
12
+ * A merge conflict is an ordinary event in concurrent work. Treating it as a
13
+ * fault would suspend sessions for something two Ministers can settle between
14
+ * themselves, train actors to escalate routine work, and bury the genuinely
15
+ * undecidable cases in noise. So nothing here suspends, nothing escalates, and
16
+ * nothing reaches for AUTHORITY.
17
+ *
18
+ * The temptation is to reuse the fault machinery because the plumbing is
19
+ * similar. That would be the error: it is the *governance meaning* that
20
+ * differs, not the mechanics.
21
+ *
22
+ * Attribution: Steve Krisjanovs, Cordfuse
23
+ */
24
+
25
+ import { VERBS, type Role, type Verb } from './canon.ts';
26
+ import { appendEntry, parseEntries, type HansardEntry } from './hansard.ts';
27
+
28
+ /* -------------------------------------------------------------------------- */
29
+ /* Detection */
30
+ /* -------------------------------------------------------------------------- */
31
+
32
+ export interface MotionFiles {
33
+ readonly motion: string;
34
+ readonly files: readonly string[];
35
+ }
36
+
37
+ export interface Conflict {
38
+ readonly motions: readonly string[];
39
+ /** Files both Motions touch. */
40
+ readonly files: readonly string[];
41
+ }
42
+
43
+ /**
44
+ * Which Motions touch the same files?
45
+ *
46
+ * File-level overlap, not line-level. Two Motions editing distant parts of one
47
+ * file usually merge cleanly, so this over-reports — but a CONFLICT costs
48
+ * nothing to record and resolve, while a missed one surfaces later as a failed
49
+ * merge with no explanation in the record. Over-reporting a routine event is
50
+ * the cheaper mistake.
51
+ */
52
+ export const detectConflicts = (motions: readonly MotionFiles[]): readonly Conflict[] => {
53
+ const conflicts: Conflict[] = [];
54
+
55
+ for (let i = 0; i < motions.length; i += 1) {
56
+ for (let j = i + 1; j < motions.length; j += 1) {
57
+ const a = motions[i];
58
+ const b = motions[j];
59
+ if (a === undefined || b === undefined) continue;
60
+
61
+ const shared = a.files.filter((f) => b.files.includes(f));
62
+ if (shared.length > 0) {
63
+ conflicts.push({ motions: [a.motion, b.motion], files: shared });
64
+ }
65
+ }
66
+ }
67
+
68
+ return conflicts;
69
+ };
70
+
71
+ /**
72
+ * Detect conflicts directly from the record.
73
+ *
74
+ * Reads every entry that declares "Files touched" and treats each as a unit of
75
+ * work. A Motion id names the unit when present; an agent turn carries none, so
76
+ * it is identified by actor+timestamp. Keying by the file list instead — as an
77
+ * earlier version did — collapsed two turns that touched the *same* file into
78
+ * one unit, and the conflict between them, the very overlap this detects, was
79
+ * lost. This is governance logic, so it lives here rather than in the CLI.
80
+ */
81
+ export const detectRecordConflicts = (hansard: string): readonly Conflict[] => {
82
+ const touched = new Map<string, string[]>();
83
+ for (const entry of parseEntries(hansard)) {
84
+ const files = entry.fields['Files touched'];
85
+ if (files === undefined || files === 'none') continue;
86
+ const motion = entry.fields['Motion'] ?? `${entry.actor}@${entry.at}`;
87
+ touched.set(motion, files.split(',').map((f) => f.trim()).filter((f) => f.length > 0));
88
+ }
89
+ return detectConflicts([...touched.entries()].map(([motion, files]) => ({ motion, files })));
90
+ };
91
+
92
+ /* -------------------------------------------------------------------------- */
93
+ /* Standing */
94
+ /* -------------------------------------------------------------------------- */
95
+
96
+ export class ConflictError extends Error {
97
+ constructor(message: string) {
98
+ super(message);
99
+ this.name = 'ConflictError';
100
+ }
101
+ }
102
+
103
+ /**
104
+ * May this role resolve a conflict?
105
+ *
106
+ * Any actor holding WRITE — which is the substance of the CANON entry, and the
107
+ * reason a conflict is not a governance event. Requiring AUTHORITY would turn
108
+ * every merge conflict into a Speaker interruption.
109
+ */
110
+ export const mayResolve = (verbs: readonly Verb[]): boolean => verbs.includes('WRITE');
111
+
112
+ /* -------------------------------------------------------------------------- */
113
+ /* Records */
114
+ /* -------------------------------------------------------------------------- */
115
+
116
+ /**
117
+ * Record that a conflict exists.
118
+ *
119
+ * Deliberately not a `SESSION_FAULT`, and it carries no resolution path: this
120
+ * is work to be done, not a failure to be attributed. Nothing about the
121
+ * session's state changes.
122
+ */
123
+ export const conflictEntry = (
124
+ conflict: Conflict,
125
+ at: string,
126
+ actor: string,
127
+ role: Role,
128
+ ): HansardEntry => ({
129
+ type: 'CONFLICT',
130
+ at,
131
+ actor,
132
+ role,
133
+ fields: {
134
+ Motions: conflict.motions.join(', '),
135
+ Files: conflict.files.join(', '),
136
+ Standing: 'any actor holding WRITE may resolve this',
137
+ 'Session status': 'CONVENED — a conflict is routine, not a governance failure',
138
+ },
139
+ body:
140
+ 'Two Motions touch the same files. This is an ordinary event in concurrent ' +
141
+ 'work and requires no ruling.',
142
+ });
143
+
144
+ export interface ResolutionInput {
145
+ readonly at: string;
146
+ readonly actor: string;
147
+ readonly role: Role;
148
+ readonly verbs: readonly Verb[];
149
+ readonly motions: readonly string[];
150
+ /** How it was settled, in the resolver's own words. */
151
+ readonly resolution: string;
152
+ }
153
+
154
+ /**
155
+ * Record a conflict resolved.
156
+ *
157
+ * Refuses an actor without WRITE — not because resolving is dangerous, but
158
+ * because a record naming someone who could not have done the work is a false
159
+ * record.
160
+ */
161
+ export const resolveConflict = (
162
+ input: ResolutionInput,
163
+ hansard: string,
164
+ ): { readonly entry: HansardEntry; readonly hansard: string } => {
165
+ if (!mayResolve(input.verbs)) {
166
+ throw new ConflictError(
167
+ `resolving a conflict requires WRITE — ${input.actor} (${input.role}) holds ${
168
+ input.verbs.length > 0 ? input.verbs.join(', ') : 'no verbs'
169
+ }`,
170
+ );
171
+ }
172
+ if (input.motions.length < 2) {
173
+ throw new ConflictError('a conflict is between two or more Motions');
174
+ }
175
+ if (input.resolution.trim() === '') {
176
+ throw new ConflictError('a resolution must state how the conflict was settled');
177
+ }
178
+
179
+ const entry: HansardEntry = {
180
+ type: 'CONFLICT_RESOLVED',
181
+ at: input.at,
182
+ actor: input.actor,
183
+ role: input.role,
184
+ fields: {
185
+ Motions: input.motions.join(', '),
186
+ 'Resolved by': `${input.actor} (${input.role}) — holding WRITE`,
187
+ 'Speaker intervention': 'none — a conflict is not a governance failure',
188
+ },
189
+ body: input.resolution.trim(),
190
+ };
191
+
192
+ return { entry, hansard: appendEntry(hansard, entry) };
193
+ };
194
+
195
+ /** Conflicts recorded and not yet resolved. */
196
+ export const openConflicts = (hansard: string): readonly string[] => {
197
+ const open = new Set<string>();
198
+ for (const entry of parseEntries(hansard)) {
199
+ const motions = entry.fields['Motions'];
200
+ if (motions === undefined) continue;
201
+ if (entry.type === 'CONFLICT') open.add(motions);
202
+ if (entry.type === 'CONFLICT_RESOLVED') open.delete(motions);
203
+ }
204
+ return [...open];
205
+ };
206
+
207
+ /** Sanity: CONFLICT must never be confused for a suspension cause. */
208
+ export const IS_GOVERNANCE_FAILURE = false;
209
+
210
+ /** Every CANON verb, for callers that need the full grant. */
211
+ export const ALL_VERBS: readonly Verb[] = VERBS;
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Hard Containment — agents may never traverse above the session directory.
3
+ *
4
+ * POLITIK-ARCHITECTURE.md § Hard Containment Rule:
5
+ *
6
+ * Agents MAY NEVER traverse above CWD.
7
+ * Reading ../anything = Standing Orders violation
8
+ * Logged to Hansard immediately
9
+ * Escalated to Speaker automatically
10
+ * Session paused pending ruling
11
+ *
12
+ * ## What this module is, and what it is not
13
+ *
14
+ * This is **detection, not prevention.** A spawned process runs with the
15
+ * operating system's permissions, and nothing in userspace can stop it reading
16
+ * a path it is entitled to read. Claiming otherwise would be the more dangerous
17
+ * error: an operator who believes the framework sandboxes agents will not
18
+ * reach for the thing that actually does.
19
+ *
20
+ * Real prevention is a deployment concern — a container, a `bwrap` jail, a user
21
+ * with no read access above the session. `politik doctor` reports whether the
22
+ * session is containerised, and RUNTIME.md's platform matrix is where that
23
+ * belongs.
24
+ *
25
+ * What is detectable after the fact is still worth having: an agent that
26
+ * *wrote* outside the session, or that *reports* having read above it, leaves
27
+ * evidence. The Hansard records what happened, which is the framework's answer
28
+ * to most things it cannot prevent.
29
+ *
30
+ * Attribution: Steve Krisjanovs, Cordfuse
31
+ */
32
+
33
+ import { isAbsolute, relative, resolve } from 'node:path';
34
+
35
+ import type { Role } from './canon.ts';
36
+ import type { HansardEntry } from './hansard.ts';
37
+
38
+ /* -------------------------------------------------------------------------- */
39
+ /* Findings */
40
+ /* -------------------------------------------------------------------------- */
41
+
42
+ export type BreachKind =
43
+ /** A file was written outside the session directory. */
44
+ | 'WROTE_OUTSIDE'
45
+ /** The agent's own report references a path above the session. */
46
+ | 'REPORTED_TRAVERSAL';
47
+
48
+ export interface Breach {
49
+ readonly kind: BreachKind;
50
+ readonly evidence: string;
51
+ }
52
+
53
+ export interface ContainmentCheck {
54
+ readonly contained: boolean;
55
+ readonly breaches: readonly Breach[];
56
+ }
57
+
58
+ /* -------------------------------------------------------------------------- */
59
+ /* Detection */
60
+ /* -------------------------------------------------------------------------- */
61
+
62
+ /** Is `path` inside `root`? */
63
+ export const isInside = (root: string, path: string): boolean => {
64
+ const target = isAbsolute(path) ? path : resolve(root, path);
65
+ const rel = relative(resolve(root), target);
66
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
67
+ };
68
+
69
+ /**
70
+ * Paths in agent output that reach above the session.
71
+ *
72
+ * Deliberately conservative. This scans prose written by a model, so it looks
73
+ * only for shapes that are unambiguous — a leading `../`, or an absolute path
74
+ * to a place a session has no business touching. Matching every mention of
75
+ * ".." would flag an agent that merely *discussed* the containment rule, and a
76
+ * detector that cries wolf teaches operators to ignore it.
77
+ */
78
+ const TRAVERSAL = /(?:^|[\s'"`(])(\.\.\/[\w.\-/]+)/g;
79
+ const SENSITIVE = /(?:^|[\s'"`(])((?:\/etc\/|\/root\/|~\/\.ssh|\/home\/[\w.-]+\/\.(?:ssh|aws|config))[\w.\-/]*)/g;
80
+
81
+ export const scanOutput = (output: string): readonly Breach[] => {
82
+ const breaches: Breach[] = [];
83
+ const seen = new Set<string>();
84
+
85
+ for (const pattern of [TRAVERSAL, SENSITIVE]) {
86
+ pattern.lastIndex = 0;
87
+ let match: RegExpExecArray | null;
88
+ while ((match = pattern.exec(output)) !== null) {
89
+ const evidence = (match[1] ?? '').trim();
90
+ if (evidence === '' || seen.has(evidence)) continue;
91
+ seen.add(evidence);
92
+ breaches.push({ kind: 'REPORTED_TRAVERSAL', evidence });
93
+ }
94
+ }
95
+
96
+ return breaches;
97
+ };
98
+
99
+ /**
100
+ * Check a completed turn for containment breaches.
101
+ *
102
+ * `touched` comes from git and is therefore already session-relative; an
103
+ * absolute path or a `..` prefix in that list means the agent wrote somewhere
104
+ * it should not have been able to.
105
+ */
106
+ export const checkContainment = (
107
+ sessionDir: string,
108
+ touched: readonly string[],
109
+ output: string,
110
+ ): ContainmentCheck => {
111
+ const breaches: Breach[] = [];
112
+
113
+ for (const path of touched) {
114
+ if (!isInside(sessionDir, path)) {
115
+ breaches.push({ kind: 'WROTE_OUTSIDE', evidence: path });
116
+ }
117
+ }
118
+
119
+ breaches.push(...scanOutput(output));
120
+
121
+ return { contained: breaches.length === 0, breaches };
122
+ };
123
+
124
+ /* -------------------------------------------------------------------------- */
125
+ /* Record */
126
+ /* -------------------------------------------------------------------------- */
127
+
128
+ /**
129
+ * Record a containment breach.
130
+ *
131
+ * The spec is unambiguous about the consequence: logged immediately, escalated
132
+ * to the Speaker, session paused pending a ruling. That is the Point of Order
133
+ * flow, so the breach reuses it rather than inventing a parallel path — the
134
+ * Speaker rules, and `politik rule` resumes.
135
+ */
136
+ export const breachEntry = (
137
+ check: ContainmentCheck,
138
+ at: string,
139
+ actor: string,
140
+ role: Role,
141
+ ): HansardEntry => ({
142
+ type: 'CONTAINMENT_BREACH',
143
+ at,
144
+ actor,
145
+ role,
146
+ fields: {
147
+ Breaches: String(check.breaches.length),
148
+ Evidence: check.breaches.map((b) => `${b.kind}: ${b.evidence}`).join('; '),
149
+ 'Session status': 'SUSPENDED — escalated to the Speaker pending a ruling',
150
+ Note: 'detection, not prevention — a spawned process runs with the operating system\'s permissions',
151
+ },
152
+ body:
153
+ 'An actor reached above the session directory. Standing Orders forbid it. ' +
154
+ 'The sitting is suspended until the Speaker rules.',
155
+ });