@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.
- package/EXECUTION.md +766 -0
- package/LICENSE +21 -0
- package/POLITIK-ARCHITECTURE.md +676 -0
- package/PROTOCOLS.md +1106 -0
- package/README.md +193 -0
- package/RESEARCH.md +475 -0
- package/RUNTIME.md +1355 -0
- package/bin/politik.js +31 -0
- package/docs/adr/0001-chamber-transport.md +67 -0
- package/docs/adr/0002-charter-schema.md +142 -0
- package/docs/adr/0003-state-json-schema.md +134 -0
- package/docs/adr/0004-motion-enactment.md +215 -0
- package/docs/adr/0005-hansard-format.md +171 -0
- package/docs/adr/0006-protocol-behavioral-enforcement.md +89 -0
- package/docs/adr/0007-protocol-mechanics.md +100 -0
- package/docs/adr/0008-session-storage.md +108 -0
- package/docs/adr/0009-match-primitive.md +74 -0
- package/package.json +55 -0
- package/protocols/CONTRIBUTING.md +130 -0
- package/protocols/adversarial-collaboration.yml +28 -0
- package/protocols/corporate.yml +35 -0
- package/protocols/elimination-tournament.yml +41 -0
- package/protocols/emergency-response-ics.yml +27 -0
- package/protocols/jury-deliberation.yml +32 -0
- package/protocols/monarchy.yml +31 -0
- package/protocols/parliamentary.yml +66 -0
- package/protocols/peer-review.yml +44 -0
- package/protocols/republic.yml +36 -0
- package/protocols/socialism-collective.yml +31 -0
- package/protocols/solo.yml +32 -0
- package/src/actors.ts +742 -0
- package/src/agents.ts +318 -0
- package/src/canon.ts +173 -0
- package/src/capability.ts +336 -0
- package/src/charter.ts +545 -0
- package/src/cli.ts +2174 -0
- package/src/conflict.ts +211 -0
- package/src/containment.ts +155 -0
- package/src/crisis.ts +381 -0
- package/src/division.ts +609 -0
- package/src/doctor.ts +168 -0
- package/src/election.ts +233 -0
- package/src/envelope.ts +223 -0
- package/src/escalation.ts +320 -0
- package/src/fault.ts +241 -0
- package/src/federation.ts +299 -0
- package/src/git.ts +163 -0
- package/src/hansard.ts +201 -0
- package/src/heartbeat.ts +282 -0
- package/src/index.ts +43 -0
- package/src/init.ts +396 -0
- package/src/integrity.ts +153 -0
- package/src/ledger.ts +341 -0
- package/src/lockfs.ts +58 -0
- package/src/projection.ts +293 -0
- package/src/prorogation.ts +307 -0
- package/src/protocol-sdk.ts +248 -0
- package/src/protocol.ts +241 -0
- package/src/providers/github.ts +347 -0
- package/src/quorum.ts +137 -0
- package/src/runner.ts +534 -0
- package/src/scm.ts +142 -0
- package/src/spawn.ts +160 -0
- package/src/standings.ts +143 -0
- package/src/state.ts +179 -0
- package/src/templates/parliamentary.ts +359 -0
- package/src/tournament.ts +200 -0
- package/src/transport.ts +190 -0
- package/src/tree.ts +371 -0
package/src/ledger.ts
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LEDGER — the secretarial cost record.
|
|
3
|
+
*
|
|
4
|
+
* The Hansard says what was decided. The LEDGER says what it cost. Together
|
|
5
|
+
* they are the claim that Politik replaces a ticket system: exact measured
|
|
6
|
+
* elapsed time, tokens and dollars per governance act, as a side effect of
|
|
7
|
+
* running the session rather than as something anyone maintains.
|
|
8
|
+
*
|
|
9
|
+
* That claim only holds if the numbers are real. This module therefore records
|
|
10
|
+
* **measured** usage where an agent reports it and says `unmeasured` where it
|
|
11
|
+
* does not — never an estimate dressed as a measurement. A ledger with invented
|
|
12
|
+
* numbers is worse than no ledger, because it is trusted.
|
|
13
|
+
*
|
|
14
|
+
* Append-only, like the Hansard: `LEDGER.md → Clerk appends after every motion,
|
|
15
|
+
* never edited` (POLITIK-ARCHITECTURE.md § File Sovereignty Rules).
|
|
16
|
+
*
|
|
17
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { Role } from './canon.ts';
|
|
21
|
+
|
|
22
|
+
/* -------------------------------------------------------------------------- */
|
|
23
|
+
/* Usage */
|
|
24
|
+
/* -------------------------------------------------------------------------- */
|
|
25
|
+
|
|
26
|
+
export interface Usage {
|
|
27
|
+
readonly input_tokens: number;
|
|
28
|
+
readonly output_tokens: number;
|
|
29
|
+
readonly cache_read_tokens: number;
|
|
30
|
+
readonly cache_creation_tokens: number;
|
|
31
|
+
/** Exact cost as reported by the agent. Null when the agent does not report. */
|
|
32
|
+
readonly cost_usd: number | null;
|
|
33
|
+
/** Model that did the work, when reported. */
|
|
34
|
+
readonly model: string | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const ZERO_USAGE: Usage = Object.freeze({
|
|
38
|
+
input_tokens: 0,
|
|
39
|
+
output_tokens: 0,
|
|
40
|
+
cache_read_tokens: 0,
|
|
41
|
+
cache_creation_tokens: 0,
|
|
42
|
+
cost_usd: null,
|
|
43
|
+
model: null,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Extract usage from an agent's structured output.
|
|
50
|
+
*
|
|
51
|
+
* Shapes are per-agent and deliberately narrow. An agent whose output does not
|
|
52
|
+
* match returns null rather than a zero-filled Usage, so "no data" stays
|
|
53
|
+
* distinguishable from "measured zero" — a distinction the whole point of this
|
|
54
|
+
* module depends on.
|
|
55
|
+
*/
|
|
56
|
+
export const parseUsage = (agentId: string, stdout: string): Usage | null => {
|
|
57
|
+
const trimmed = stdout.trim();
|
|
58
|
+
if (trimmed === '') return null;
|
|
59
|
+
|
|
60
|
+
// JSONL agents emit a stream of events; the usage arrives in one of them.
|
|
61
|
+
if (agentId === 'opencode') return parseOpencode(trimmed);
|
|
62
|
+
if (agentId === 'codex-cli') return parseCodex(trimmed);
|
|
63
|
+
|
|
64
|
+
if (!trimmed.startsWith('{')) return null;
|
|
65
|
+
|
|
66
|
+
let raw: unknown;
|
|
67
|
+
try {
|
|
68
|
+
raw = JSON.parse(trimmed);
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
if (typeof raw !== 'object' || raw === null) return null;
|
|
73
|
+
const doc = raw as Record<string, unknown>;
|
|
74
|
+
|
|
75
|
+
// Gemini and Qwen share a CLI lineage and a stats shape: per-model token
|
|
76
|
+
// counts, no cost. Recording tokens with `cost_usd: null` is the honest
|
|
77
|
+
// result — the vendor does not report spend, and inventing a price from a
|
|
78
|
+
// rate card would be an estimate dressed as a measurement.
|
|
79
|
+
if (agentId === 'gemini-cli' || agentId === 'qwen-code') {
|
|
80
|
+
const stats = (doc['stats'] ?? {}) as Record<string, unknown>;
|
|
81
|
+
const models = (stats['models'] ?? {}) as Record<string, unknown>;
|
|
82
|
+
const name = Object.keys(models)[0];
|
|
83
|
+
if (name === undefined) return null;
|
|
84
|
+
const t = ((models[name] as Record<string, unknown>)['tokens'] ?? {}) as Record<string, unknown>;
|
|
85
|
+
return {
|
|
86
|
+
input_tokens: num(t['input']),
|
|
87
|
+
output_tokens: num(t['candidates']),
|
|
88
|
+
cache_read_tokens: num(t['cached']),
|
|
89
|
+
cache_creation_tokens: 0,
|
|
90
|
+
cost_usd: null,
|
|
91
|
+
model: name,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (agentId === 'claude-code') {
|
|
96
|
+
const usage = (doc['usage'] ?? {}) as Record<string, unknown>;
|
|
97
|
+
const models = Object.keys((doc['modelUsage'] ?? {}) as Record<string, unknown>);
|
|
98
|
+
return {
|
|
99
|
+
input_tokens: num(usage['input_tokens']),
|
|
100
|
+
output_tokens: num(usage['output_tokens']),
|
|
101
|
+
cache_read_tokens: num(usage['cache_read_input_tokens']),
|
|
102
|
+
cache_creation_tokens: num(usage['cache_creation_input_tokens']),
|
|
103
|
+
cost_usd: typeof doc['total_cost_usd'] === 'number' ? doc['total_cost_usd'] : null,
|
|
104
|
+
model: models[0] ?? null,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Antigravity (agy) and GitHub Copilot usage will parse here once a real sample
|
|
109
|
+
// is captured (Copilot needs an active subscription first). Aider and Goose are
|
|
110
|
+
// deferred and open for a PR (see EXECUTION.md § Roadmap). Falling through to
|
|
111
|
+
// null records `unmeasured` — safe, never a fabricated number.
|
|
112
|
+
return null;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* OpenCode emits JSONL events; usage rides on the ones carrying `tokens`.
|
|
117
|
+
* Later events win — the last report of a turn is its total.
|
|
118
|
+
*/
|
|
119
|
+
const parseOpencode = (stdout: string): Usage | null => {
|
|
120
|
+
let tokens: Record<string, unknown> | null = null;
|
|
121
|
+
let cost: number | null = null;
|
|
122
|
+
let model: string | null = null;
|
|
123
|
+
|
|
124
|
+
for (const line of stdout.split('\n')) {
|
|
125
|
+
const t = line.trim();
|
|
126
|
+
if (!t.startsWith('{')) continue;
|
|
127
|
+
let doc: Record<string, unknown>;
|
|
128
|
+
try {
|
|
129
|
+
doc = JSON.parse(t) as Record<string, unknown>;
|
|
130
|
+
} catch {
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
for (const scope of [doc, (doc['part'] ?? {}) as Record<string, unknown>]) {
|
|
134
|
+
if (typeof scope['tokens'] === 'object' && scope['tokens'] !== null) {
|
|
135
|
+
tokens = scope['tokens'] as Record<string, unknown>;
|
|
136
|
+
}
|
|
137
|
+
if (typeof scope['cost'] === 'number') cost = scope['cost'];
|
|
138
|
+
if (typeof scope['modelID'] === 'string') model = scope['modelID'];
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (tokens === null) return null;
|
|
143
|
+
const cache = (tokens['cache'] ?? {}) as Record<string, unknown>;
|
|
144
|
+
return {
|
|
145
|
+
input_tokens: num(tokens['input']),
|
|
146
|
+
output_tokens: num(tokens['output']),
|
|
147
|
+
cache_read_tokens: num(cache['read']),
|
|
148
|
+
cache_creation_tokens: num(cache['write']),
|
|
149
|
+
cost_usd: cost,
|
|
150
|
+
model,
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/** Codex emits JSONL; `turn.completed` carries the usage. */
|
|
155
|
+
const parseCodex = (stdout: string): Usage | null => {
|
|
156
|
+
for (const line of stdout.split('\n').reverse()) {
|
|
157
|
+
const t = line.trim();
|
|
158
|
+
if (!t.startsWith('{')) continue;
|
|
159
|
+
let doc: Record<string, unknown>;
|
|
160
|
+
try {
|
|
161
|
+
doc = JSON.parse(t) as Record<string, unknown>;
|
|
162
|
+
} catch {
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
const usage = doc['usage'];
|
|
166
|
+
if (typeof usage !== 'object' || usage === null) continue;
|
|
167
|
+
const u = usage as Record<string, unknown>;
|
|
168
|
+
return {
|
|
169
|
+
input_tokens: num(u['input_tokens']),
|
|
170
|
+
output_tokens: num(u['output_tokens']),
|
|
171
|
+
cache_read_tokens: num(u['cached_input_tokens']),
|
|
172
|
+
cache_creation_tokens: 0,
|
|
173
|
+
cost_usd: null,
|
|
174
|
+
model: null,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
return null;
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
/** The agent's actual answer, pulled out of structured output. */
|
|
181
|
+
export const parseResultText = (agentId: string, stdout: string): string | null => {
|
|
182
|
+
const trimmed = stdout.trim();
|
|
183
|
+
if (trimmed === '') return null;
|
|
184
|
+
|
|
185
|
+
// JSONL agents: the answer is assembled from text events rather than carried
|
|
186
|
+
// in one field.
|
|
187
|
+
if (agentId === 'opencode' || agentId === 'codex-cli') {
|
|
188
|
+
const parts: string[] = [];
|
|
189
|
+
for (const line of trimmed.split('\n')) {
|
|
190
|
+
const t = line.trim();
|
|
191
|
+
if (!t.startsWith('{')) continue;
|
|
192
|
+
try {
|
|
193
|
+
const doc = JSON.parse(t) as Record<string, unknown>;
|
|
194
|
+
const part = (doc['part'] ?? {}) as Record<string, unknown>;
|
|
195
|
+
if (doc['type'] === 'text' && typeof part['text'] === 'string') parts.push(part['text']);
|
|
196
|
+
const item = (doc['item'] ?? {}) as Record<string, unknown>;
|
|
197
|
+
if (typeof item['text'] === 'string') parts.push(item['text']);
|
|
198
|
+
} catch {
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return parts.length > 0 ? parts.join('').trim() : null;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (!trimmed.startsWith('{')) return null;
|
|
206
|
+
try {
|
|
207
|
+
const doc = JSON.parse(trimmed) as Record<string, unknown>;
|
|
208
|
+
if (agentId === 'claude-code' && typeof doc['result'] === 'string') {
|
|
209
|
+
return doc['result'];
|
|
210
|
+
}
|
|
211
|
+
// Gemini and Qwen carry the answer in `response`.
|
|
212
|
+
if ((agentId === 'gemini-cli' || agentId === 'qwen-code') && typeof doc['response'] === 'string') {
|
|
213
|
+
return doc['response'];
|
|
214
|
+
}
|
|
215
|
+
} catch {
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
return null;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
/* -------------------------------------------------------------------------- */
|
|
222
|
+
/* Entries */
|
|
223
|
+
/* -------------------------------------------------------------------------- */
|
|
224
|
+
|
|
225
|
+
export interface LedgerEntry {
|
|
226
|
+
readonly at: string;
|
|
227
|
+
readonly actor: string;
|
|
228
|
+
readonly role: Role;
|
|
229
|
+
/** What the cost was incurred doing — a Motion id, or the act's record type. */
|
|
230
|
+
readonly item: string;
|
|
231
|
+
readonly elapsed_ms: number;
|
|
232
|
+
readonly usage: Usage | null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const cell = (v: string | number): string => String(v).replace(/\|/g, '\\|');
|
|
236
|
+
|
|
237
|
+
/** Render one ledger row. */
|
|
238
|
+
export const renderRow = (entry: LedgerEntry): string => {
|
|
239
|
+
const u = entry.usage;
|
|
240
|
+
const tokens =
|
|
241
|
+
u === null
|
|
242
|
+
? 'unmeasured'
|
|
243
|
+
: String(u.input_tokens + u.output_tokens + u.cache_read_tokens + u.cache_creation_tokens);
|
|
244
|
+
const cost =
|
|
245
|
+
u === null || u.cost_usd === null ? 'unmeasured' : `$${u.cost_usd.toFixed(6)}`;
|
|
246
|
+
|
|
247
|
+
return `| ${cell(entry.at)} | ${cell(entry.actor)} (${entry.role}) | ${cell(entry.item)} | ${cell(
|
|
248
|
+
(entry.elapsed_ms / 1000).toFixed(1),
|
|
249
|
+
)}s | ${cell(tokens)} | ${cell(cost)} | ${cell(u?.model ?? '—')} |`;
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
export const LEDGER_HEADER = [
|
|
253
|
+
'| Timestamp | Actor | Item | Elapsed | Tokens | Cost (USD) | Model |',
|
|
254
|
+
'|---|---|---|---|---|---|---|',
|
|
255
|
+
].join('\n');
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Append a row to the LEDGER.
|
|
259
|
+
*
|
|
260
|
+
* Returns the previous document verbatim as a prefix, same guarantee as the
|
|
261
|
+
* Hansard. If the document has no table yet, the header is inserted once.
|
|
262
|
+
*/
|
|
263
|
+
export const appendLedgerRow = (document: string, entry: LedgerEntry): string => {
|
|
264
|
+
const base = document.endsWith('\n') || document === '' ? document : `${document}\n`;
|
|
265
|
+
const hasHeader = base.includes('| Timestamp | Actor |');
|
|
266
|
+
const row = renderRow(entry);
|
|
267
|
+
// Trim trailing blank lines before appending. The LEDGER template ends its
|
|
268
|
+
// header with a blank line; without this the first row lands one line below
|
|
269
|
+
// the separator, and a blank line inside a markdown table splits it in two —
|
|
270
|
+
// so the cost record renders as a broken table on the platform that hosts it.
|
|
271
|
+
return hasHeader ? `${base.replace(/\n+$/, '\n')}${row}\n` : `${base}\n${LEDGER_HEADER}\n${row}\n`;
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
/* -------------------------------------------------------------------------- */
|
|
275
|
+
/* Totals */
|
|
276
|
+
/* -------------------------------------------------------------------------- */
|
|
277
|
+
|
|
278
|
+
export interface LedgerTotals {
|
|
279
|
+
readonly rows: number;
|
|
280
|
+
readonly elapsed_ms: number;
|
|
281
|
+
readonly tokens: number;
|
|
282
|
+
readonly cost_usd: number;
|
|
283
|
+
/** Rows whose cost the agent did not report. */
|
|
284
|
+
readonly unmeasured: number;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const ROW = /^\|\s*(\S+)\s*\|([^|]*)\|([^|]*)\|\s*([\d.]+)s\s*\|\s*(\S+)\s*\|\s*(\S+)\s*\|/;
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Total the LEDGER by reading it back.
|
|
291
|
+
*
|
|
292
|
+
* `unmeasured` is reported separately and never folded into the cost. A total
|
|
293
|
+
* that silently omitted unmeasured rows would understate spend while looking
|
|
294
|
+
* authoritative — the failure mode this module exists to avoid.
|
|
295
|
+
*/
|
|
296
|
+
export const totals = (document: string): LedgerTotals => {
|
|
297
|
+
let rows = 0;
|
|
298
|
+
let elapsed = 0;
|
|
299
|
+
let tokens = 0;
|
|
300
|
+
let cost = 0;
|
|
301
|
+
let unmeasured = 0;
|
|
302
|
+
|
|
303
|
+
for (const line of document.split('\n')) {
|
|
304
|
+
const match = ROW.exec(line.trim());
|
|
305
|
+
if (match === null) continue;
|
|
306
|
+
rows += 1;
|
|
307
|
+
elapsed += Math.round(Number.parseFloat(match[4] ?? '0') * 1000);
|
|
308
|
+
|
|
309
|
+
const tokenCell = (match[5] ?? '').trim();
|
|
310
|
+
if (tokenCell !== 'unmeasured') tokens += Number.parseInt(tokenCell, 10) || 0;
|
|
311
|
+
|
|
312
|
+
const costCell = (match[6] ?? '').trim();
|
|
313
|
+
if (costCell.startsWith('$')) cost += Number.parseFloat(costCell.slice(1)) || 0;
|
|
314
|
+
else unmeasured += 1;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return { rows, elapsed_ms: elapsed, tokens, cost_usd: cost, unmeasured };
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Has the session passed a cost ceiling or warning line?
|
|
322
|
+
*
|
|
323
|
+
* The cost ceiling is the guardrail that matters for API-key deployments: an
|
|
324
|
+
* overnight proceeding can otherwise burn credits before anyone notices
|
|
325
|
+
* (RUNTIME.md § Session Termination Conditions).
|
|
326
|
+
*/
|
|
327
|
+
export const checkCostCeiling = (
|
|
328
|
+
document: string,
|
|
329
|
+
maxCostUsd: number | null,
|
|
330
|
+
warningUsd: number | null,
|
|
331
|
+
): { readonly exceeded: boolean; readonly warning: boolean; readonly spent: number } => {
|
|
332
|
+
const spent = totals(document).cost_usd;
|
|
333
|
+
return {
|
|
334
|
+
exceeded: maxCostUsd !== null && spent >= maxCostUsd,
|
|
335
|
+
warning:
|
|
336
|
+
warningUsd !== null &&
|
|
337
|
+
spent >= warningUsd &&
|
|
338
|
+
(maxCostUsd === null || spent < maxCostUsd),
|
|
339
|
+
spent,
|
|
340
|
+
};
|
|
341
|
+
};
|
package/src/lockfs.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Filesystem-backed LockFs.
|
|
3
|
+
*
|
|
4
|
+
* The atomicity the election depends on comes from `open(2)` with
|
|
5
|
+
* `O_CREAT|O_EXCL` — Node's `wx` flag — which creates a file and fails if it
|
|
6
|
+
* already exists, in a single syscall. Two agents racing to create the same
|
|
7
|
+
* lockfile cannot both succeed.
|
|
8
|
+
*
|
|
9
|
+
* Kept in its own module so `election.ts` has no filesystem dependency and can
|
|
10
|
+
* be exercised without touching a disk.
|
|
11
|
+
*
|
|
12
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { dirname } from 'node:path';
|
|
17
|
+
|
|
18
|
+
import type { LockFs } from './election.ts';
|
|
19
|
+
|
|
20
|
+
/** Errors that mean "the thing is not there", as opposed to a real fault. */
|
|
21
|
+
const isAbsent = (err: unknown): boolean =>
|
|
22
|
+
typeof err === 'object' &&
|
|
23
|
+
err !== null &&
|
|
24
|
+
'code' in err &&
|
|
25
|
+
(err as { code: string }).code === 'ENOENT';
|
|
26
|
+
|
|
27
|
+
const isExists = (err: unknown): boolean =>
|
|
28
|
+
typeof err === 'object' &&
|
|
29
|
+
err !== null &&
|
|
30
|
+
'code' in err &&
|
|
31
|
+
(err as { code: string }).code === 'EEXIST';
|
|
32
|
+
|
|
33
|
+
export const nodeLockFs: LockFs = {
|
|
34
|
+
async createExclusive(path: string, contents: string): Promise<boolean> {
|
|
35
|
+
try {
|
|
36
|
+
await mkdir(dirname(path), { recursive: true });
|
|
37
|
+
// 'wx' — create exclusively. Fails with EEXIST if the path exists.
|
|
38
|
+
await writeFile(path, contents, { flag: 'wx' });
|
|
39
|
+
return true;
|
|
40
|
+
} catch (err) {
|
|
41
|
+
if (isExists(err)) return false;
|
|
42
|
+
throw err;
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
async readFile(path: string): Promise<string | null> {
|
|
47
|
+
try {
|
|
48
|
+
return await readFile(path, 'utf8');
|
|
49
|
+
} catch (err) {
|
|
50
|
+
if (isAbsent(err)) return null;
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
async remove(path: string): Promise<void> {
|
|
56
|
+
await rm(path, { force: true });
|
|
57
|
+
},
|
|
58
|
+
};
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SCM projection — governance acts projected onto a hosting platform.
|
|
3
|
+
*
|
|
4
|
+
* A Politik session is a git repository. That much is mandatory: the Charter,
|
|
5
|
+
* the Hansard, STATE.json and the audit trail all live there, and a session
|
|
6
|
+
* without git has no substrate.
|
|
7
|
+
*
|
|
8
|
+
* A **provider** is optional, and this module is the seam. When one is
|
|
9
|
+
* configured, governance acts are additionally projected onto the platform —
|
|
10
|
+
* a Motion becomes a Pull Request, a Division becomes a review request, an
|
|
11
|
+
* Escalation becomes an Issue. When none is configured the session is complete
|
|
12
|
+
* and correct without them.
|
|
13
|
+
*
|
|
14
|
+
* ## Why optional
|
|
15
|
+
*
|
|
16
|
+
* The architecture's own tagline is "Run local, run free", and ADR-0001 states
|
|
17
|
+
* a session "convenes with no broker, no daemon, and no network service". A
|
|
18
|
+
* framework making that promise cannot require an API client. But the same
|
|
19
|
+
* document says the repository "is the motion system (Pull Requests)".
|
|
20
|
+
*
|
|
21
|
+
* Both hold under this split: git is the session, the platform is a projection
|
|
22
|
+
* of it. Local sessions get the whole governance model; hosted sessions also
|
|
23
|
+
* get the platform objects. Nothing about a Division changes because it was
|
|
24
|
+
* mirrored to a review.
|
|
25
|
+
*
|
|
26
|
+
* ## The rule this module exists to keep
|
|
27
|
+
*
|
|
28
|
+
* **A projection failure must never invalidate a governance act.** The Hansard
|
|
29
|
+
* is the record. If a Motion carried and the merge call fails, the Motion still
|
|
30
|
+
* carried — the projection is behind, not the decision. Every function here
|
|
31
|
+
* therefore reports what happened and refuses to throw its caller's governance
|
|
32
|
+
* away.
|
|
33
|
+
*
|
|
34
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
import type { MergeStrategy } from './canon.ts';
|
|
38
|
+
import { parseEntries, type HansardEntry } from './hansard.ts';
|
|
39
|
+
import { GitHubProvider } from './providers/github.ts';
|
|
40
|
+
import type { ScmProvider } from './scm.ts';
|
|
41
|
+
|
|
42
|
+
/* -------------------------------------------------------------------------- */
|
|
43
|
+
/* Resolution */
|
|
44
|
+
/* -------------------------------------------------------------------------- */
|
|
45
|
+
|
|
46
|
+
export interface ProviderConfig {
|
|
47
|
+
/** `owner/name`. Absent means local-only. */
|
|
48
|
+
readonly repo?: string | undefined;
|
|
49
|
+
/** Token. Falls back to GH_TOKEN / GITHUB_TOKEN. */
|
|
50
|
+
readonly token?: string | undefined;
|
|
51
|
+
readonly baseBranch?: string | undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ProviderResolution {
|
|
55
|
+
readonly provider: ScmProvider | null;
|
|
56
|
+
/** Why there is no provider, for the operator. Null when there is one. */
|
|
57
|
+
readonly reason: string | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Resolve a provider from configuration.
|
|
62
|
+
*
|
|
63
|
+
* Returns a reason rather than throwing when none can be built: running local
|
|
64
|
+
* is a supported mode, not a misconfiguration, and an operator who simply did
|
|
65
|
+
* not pass `--repo` should see an explanation rather than an error.
|
|
66
|
+
*/
|
|
67
|
+
export const resolveProvider = (
|
|
68
|
+
config: ProviderConfig,
|
|
69
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
70
|
+
): ProviderResolution => {
|
|
71
|
+
if (config.repo === undefined || config.repo === '') {
|
|
72
|
+
return { provider: null, reason: 'no --repo given — running local-only' };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const [owner, repo] = config.repo.split('/');
|
|
76
|
+
if (owner === undefined || repo === undefined || owner === '' || repo === '') {
|
|
77
|
+
return { provider: null, reason: `--repo must be owner/name, got "${config.repo}"` };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const token = config.token ?? env['GH_TOKEN'] ?? env['GITHUB_TOKEN'];
|
|
81
|
+
if (token === undefined || token === '') {
|
|
82
|
+
return {
|
|
83
|
+
provider: null,
|
|
84
|
+
reason: 'no token — set GH_TOKEN or GITHUB_TOKEN, or pass --token',
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
provider: new GitHubProvider({
|
|
90
|
+
owner,
|
|
91
|
+
repo,
|
|
92
|
+
token,
|
|
93
|
+
...(config.baseBranch === undefined ? {} : { baseBranch: config.baseBranch }),
|
|
94
|
+
}),
|
|
95
|
+
reason: null,
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/* -------------------------------------------------------------------------- */
|
|
100
|
+
/* Motion ↔ platform object */
|
|
101
|
+
/* -------------------------------------------------------------------------- */
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The platform object a Motion is projected onto.
|
|
105
|
+
*
|
|
106
|
+
* Read back from the Hansard rather than held in a side table: the record is
|
|
107
|
+
* the register, exactly as it is for actor seats. A Motion tabled before a
|
|
108
|
+
* provider was configured simply has no link, which is a legitimate state.
|
|
109
|
+
*/
|
|
110
|
+
export const motionPr = (hansard: string, motion: string): number | null => {
|
|
111
|
+
// Latest link wins: a Motion re-projected after a branch was recreated should
|
|
112
|
+
// resolve to its current pull request, not its first.
|
|
113
|
+
for (const entry of [...parseEntries(hansard)].reverse()) {
|
|
114
|
+
if (entry.fields['Motion'] !== motion) continue;
|
|
115
|
+
const pr = entry.fields['Pull request'];
|
|
116
|
+
if (pr === undefined) continue;
|
|
117
|
+
const n = Number.parseInt(pr.replace(/^#/, ''), 10);
|
|
118
|
+
if (Number.isInteger(n)) return n;
|
|
119
|
+
}
|
|
120
|
+
return null;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/** Record the link between a Motion and its platform object. */
|
|
124
|
+
export const linkEntry = (
|
|
125
|
+
motion: string,
|
|
126
|
+
pr: number,
|
|
127
|
+
url: string,
|
|
128
|
+
at: string,
|
|
129
|
+
): HansardEntry => ({
|
|
130
|
+
type: 'MOTION_PROJECTED',
|
|
131
|
+
at,
|
|
132
|
+
actor: 'RECORD',
|
|
133
|
+
role: 'OPERATOR',
|
|
134
|
+
fields: {
|
|
135
|
+
Motion: motion,
|
|
136
|
+
'Pull request': `#${pr}`,
|
|
137
|
+
Location: url,
|
|
138
|
+
},
|
|
139
|
+
body: 'The Motion is projected onto the hosting platform. The Hansard remains the record.',
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
/* -------------------------------------------------------------------------- */
|
|
143
|
+
/* Projections */
|
|
144
|
+
/* -------------------------------------------------------------------------- */
|
|
145
|
+
|
|
146
|
+
export interface ProjectionResult {
|
|
147
|
+
/** Did the projection reach the platform? */
|
|
148
|
+
readonly projected: boolean;
|
|
149
|
+
/** What happened, for the operator and the record. */
|
|
150
|
+
readonly detail: string;
|
|
151
|
+
/** Platform reference, when one was created or acted on. */
|
|
152
|
+
readonly ref: string | null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const skipped = (reason: string): ProjectionResult => ({
|
|
156
|
+
projected: false,
|
|
157
|
+
detail: reason,
|
|
158
|
+
ref: null,
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Run a projection, converting any platform failure into a reported result.
|
|
163
|
+
*
|
|
164
|
+
* Deliberately swallows the error. A governance act has already been decided
|
|
165
|
+
* and recorded by the time a projection runs; letting a network fault propagate
|
|
166
|
+
* would abort a caller that has nothing left to undo, and would make the
|
|
167
|
+
* Hansard's correctness depend on GitHub being reachable.
|
|
168
|
+
*/
|
|
169
|
+
const attempt = async (
|
|
170
|
+
what: string,
|
|
171
|
+
run: () => Promise<{ ref: string; detail: string }>,
|
|
172
|
+
): Promise<ProjectionResult> => {
|
|
173
|
+
try {
|
|
174
|
+
const { ref, detail } = await run();
|
|
175
|
+
return { projected: true, detail, ref };
|
|
176
|
+
} catch (error) {
|
|
177
|
+
return {
|
|
178
|
+
projected: false,
|
|
179
|
+
detail: `${what} failed: ${error instanceof Error ? error.message : String(error)} — the governance act stands; the projection is behind`,
|
|
180
|
+
ref: null,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/** Project a called Division onto a review request. */
|
|
186
|
+
export const projectDivision = async (
|
|
187
|
+
provider: ScmProvider | null,
|
|
188
|
+
hansard: string,
|
|
189
|
+
motion: string,
|
|
190
|
+
reviewers: readonly string[],
|
|
191
|
+
): Promise<ProjectionResult> => {
|
|
192
|
+
if (provider === null) return skipped('local-only — no review requested');
|
|
193
|
+
const pr = motionPr(hansard, motion);
|
|
194
|
+
if (pr === null) return skipped(`${motion} is not projected onto a pull request`);
|
|
195
|
+
if (reviewers.length === 0) return skipped('no reviewers named');
|
|
196
|
+
|
|
197
|
+
return attempt('requestReview', async () => {
|
|
198
|
+
const division = await provider.requestReview(pr, reviewers);
|
|
199
|
+
return { ref: division.url, detail: `review requested on #${pr}` };
|
|
200
|
+
});
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Project an Assent onto a merge — the act ADR-0004 defines Assent as.
|
|
205
|
+
*
|
|
206
|
+
* The Division decides and the Assent enacts; this is where enactment actually
|
|
207
|
+
* reaches the world. Until it was wired, `politik assent` recorded a decision
|
|
208
|
+
* that changed nothing.
|
|
209
|
+
*/
|
|
210
|
+
export const projectAssent = async (
|
|
211
|
+
provider: ScmProvider | null,
|
|
212
|
+
hansard: string,
|
|
213
|
+
motion: string,
|
|
214
|
+
strategy: MergeStrategy,
|
|
215
|
+
): Promise<ProjectionResult> => {
|
|
216
|
+
if (provider === null) return skipped('local-only — nothing to merge');
|
|
217
|
+
const pr = motionPr(hansard, motion);
|
|
218
|
+
if (pr === null) return skipped(`${motion} is not projected onto a pull request`);
|
|
219
|
+
|
|
220
|
+
return attempt('merge', async () => {
|
|
221
|
+
const result = await provider.merge(pr, strategy);
|
|
222
|
+
return {
|
|
223
|
+
ref: result.sha,
|
|
224
|
+
detail: result.merged
|
|
225
|
+
? `#${pr} merged via ${strategy} (${result.sha.slice(0, 8)})`
|
|
226
|
+
: `#${pr} was not merged by the platform`,
|
|
227
|
+
};
|
|
228
|
+
});
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
/** Project an Escalation onto an Issue. */
|
|
232
|
+
export const projectEscalation = async (
|
|
233
|
+
provider: ScmProvider | null,
|
|
234
|
+
title: string,
|
|
235
|
+
body: string,
|
|
236
|
+
labels: readonly string[] = ['point-of-order'],
|
|
237
|
+
): Promise<ProjectionResult> => {
|
|
238
|
+
if (provider === null) return skipped('local-only — no issue opened');
|
|
239
|
+
|
|
240
|
+
return attempt('openIssue', async () => {
|
|
241
|
+
const escalation = await provider.openIssue(title, body, labels);
|
|
242
|
+
return { ref: escalation.url, detail: `issue #${escalation.number} opened` };
|
|
243
|
+
});
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
/** Notify the Speaker out of band. */
|
|
247
|
+
export const projectNotification = async (
|
|
248
|
+
provider: ScmProvider | null,
|
|
249
|
+
actor: string,
|
|
250
|
+
message: string,
|
|
251
|
+
): Promise<ProjectionResult> => {
|
|
252
|
+
if (provider === null) return skipped('local-only — no notification sent');
|
|
253
|
+
return attempt('notify', async () => {
|
|
254
|
+
await provider.notify(actor, message);
|
|
255
|
+
return { ref: actor, detail: `notified ${actor}` };
|
|
256
|
+
});
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
/** Close the sitting's milestone as part of prorogation. */
|
|
260
|
+
export const projectProrogation = async (
|
|
261
|
+
provider: ScmProvider | null,
|
|
262
|
+
milestoneId: string | null,
|
|
263
|
+
): Promise<ProjectionResult> => {
|
|
264
|
+
if (provider === null) return skipped('local-only — no milestone closed');
|
|
265
|
+
if (milestoneId === null) return skipped('no milestone declared for this sitting');
|
|
266
|
+
return attempt('closeMilestone', async () => {
|
|
267
|
+
await provider.closeMilestone(milestoneId);
|
|
268
|
+
return { ref: milestoneId, detail: `milestone ${milestoneId} closed` };
|
|
269
|
+
});
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Record a projection outcome in the Hansard.
|
|
274
|
+
*
|
|
275
|
+
* Both outcomes are recorded, including failures. A reader must be able to see
|
|
276
|
+
* that a Motion carried and its merge did not land — the gap between decision
|
|
277
|
+
* and effect is exactly the kind of thing a governance record exists to expose.
|
|
278
|
+
*/
|
|
279
|
+
export const projectionEntry = (
|
|
280
|
+
act: string,
|
|
281
|
+
result: ProjectionResult,
|
|
282
|
+
at: string,
|
|
283
|
+
): HansardEntry => ({
|
|
284
|
+
type: result.projected ? 'PROJECTION' : 'PROJECTION_SKIPPED',
|
|
285
|
+
at,
|
|
286
|
+
actor: 'RECORD',
|
|
287
|
+
role: 'OPERATOR',
|
|
288
|
+
fields: {
|
|
289
|
+
Act: act,
|
|
290
|
+
Outcome: result.detail,
|
|
291
|
+
...(result.ref === null ? {} : { Reference: result.ref }),
|
|
292
|
+
},
|
|
293
|
+
});
|