@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
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Federation — the GLOBAL layer as local traversal (ADR-0008 phase 2).
|
|
3
|
+
*
|
|
4
|
+
* EXECUTION.md § The Politik Tree makes an organisation a 1:N hierarchy of
|
|
5
|
+
* sessions. ADR-0008 makes that tree one repository of nested directories, and
|
|
6
|
+
* this module is the payoff it promised: the registry ("all sessions and their
|
|
7
|
+
* state"), cascade propagation, and roll-up are ordinary reads over one working
|
|
8
|
+
* tree, not cross-repository orchestration. There is no federation *repo* — the
|
|
9
|
+
* tree of directories IS the federation.
|
|
10
|
+
*
|
|
11
|
+
* The engine stayed storage-agnostic; nothing here changes how a session runs.
|
|
12
|
+
* Discovery walks directories; everything downstream (buildTree, rollUp,
|
|
13
|
+
* detectCascades) is pure and reuses tree.ts, ledger.ts and hansard.ts, so a
|
|
14
|
+
* node in a federated tree obeys exactly the governance a standalone one does.
|
|
15
|
+
*
|
|
16
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
20
|
+
import { existsSync } from 'node:fs';
|
|
21
|
+
import { join, resolve, relative } from 'node:path';
|
|
22
|
+
|
|
23
|
+
import { parseCharter } from './charter.ts';
|
|
24
|
+
import { parseState } from './state.ts';
|
|
25
|
+
import { totals } from './ledger.ts';
|
|
26
|
+
import { parseEntries } from './hansard.ts';
|
|
27
|
+
import {
|
|
28
|
+
checkCascade, DEFAULT_CASCADE, type CascadeAlert, type CascadeConfig, type SiblingFault,
|
|
29
|
+
} from './tree.ts';
|
|
30
|
+
|
|
31
|
+
/* -------------------------------------------------------------------------- */
|
|
32
|
+
/* Node model */
|
|
33
|
+
/* -------------------------------------------------------------------------- */
|
|
34
|
+
|
|
35
|
+
export interface FederationNode {
|
|
36
|
+
/** Absolute directory of the node's session. */
|
|
37
|
+
readonly dir: string;
|
|
38
|
+
/** Directory relative to the tree root — the human-facing identity. */
|
|
39
|
+
readonly rel: string;
|
|
40
|
+
readonly guid: string;
|
|
41
|
+
readonly protocol: string;
|
|
42
|
+
readonly state: string;
|
|
43
|
+
/** Suspension cause, when SUSPENDED. */
|
|
44
|
+
readonly cause: string | null;
|
|
45
|
+
readonly since: string | null;
|
|
46
|
+
readonly cost_usd: number;
|
|
47
|
+
readonly tokens: number;
|
|
48
|
+
/** Parent's absolute dir, or null for a root (inherits_from outside the tree). */
|
|
49
|
+
readonly parent: string | null;
|
|
50
|
+
/** Absolute dirs of the immediate children. */
|
|
51
|
+
readonly children: readonly string[];
|
|
52
|
+
readonly depth: number;
|
|
53
|
+
/** Raw record, kept for fault and open-Motion scanning. */
|
|
54
|
+
readonly hansard: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface RawNode {
|
|
58
|
+
readonly dir: string;
|
|
59
|
+
readonly guid: string;
|
|
60
|
+
readonly protocol: string;
|
|
61
|
+
readonly state: string;
|
|
62
|
+
readonly cause: string | null;
|
|
63
|
+
readonly since: string | null;
|
|
64
|
+
readonly cost_usd: number;
|
|
65
|
+
readonly tokens: number;
|
|
66
|
+
readonly parentDir: string | null;
|
|
67
|
+
readonly hansard: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/* -------------------------------------------------------------------------- */
|
|
71
|
+
/* Discovery (I/O) */
|
|
72
|
+
/* -------------------------------------------------------------------------- */
|
|
73
|
+
|
|
74
|
+
const SKIP = new Set(['.git', 'node_modules', '.politik']);
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Every session directory under root — one that carries CHARTER.md and
|
|
78
|
+
* STATE.json. Descends through session directories too: in monorepo mode a node
|
|
79
|
+
* contains its children, so finding a session is never a reason to stop walking.
|
|
80
|
+
*/
|
|
81
|
+
export const findSessionDirs = async (root: string): Promise<readonly string[]> => {
|
|
82
|
+
const found: string[] = [];
|
|
83
|
+
const walk = async (dir: string): Promise<void> => {
|
|
84
|
+
if (existsSync(join(dir, 'CHARTER.md')) && existsSync(join(dir, 'STATE.json'))) {
|
|
85
|
+
found.push(dir);
|
|
86
|
+
}
|
|
87
|
+
let entries: import('node:fs').Dirent[];
|
|
88
|
+
try {
|
|
89
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
90
|
+
} catch {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
for (const entry of entries) {
|
|
94
|
+
if (!entry.isDirectory() || SKIP.has(entry.name)) continue;
|
|
95
|
+
await walk(join(dir, entry.name));
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
await walk(root);
|
|
99
|
+
return found;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** Read one node's records. Returns null if the directory is not a valid session. */
|
|
103
|
+
export const readNode = async (dir: string): Promise<RawNode | null> => {
|
|
104
|
+
const [charterRaw, stateRaw] = await Promise.all([
|
|
105
|
+
readFile(join(dir, 'CHARTER.md'), 'utf8').catch(() => null),
|
|
106
|
+
readFile(join(dir, 'STATE.json'), 'utf8').catch(() => null),
|
|
107
|
+
]);
|
|
108
|
+
if (charterRaw === null || stateRaw === null) return null;
|
|
109
|
+
|
|
110
|
+
const parsed = parseCharter(charterRaw);
|
|
111
|
+
const state = parseState(stateRaw);
|
|
112
|
+
if (!parsed.ok || state === null) return null;
|
|
113
|
+
const charter = parsed.charter;
|
|
114
|
+
|
|
115
|
+
const ledgerDoc = await readFile(join(dir, charter.ledger.path), 'utf8').catch(() => '');
|
|
116
|
+
const hansard = await readFile(join(dir, 'HANSARD.md'), 'utf8').catch(() => '');
|
|
117
|
+
const cost = totals(ledgerDoc);
|
|
118
|
+
|
|
119
|
+
// inherits_from is relative to the child; resolve it to the parent's directory.
|
|
120
|
+
const parentDir = charter.inherits_from === null ? null : resolve(dir, charter.inherits_from);
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
dir,
|
|
124
|
+
guid: state.session_guid,
|
|
125
|
+
protocol: charter.protocol,
|
|
126
|
+
state: state.state,
|
|
127
|
+
cause: state.suspension?.cause ?? null,
|
|
128
|
+
since: state.suspension?.since ?? null,
|
|
129
|
+
cost_usd: cost.cost_usd,
|
|
130
|
+
tokens: cost.tokens,
|
|
131
|
+
parentDir,
|
|
132
|
+
hansard,
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/** Discover and assemble the whole tree rooted at `root`. */
|
|
137
|
+
export const discoverTree = async (root: string): Promise<readonly FederationNode[]> => {
|
|
138
|
+
const dirs = await findSessionDirs(root);
|
|
139
|
+
const raws = (await Promise.all(dirs.map(readNode))).filter((n): n is RawNode => n !== null);
|
|
140
|
+
return buildTree(raws, root);
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/* -------------------------------------------------------------------------- */
|
|
144
|
+
/* Assembly (pure) */
|
|
145
|
+
/* -------------------------------------------------------------------------- */
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Link parent→children and compute depth from the resolved `inherits_from`
|
|
149
|
+
* pointers. A pointer that resolves outside the discovered set makes the node a
|
|
150
|
+
* root — the tree is whatever was found under `root`, not the whole filesystem.
|
|
151
|
+
*/
|
|
152
|
+
export const buildTree = (raws: readonly RawNode[], root: string): readonly FederationNode[] => {
|
|
153
|
+
const byDir = new Map(raws.map((r) => [r.dir, r]));
|
|
154
|
+
const inTree = (dir: string | null): dir is string => dir !== null && byDir.has(dir);
|
|
155
|
+
|
|
156
|
+
const children = new Map<string, string[]>();
|
|
157
|
+
for (const r of raws) {
|
|
158
|
+
if (inTree(r.parentDir)) {
|
|
159
|
+
const list = children.get(r.parentDir) ?? [];
|
|
160
|
+
list.push(r.dir);
|
|
161
|
+
children.set(r.parentDir, list);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const depthOf = (dir: string): number => {
|
|
166
|
+
let depth = 0;
|
|
167
|
+
const seen = new Set<string>();
|
|
168
|
+
let cur = byDir.get(dir);
|
|
169
|
+
while (cur && inTree(cur.parentDir) && !seen.has(cur.dir)) {
|
|
170
|
+
seen.add(cur.dir);
|
|
171
|
+
depth += 1;
|
|
172
|
+
cur = byDir.get(cur.parentDir);
|
|
173
|
+
}
|
|
174
|
+
return depth;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const objByDir = new Map<string, FederationNode>(
|
|
178
|
+
raws.map((r) => [r.dir, {
|
|
179
|
+
dir: r.dir,
|
|
180
|
+
rel: relative(root, r.dir) || '.',
|
|
181
|
+
guid: r.guid,
|
|
182
|
+
protocol: r.protocol,
|
|
183
|
+
state: r.state,
|
|
184
|
+
cause: r.cause,
|
|
185
|
+
since: r.since,
|
|
186
|
+
cost_usd: r.cost_usd,
|
|
187
|
+
tokens: r.tokens,
|
|
188
|
+
parent: inTree(r.parentDir) ? r.parentDir : null,
|
|
189
|
+
children: (children.get(r.dir) ?? []).slice().sort(),
|
|
190
|
+
depth: depthOf(r.dir),
|
|
191
|
+
hansard: r.hansard,
|
|
192
|
+
}]),
|
|
193
|
+
);
|
|
194
|
+
|
|
195
|
+
// Emit in pre-order (a node immediately before its children) so the flat list
|
|
196
|
+
// reads as the tree it is — a child never appears detached from its parent.
|
|
197
|
+
const ordered: FederationNode[] = [];
|
|
198
|
+
const seen = new Set<string>();
|
|
199
|
+
const visit = (dir: string): void => {
|
|
200
|
+
const node = objByDir.get(dir);
|
|
201
|
+
if (node === undefined || seen.has(dir)) return;
|
|
202
|
+
seen.add(dir);
|
|
203
|
+
ordered.push(node);
|
|
204
|
+
for (const child of node.children) visit(child);
|
|
205
|
+
};
|
|
206
|
+
[...objByDir.values()]
|
|
207
|
+
.filter((n) => n.parent === null)
|
|
208
|
+
.sort((a, b) => a.rel.localeCompare(b.rel))
|
|
209
|
+
.forEach((root_) => visit(root_.dir));
|
|
210
|
+
// Any node not reached from a root (a broken pointer or cycle) still shows.
|
|
211
|
+
for (const node of objByDir.values()) if (!seen.has(node.dir)) visit(node.dir);
|
|
212
|
+
|
|
213
|
+
return ordered;
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
/* -------------------------------------------------------------------------- */
|
|
217
|
+
/* Roll-up (pure) */
|
|
218
|
+
/* -------------------------------------------------------------------------- */
|
|
219
|
+
|
|
220
|
+
export interface RollUp {
|
|
221
|
+
readonly nodes: number;
|
|
222
|
+
readonly by_state: Readonly<Record<string, number>>;
|
|
223
|
+
readonly total_cost_usd: number;
|
|
224
|
+
readonly total_tokens: number;
|
|
225
|
+
readonly open_divisions: number;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Motions on the floor: a Division was called and no outcome has been recorded. */
|
|
229
|
+
export const openDivisions = (hansard: string): number => {
|
|
230
|
+
const open = new Set<string>();
|
|
231
|
+
for (const entry of parseEntries(hansard)) {
|
|
232
|
+
const motion = entry.fields['Motion'];
|
|
233
|
+
if (motion === undefined) continue;
|
|
234
|
+
if (entry.type === 'DIVISION_CALLED') open.add(motion);
|
|
235
|
+
else if (entry.type === 'MOTION_CARRIED' || entry.type === 'MOTION_REJECTED') open.delete(motion);
|
|
236
|
+
}
|
|
237
|
+
return open.size;
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
export const rollUp = (nodes: readonly FederationNode[]): RollUp => {
|
|
241
|
+
const by_state: Record<string, number> = {};
|
|
242
|
+
let cost = 0;
|
|
243
|
+
let tokens = 0;
|
|
244
|
+
let open = 0;
|
|
245
|
+
for (const node of nodes) {
|
|
246
|
+
by_state[node.state] = (by_state[node.state] ?? 0) + 1;
|
|
247
|
+
cost += node.cost_usd;
|
|
248
|
+
tokens += node.tokens;
|
|
249
|
+
open += openDivisions(node.hansard);
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
nodes: nodes.length,
|
|
253
|
+
by_state,
|
|
254
|
+
total_cost_usd: cost,
|
|
255
|
+
total_tokens: tokens,
|
|
256
|
+
open_divisions: open,
|
|
257
|
+
};
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
/* -------------------------------------------------------------------------- */
|
|
261
|
+
/* Cascade detection (pure) */
|
|
262
|
+
/* -------------------------------------------------------------------------- */
|
|
263
|
+
|
|
264
|
+
export interface CascadeFinding {
|
|
265
|
+
readonly parent: FederationNode;
|
|
266
|
+
readonly alert: CascadeAlert;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* A fault propagating across siblings. For every parent, gather its SUSPENDED
|
|
271
|
+
* children as sibling faults (signature = the suspension cause) and ask the
|
|
272
|
+
* existing checkCascade whether enough share a cause within the window to warn.
|
|
273
|
+
* Detection only — recording the alert on the parent is the CLI's job, so the
|
|
274
|
+
* traversal stays pure and testable.
|
|
275
|
+
*/
|
|
276
|
+
export const detectCascades = (
|
|
277
|
+
nodes: readonly FederationNode[],
|
|
278
|
+
now: string,
|
|
279
|
+
config: CascadeConfig = DEFAULT_CASCADE,
|
|
280
|
+
): readonly CascadeFinding[] => {
|
|
281
|
+
const byDir = new Map(nodes.map((n) => [n.dir, n]));
|
|
282
|
+
const findings: CascadeFinding[] = [];
|
|
283
|
+
|
|
284
|
+
for (const parent of nodes) {
|
|
285
|
+
if (parent.children.length === 0) continue;
|
|
286
|
+
const faults: SiblingFault[] = [];
|
|
287
|
+
for (const childDir of parent.children) {
|
|
288
|
+
const child = byDir.get(childDir);
|
|
289
|
+
if (child && child.state === 'SUSPENDED' && child.cause !== null && child.since !== null) {
|
|
290
|
+
faults.push({ node: child.guid, signature: child.cause, at: child.since });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
if (faults.length === 0) continue;
|
|
294
|
+
const alert = checkCascade(faults, now, config);
|
|
295
|
+
if (alert.triggered) findings.push({ parent, alert });
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return findings;
|
|
299
|
+
};
|
package/src/git.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Committing the record.
|
|
3
|
+
*
|
|
4
|
+
* The Hansard is the session, and this framework's own Standing Orders tell
|
|
5
|
+
* every actor "commit your result; uncommitted work does not exist". That rule
|
|
6
|
+
* binds the engine too: a governance act written to a file but never committed
|
|
7
|
+
* has, by the framework's own definition, not happened.
|
|
8
|
+
*
|
|
9
|
+
* On a GitHub-backed session `ScmProvider.commit()` lands these writes. Local
|
|
10
|
+
* sessions had no equivalent, so the Division and Assent cycle sat dirty in the
|
|
11
|
+
* working tree — a record that did not exist. This module closes that gap.
|
|
12
|
+
*
|
|
13
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { spawn } from 'node:child_process';
|
|
17
|
+
import { existsSync } from 'node:fs';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
|
|
20
|
+
export interface CommitResult {
|
|
21
|
+
readonly committed: boolean;
|
|
22
|
+
/** Populated when a commit was made. */
|
|
23
|
+
readonly sha: string | null;
|
|
24
|
+
readonly reason: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const git = (
|
|
28
|
+
dir: string,
|
|
29
|
+
args: readonly string[],
|
|
30
|
+
spawnFn: typeof spawn,
|
|
31
|
+
): Promise<{ code: number; out: string }> =>
|
|
32
|
+
new Promise((resolve) => {
|
|
33
|
+
const child = spawnFn('git', [...args], {
|
|
34
|
+
cwd: dir,
|
|
35
|
+
shell: false,
|
|
36
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
37
|
+
});
|
|
38
|
+
let output = '';
|
|
39
|
+
child.stdout?.on('data', (c: Buffer) => {
|
|
40
|
+
output += c.toString();
|
|
41
|
+
});
|
|
42
|
+
child.on('close', (code) => resolve({ code: code ?? 1, out: output.trim() }));
|
|
43
|
+
child.on('error', () => resolve({ code: 1, out: '' }));
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Commit the session record.
|
|
48
|
+
*
|
|
49
|
+
* Deliberately narrow: only the files named are staged. A governance command
|
|
50
|
+
* must never sweep up whatever else happens to be dirty in the working tree —
|
|
51
|
+
* an actor's half-finished work is not part of the record of a Division, and
|
|
52
|
+
* committing it under the Speaker's name would misattribute it.
|
|
53
|
+
*
|
|
54
|
+
* Silent no-ops rather than failures when the directory is not a git
|
|
55
|
+
* repository: a session can legitimately be exercised outside git (tests,
|
|
56
|
+
* dry runs), and the caller decides whether that matters.
|
|
57
|
+
*/
|
|
58
|
+
export const commitRecord = async (
|
|
59
|
+
dir: string,
|
|
60
|
+
message: string,
|
|
61
|
+
paths: readonly string[] = ['HANSARD.md', 'STATE.json'],
|
|
62
|
+
spawnFn: typeof spawn = spawn,
|
|
63
|
+
): Promise<CommitResult> => {
|
|
64
|
+
const isRepo = await git(dir, ['rev-parse', '--is-inside-work-tree'], spawnFn);
|
|
65
|
+
if (isRepo.code !== 0) {
|
|
66
|
+
return { committed: false, sha: null, reason: 'not a git repository' };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// `git add` fails outright if any pathspec matches nothing, which would mean
|
|
70
|
+
// a session that has not yet written STATE.json commits nothing at all.
|
|
71
|
+
// Filter to what exists so one absent file cannot suppress the whole record.
|
|
72
|
+
const present: string[] = [];
|
|
73
|
+
for (const path of paths) {
|
|
74
|
+
if (existsSync(join(dir, path))) present.push(path);
|
|
75
|
+
}
|
|
76
|
+
if (present.length === 0) {
|
|
77
|
+
return { committed: false, sha: null, reason: 'no record files present' };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const add = await git(dir, ['add', '--', ...present], spawnFn);
|
|
81
|
+
if (add.code !== 0) {
|
|
82
|
+
return { committed: false, sha: null, reason: 'nothing to stage' };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const staged = await git(dir, ['diff', '--cached', '--name-only'], spawnFn);
|
|
86
|
+
if (staged.out === '') {
|
|
87
|
+
return { committed: false, sha: null, reason: 'no changes to record' };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const commit = await git(dir, ['commit', '-m', message], spawnFn);
|
|
91
|
+
if (commit.code !== 0) {
|
|
92
|
+
return { committed: false, sha: null, reason: 'commit failed' };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const sha = await git(dir, ['rev-parse', 'HEAD'], spawnFn);
|
|
96
|
+
return { committed: true, sha: sha.out || null, reason: 'recorded' };
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Make a session's directory record-bearing. Writ Drop "creates the session
|
|
101
|
+
* repo"; without a repo, `commitRecord` silently no-ops and no act is recorded.
|
|
102
|
+
*
|
|
103
|
+
* Two shapes, auto-detected (ADR-0008 — a session is a git-tracked *directory*,
|
|
104
|
+
* standalone repo or subtree of one):
|
|
105
|
+
* - **Standalone**: the directory is not yet in a repo → `git init` it and land
|
|
106
|
+
* the writ drop, attributed to the Speaker.
|
|
107
|
+
* - **Monorepo**: the directory already sits inside a repo (a parent tree, or a
|
|
108
|
+
* clone) → commit the writ drop *to that repo* rather than nesting a new one.
|
|
109
|
+
* Per-commit identity, so the enclosing repo's own config is untouched;
|
|
110
|
+
* no-ops if there is nothing to commit (e.g. a re-run on a clone).
|
|
111
|
+
*
|
|
112
|
+
* Best-effort: a host without git degrades to a plain directory.
|
|
113
|
+
*/
|
|
114
|
+
export const initSessionRepo = async (
|
|
115
|
+
dir: string,
|
|
116
|
+
speaker: string,
|
|
117
|
+
guid: string,
|
|
118
|
+
spawnFn: typeof spawn = spawn,
|
|
119
|
+
opts: { readonly standalone?: boolean } = {},
|
|
120
|
+
): Promise<CommitResult> => {
|
|
121
|
+
const isRepo = await git(dir, ['rev-parse', '--is-inside-work-tree'], spawnFn);
|
|
122
|
+
// Default is auto-detect (monorepo when already inside a repo). `standalone`
|
|
123
|
+
// is the explicit opt-out (ADR-0008 phase 3): give this session its own repo
|
|
124
|
+
// even inside an enclosing tree — for per-session GitHub projection or a
|
|
125
|
+
// per-node permission boundary, the two cases standalone mode exists for.
|
|
126
|
+
if (isRepo.code === 0 && opts.standalone !== true) {
|
|
127
|
+
// Monorepo: land the writ drop in the enclosing repo. `add .` stages only
|
|
128
|
+
// this session's subtree; the per-commit identity attributes it to the
|
|
129
|
+
// Speaker without rewriting the parent repo's config. Exclude `*.tmp` — an
|
|
130
|
+
// atomic write interrupted mid-flight can orphan one, and it must never enter
|
|
131
|
+
// the record.
|
|
132
|
+
await git(dir, ['add', '.', ':(exclude)*.tmp'], spawnFn);
|
|
133
|
+
const commit = await git(
|
|
134
|
+
dir,
|
|
135
|
+
['-c', `user.name=${speaker}`, '-c', `user.email=${speaker}@politik.local`,
|
|
136
|
+
'commit', '-m', `writ drop: session ${guid}`],
|
|
137
|
+
spawnFn,
|
|
138
|
+
);
|
|
139
|
+
if (commit.code !== 0) {
|
|
140
|
+
return { committed: false, sha: null, reason: 'existing repository — nothing to commit' };
|
|
141
|
+
}
|
|
142
|
+
const sha = await git(dir, ['rev-parse', 'HEAD'], spawnFn);
|
|
143
|
+
return { committed: true, sha: sha.out || null, reason: 'writ drop committed to the enclosing repo' };
|
|
144
|
+
}
|
|
145
|
+
// A forced standalone inside an enclosing repo nests a fresh repo here — a
|
|
146
|
+
// deliberate isolation boundary, not the accidental nested `.git` the
|
|
147
|
+
// auto-detect exists to avoid. Name it so the operator knows it was on purpose.
|
|
148
|
+
const nested = isRepo.code === 0;
|
|
149
|
+
if ((await git(dir, ['init', '-q'], spawnFn)).code !== 0) {
|
|
150
|
+
return { committed: false, sha: null, reason: 'git unavailable — local directory only' };
|
|
151
|
+
}
|
|
152
|
+
await git(dir, ['config', 'user.name', speaker], spawnFn);
|
|
153
|
+
await git(dir, ['config', 'user.email', `${speaker}@politik.local`], spawnFn);
|
|
154
|
+
await git(dir, ['add', '-A', '.', ':(exclude)*.tmp'], spawnFn);
|
|
155
|
+
const commit = await git(dir, ['commit', '-m', `writ drop: session ${guid}`], spawnFn);
|
|
156
|
+
if (commit.code !== 0) return { committed: false, sha: null, reason: 'repo initialized, nothing to commit' };
|
|
157
|
+
const sha = await git(dir, ['rev-parse', 'HEAD'], spawnFn);
|
|
158
|
+
return {
|
|
159
|
+
committed: true,
|
|
160
|
+
sha: sha.out || null,
|
|
161
|
+
reason: nested ? 'standalone repo initialized (isolated inside an enclosing tree)' : 'session repo initialized',
|
|
162
|
+
};
|
|
163
|
+
};
|
package/src/hansard.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hansard commit writer.
|
|
3
|
+
*
|
|
4
|
+
* HANSARD.md is the append-only attributed record of a proceeding
|
|
5
|
+
* (POLITIK-ARCHITECTURE.md § File Sovereignty Rules: "Append only, never edited").
|
|
6
|
+
* The RECORD agent writes it; no actor edits an entry once committed.
|
|
7
|
+
*
|
|
8
|
+
* ## On the format
|
|
9
|
+
*
|
|
10
|
+
* The format is fixed by ADR-0005. Entries are H2 under the document's H1 title
|
|
11
|
+
* (ruling 1), headed `## <ISO-8601 UTC> — <RECORD_TYPE>` (ruling 2). Record
|
|
12
|
+
* types are an open string set, always written in CANON and never translated
|
|
13
|
+
* into protocol vocabulary (ruling 3). Attribution is mandatory (ruling 4).
|
|
14
|
+
* Fields are single-line; prose goes in the body (ruling 5). Append-only is
|
|
15
|
+
* mechanical: a new document must contain the old one verbatim as a prefix
|
|
16
|
+
* (ruling 6). Reading back is best-effort and never authoritative — git history
|
|
17
|
+
* is (ruling 7).
|
|
18
|
+
*
|
|
19
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { Role } from './canon.ts';
|
|
23
|
+
|
|
24
|
+
/* -------------------------------------------------------------------------- */
|
|
25
|
+
/* Record types */
|
|
26
|
+
/* -------------------------------------------------------------------------- */
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Record types named in the source documents. Not exhaustive and not a closed
|
|
30
|
+
* enum — `HansardEntry.type` accepts any string so a protocol may record events
|
|
31
|
+
* these documents never anticipated.
|
|
32
|
+
*/
|
|
33
|
+
export const RECORD_TYPES = {
|
|
34
|
+
WRIT_DROP: 'WRIT_DROP',
|
|
35
|
+
SESSION_INVALID: 'SESSION_INVALID',
|
|
36
|
+
SESSION_FAULT: 'SESSION_FAULT',
|
|
37
|
+
SESSION_FAULT_CRITICAL: 'SESSION_FAULT_CRITICAL',
|
|
38
|
+
FAULT_RESOLVED: 'FAULT_RESOLVED',
|
|
39
|
+
FAULT_RESOLVED_AUTO: 'FAULT_RESOLVED_AUTO',
|
|
40
|
+
ACTOR_STATE: 'ACTOR_STATE',
|
|
41
|
+
} as const;
|
|
42
|
+
|
|
43
|
+
export type RecordType = string;
|
|
44
|
+
|
|
45
|
+
/* -------------------------------------------------------------------------- */
|
|
46
|
+
/* Entry */
|
|
47
|
+
/* -------------------------------------------------------------------------- */
|
|
48
|
+
|
|
49
|
+
export interface HansardEntry {
|
|
50
|
+
/** Record type, e.g. WRIT_DROP. Rendered as the entry heading. */
|
|
51
|
+
readonly type: RecordType;
|
|
52
|
+
/** ISO-8601 UTC. Supplied by the caller — this module reads no clock. */
|
|
53
|
+
readonly at: string;
|
|
54
|
+
/** Acting actor's handle. Attribution is not optional in a Hansard. */
|
|
55
|
+
readonly actor: string;
|
|
56
|
+
/** The actor's CANON role at the time of the act. */
|
|
57
|
+
readonly role: Role;
|
|
58
|
+
/** Bold-label fields, rendered in insertion order. */
|
|
59
|
+
readonly fields?: Readonly<Record<string, string>>;
|
|
60
|
+
/** Free prose appended after the fields. */
|
|
61
|
+
readonly body?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Thrown when an entry cannot be attributed. An unattributed record is not a Hansard record. */
|
|
65
|
+
export class HansardError extends Error {
|
|
66
|
+
constructor(message: string) {
|
|
67
|
+
super(message);
|
|
68
|
+
this.name = 'HansardError';
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/* -------------------------------------------------------------------------- */
|
|
73
|
+
/* Rendering */
|
|
74
|
+
/* -------------------------------------------------------------------------- */
|
|
75
|
+
|
|
76
|
+
const escapeField = (value: string): string => value.replace(/\r?\n/g, ' ').trim();
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Render one entry.
|
|
80
|
+
*
|
|
81
|
+
* Multi-line field values are collapsed to a single line: a field that spans
|
|
82
|
+
* lines would be indistinguishable from the prose body when the file is read
|
|
83
|
+
* back, and the Hansard's value depends on being unambiguously parseable.
|
|
84
|
+
* Long-form content belongs in `body`.
|
|
85
|
+
*/
|
|
86
|
+
export const renderEntry = (entry: HansardEntry): string => {
|
|
87
|
+
if (entry.actor.trim() === '') {
|
|
88
|
+
throw new HansardError('Hansard entry requires an actor — records are attributed');
|
|
89
|
+
}
|
|
90
|
+
if (entry.type.trim() === '') {
|
|
91
|
+
throw new HansardError('Hansard entry requires a record type');
|
|
92
|
+
}
|
|
93
|
+
if (entry.at.trim() === '') {
|
|
94
|
+
throw new HansardError('Hansard entry requires a timestamp');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const lines = [
|
|
98
|
+
`## ${entry.at} — ${entry.type}`,
|
|
99
|
+
'',
|
|
100
|
+
`**Actor:** ${entry.actor} (${entry.role})`,
|
|
101
|
+
];
|
|
102
|
+
|
|
103
|
+
for (const [key, value] of Object.entries(entry.fields ?? {})) {
|
|
104
|
+
lines.push(`**${key}:** ${escapeField(value)}`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (entry.body !== undefined && entry.body.trim() !== '') {
|
|
108
|
+
lines.push('', entry.body.trim());
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
lines.push('');
|
|
112
|
+
return lines.join('\n');
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/* -------------------------------------------------------------------------- */
|
|
116
|
+
/* Append */
|
|
117
|
+
/* -------------------------------------------------------------------------- */
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Append an entry to a Hansard document.
|
|
121
|
+
*
|
|
122
|
+
* Pure: takes the current document, returns the new one. The caller commits it
|
|
123
|
+
* through an ScmProvider. Existing content is never rewritten — the returned
|
|
124
|
+
* document always starts with the input verbatim, which is the append-only
|
|
125
|
+
* guarantee made mechanical.
|
|
126
|
+
*/
|
|
127
|
+
export const appendEntry = (document: string, entry: HansardEntry): string => {
|
|
128
|
+
const base = document.endsWith('\n') || document === '' ? document : `${document}\n`;
|
|
129
|
+
return `${base}\n${renderEntry(entry)}`;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/** Append several entries in order. */
|
|
133
|
+
export const appendEntries = (
|
|
134
|
+
document: string,
|
|
135
|
+
entries: readonly HansardEntry[],
|
|
136
|
+
): string => entries.reduce(appendEntry, document);
|
|
137
|
+
|
|
138
|
+
/* -------------------------------------------------------------------------- */
|
|
139
|
+
/* Reading back */
|
|
140
|
+
/* -------------------------------------------------------------------------- */
|
|
141
|
+
|
|
142
|
+
export interface ParsedEntry {
|
|
143
|
+
readonly type: string;
|
|
144
|
+
readonly at: string;
|
|
145
|
+
readonly actor: string;
|
|
146
|
+
readonly role: string;
|
|
147
|
+
readonly fields: Readonly<Record<string, string>>;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const ENTRY_HEADING = /^##\s+(\S+)\s+—\s+(.+?)\s*$/;
|
|
151
|
+
const FIELD_LINE = /^\*\*(.+?):\*\*\s*(.*)$/;
|
|
152
|
+
const ACTOR_VALUE = /^(.*?)\s*\(([A-Z]+)\)\s*$/;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Read entries back out of a Hansard document.
|
|
156
|
+
*
|
|
157
|
+
* Provided so the record can be audited and so tests can assert what was
|
|
158
|
+
* written. Best-effort: a document that predates this writer, or that a future
|
|
159
|
+
* Phase 4 spec reshapes, may parse partially. Reading is never authoritative —
|
|
160
|
+
* git history is.
|
|
161
|
+
*/
|
|
162
|
+
export const parseEntries = (document: string): readonly ParsedEntry[] => {
|
|
163
|
+
const entries: ParsedEntry[] = [];
|
|
164
|
+
const lines = document.replace(/\r\n/g, '\n').split('\n');
|
|
165
|
+
|
|
166
|
+
let current: { at: string; type: string; fields: Record<string, string> } | null = null;
|
|
167
|
+
|
|
168
|
+
const flush = () => {
|
|
169
|
+
if (current === null) return;
|
|
170
|
+
const actorRaw = current.fields['Actor'] ?? '';
|
|
171
|
+
const match = ACTOR_VALUE.exec(actorRaw);
|
|
172
|
+
const { Actor: _actor, ...rest } = current.fields;
|
|
173
|
+
entries.push({
|
|
174
|
+
type: current.type,
|
|
175
|
+
at: current.at,
|
|
176
|
+
actor: (match?.[1] ?? actorRaw).trim(),
|
|
177
|
+
role: match?.[2] ?? '',
|
|
178
|
+
fields: rest,
|
|
179
|
+
});
|
|
180
|
+
current = null;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
for (const line of lines) {
|
|
184
|
+
const heading = ENTRY_HEADING.exec(line);
|
|
185
|
+
if (heading) {
|
|
186
|
+
flush();
|
|
187
|
+
current = { at: heading[1] ?? '', type: heading[2] ?? '', fields: {} };
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
if (current === null) continue;
|
|
191
|
+
const field = FIELD_LINE.exec(line);
|
|
192
|
+
if (field) current.fields[field[1] ?? ''] = (field[2] ?? '').trim();
|
|
193
|
+
}
|
|
194
|
+
flush();
|
|
195
|
+
|
|
196
|
+
return entries;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
/** The most recent entry, or null for an empty Hansard. */
|
|
200
|
+
export const lastEntry = (document: string): ParsedEntry | null =>
|
|
201
|
+
parseEntries(document).at(-1) ?? null;
|