@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/quorum.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quorum check.
|
|
3
|
+
*
|
|
4
|
+
* Quorum is the minimum number of actors for a valid Division
|
|
5
|
+
* (RUNTIME.md § SESSION QUORUM, MINIMUM CAST AND SINGLE-PLAYER SESSIONS).
|
|
6
|
+
* Two distinct gates live here and are frequently confused:
|
|
7
|
+
*
|
|
8
|
+
* - **minimum_cast** — a Writ Drop gate. Are the required constituencies
|
|
9
|
+
* declared at all? Enforced by the Charter validator (ADR-0002 rule 3).
|
|
10
|
+
* - **quorum** — a runtime gate. Are enough actors *present right now* for a
|
|
11
|
+
* Division to be valid? That is this module.
|
|
12
|
+
*
|
|
13
|
+
* `quorum: 1` is a legitimate configuration, not a degenerate one: a
|
|
14
|
+
* single-player session whose governance value is the audit trail and the
|
|
15
|
+
* structured constraint rather than multi-agent debate.
|
|
16
|
+
*
|
|
17
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { Role } from './canon.ts';
|
|
21
|
+
|
|
22
|
+
/* -------------------------------------------------------------------------- */
|
|
23
|
+
/* Override */
|
|
24
|
+
/* -------------------------------------------------------------------------- */
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A Speaker's explicit acknowledgement that the session proceeds with a
|
|
28
|
+
* reduced cast. Always visible in the Hansard — it cannot be hidden.
|
|
29
|
+
*/
|
|
30
|
+
export interface QuorumOverride {
|
|
31
|
+
readonly enabled: boolean;
|
|
32
|
+
/** Required. A degraded session with no stated reason is not auditable. */
|
|
33
|
+
readonly reason: string;
|
|
34
|
+
/** Must be AUTHORITY. Nobody else can acknowledge a degraded session. */
|
|
35
|
+
readonly acknowledged_by: Role;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/* -------------------------------------------------------------------------- */
|
|
39
|
+
/* Result */
|
|
40
|
+
/* -------------------------------------------------------------------------- */
|
|
41
|
+
|
|
42
|
+
export interface QuorumResult {
|
|
43
|
+
/** May a Division proceed? */
|
|
44
|
+
readonly met: boolean;
|
|
45
|
+
readonly required: number;
|
|
46
|
+
readonly present: number;
|
|
47
|
+
/** True when quorum failed on the numbers but an override carried it. */
|
|
48
|
+
readonly degraded: boolean;
|
|
49
|
+
/** Populated when the check fails, or when an override is invalid. */
|
|
50
|
+
readonly reason: string | null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface QuorumInput {
|
|
54
|
+
readonly required: number;
|
|
55
|
+
/** Actors present and eligible to vote right now. */
|
|
56
|
+
readonly present: number;
|
|
57
|
+
readonly override?: QuorumOverride | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/* -------------------------------------------------------------------------- */
|
|
61
|
+
/* Check */
|
|
62
|
+
/* -------------------------------------------------------------------------- */
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Evaluate quorum.
|
|
66
|
+
*
|
|
67
|
+
* An override that fails its own preconditions does **not** carry the session:
|
|
68
|
+
* a malformed override is treated as no override at all, because a degraded
|
|
69
|
+
* session that cannot be audited is worse than a halted one.
|
|
70
|
+
*/
|
|
71
|
+
export const checkQuorum = (input: QuorumInput): QuorumResult => {
|
|
72
|
+
const { required, present } = input;
|
|
73
|
+
|
|
74
|
+
if (present >= required) {
|
|
75
|
+
return { met: true, required, present, degraded: false, reason: null };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const override = input.override ?? null;
|
|
79
|
+
if (override === null || !override.enabled) {
|
|
80
|
+
return {
|
|
81
|
+
met: false,
|
|
82
|
+
required,
|
|
83
|
+
present,
|
|
84
|
+
degraded: false,
|
|
85
|
+
reason: `quorum not met: ${present} of ${required} actors present`,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (override.reason.trim() === '') {
|
|
90
|
+
return {
|
|
91
|
+
met: false,
|
|
92
|
+
required,
|
|
93
|
+
present,
|
|
94
|
+
degraded: false,
|
|
95
|
+
reason: 'quorum_override requires an explicit quorum_override_reason',
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (override.acknowledged_by !== 'AUTHORITY') {
|
|
100
|
+
return {
|
|
101
|
+
met: false,
|
|
102
|
+
required,
|
|
103
|
+
present,
|
|
104
|
+
degraded: false,
|
|
105
|
+
reason: `quorum_override must be acknowledged by AUTHORITY, not ${override.acknowledged_by}`,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
met: true,
|
|
111
|
+
required,
|
|
112
|
+
present,
|
|
113
|
+
degraded: true,
|
|
114
|
+
reason: override.reason.trim(),
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Render the Hansard fields for a quorum decision.
|
|
120
|
+
*
|
|
121
|
+
* A degraded session must be legible to any later reviewer, so the override
|
|
122
|
+
* and its reason are recorded as fields rather than buried in prose.
|
|
123
|
+
*/
|
|
124
|
+
export const quorumFields = (result: QuorumResult): Record<string, string> => {
|
|
125
|
+
const fields: Record<string, string> = {
|
|
126
|
+
Quorum: result.met ? 'MET' : 'NOT MET',
|
|
127
|
+
Required: String(result.required),
|
|
128
|
+
Present: String(result.present),
|
|
129
|
+
};
|
|
130
|
+
if (result.degraded) {
|
|
131
|
+
fields['Degraded'] = 'Yes — quorum_override acknowledged by AUTHORITY';
|
|
132
|
+
fields['Override reason'] = result.reason ?? '';
|
|
133
|
+
} else if (!result.met && result.reason !== null) {
|
|
134
|
+
fields['Reason'] = result.reason;
|
|
135
|
+
}
|
|
136
|
+
return fields;
|
|
137
|
+
};
|
package/src/runner.ts
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session runner — the engine loop.
|
|
3
|
+
*
|
|
4
|
+
* Everything else in this framework is a component: parse a Charter, elect a
|
|
5
|
+
* broadcaster, compose a prompt, spawn an agent, append a record. This module
|
|
6
|
+
* is what asks them to happen in order, and it is the difference between a
|
|
7
|
+
* framework that is tested and a framework that has run.
|
|
8
|
+
*
|
|
9
|
+
* broadcast -> elect -> compose -> spawn -> capture -> record -> settle
|
|
10
|
+
*
|
|
11
|
+
* The loop is deliberately thin. Every decision it makes has already been made
|
|
12
|
+
* somewhere pure and testable; the runner's job is sequencing and I/O, not
|
|
13
|
+
* governance. If a governance question is being answered here, it is in the
|
|
14
|
+
* wrong place.
|
|
15
|
+
*
|
|
16
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { spawn } from 'node:child_process';
|
|
20
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
21
|
+
import { join } from 'node:path';
|
|
22
|
+
|
|
23
|
+
import { findAgent, composePrompt, type AgentSpec } from './agents.ts';
|
|
24
|
+
import type { Role, Verb } from './canon.ts';
|
|
25
|
+
import { parseCharter, type Charter } from './charter.ts';
|
|
26
|
+
import { parseEnvelope, claimSlot, type Envelope } from './envelope.ts';
|
|
27
|
+
import { standForElection, bowOut, type ElectionOptions } from './election.ts';
|
|
28
|
+
import { nodeLockFs } from './lockfs.ts';
|
|
29
|
+
import { appendEntry, type HansardEntry } from './hansard.ts';
|
|
30
|
+
import { spawnAgent, type SpawnResult } from './spawn.ts';
|
|
31
|
+
import {
|
|
32
|
+
appendLedgerRow, parseResultText, parseUsage, type Usage,
|
|
33
|
+
} from './ledger.ts';
|
|
34
|
+
import { createState, parseState, serializeState, type SessionStateFile } from './state.ts';
|
|
35
|
+
import { checkCapability, parseProfile } from './capability.ts';
|
|
36
|
+
import { breachEntry, checkContainment } from './containment.ts';
|
|
37
|
+
import {
|
|
38
|
+
DEFAULT_FAULT_HANDLING, autoResolvedRecord, classify, faultRecord, shouldRetry,
|
|
39
|
+
type Classification,
|
|
40
|
+
} from './fault.ts';
|
|
41
|
+
|
|
42
|
+
/* -------------------------------------------------------------------------- */
|
|
43
|
+
/* Inputs */
|
|
44
|
+
/* -------------------------------------------------------------------------- */
|
|
45
|
+
|
|
46
|
+
export interface RunOptions {
|
|
47
|
+
/** Session repo working directory. Agents run here and may not go above it. */
|
|
48
|
+
readonly dir: string;
|
|
49
|
+
/** Registry id of the agent to seat, e.g. `claude-code`. */
|
|
50
|
+
readonly agent_id: string;
|
|
51
|
+
/** Handle recorded in the Hansard for this agent. */
|
|
52
|
+
readonly actor: string;
|
|
53
|
+
/** Constituency to seat the agent in. */
|
|
54
|
+
readonly role: Role;
|
|
55
|
+
/** The business — becomes the envelope prompt. */
|
|
56
|
+
readonly task: string;
|
|
57
|
+
/** ISO-8601 UTC. Supplied by the caller; the runner reads no clock. */
|
|
58
|
+
readonly now: string;
|
|
59
|
+
/** Verbs the Charter grants this role. */
|
|
60
|
+
readonly verbs?: readonly Verb[];
|
|
61
|
+
readonly timeout_ms?: number;
|
|
62
|
+
/**
|
|
63
|
+
* Ask the agent for structured output so the LEDGER can record real tokens
|
|
64
|
+
* and cost. On by default: an unmeasured turn is a hole in the cost record.
|
|
65
|
+
*/
|
|
66
|
+
readonly measure?: boolean;
|
|
67
|
+
/** Directory for constituency lockfiles. Defaults to the session's .politik. */
|
|
68
|
+
readonly lock_dir?: string;
|
|
69
|
+
/** Injectable for tests. */
|
|
70
|
+
readonly spawnFn?: typeof spawn;
|
|
71
|
+
/**
|
|
72
|
+
* Wait between retries. Injectable so tests do not sleep for minutes.
|
|
73
|
+
*
|
|
74
|
+
* A synchronous CLI blocking for the documented five minutes is a real cost;
|
|
75
|
+
* an operator who wants control passes `--retry-delay 0` or sets it in the
|
|
76
|
+
* Charter. The alternative — scheduling the retry — needs a daemon this
|
|
77
|
+
* architecture deliberately does not have.
|
|
78
|
+
*/
|
|
79
|
+
readonly sleepFn?: (ms: number) => Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* A broadcast received from the bus.
|
|
82
|
+
*
|
|
83
|
+
* When absent the runner synthesizes an envelope from `task` — the direct
|
|
84
|
+
* invocation path. When present the session is genuinely broadcast-driven:
|
|
85
|
+
* the envelope came off the transport and carries the slot count the
|
|
86
|
+
* broadcaster published, not one this process invented.
|
|
87
|
+
*/
|
|
88
|
+
readonly envelope?: Envelope;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type RunOutcome =
|
|
92
|
+
| {
|
|
93
|
+
readonly ok: true;
|
|
94
|
+
readonly result: SpawnResult;
|
|
95
|
+
readonly entry: HansardEntry;
|
|
96
|
+
readonly files_touched: readonly string[];
|
|
97
|
+
/** The turn completed but the agent filed a Point of Order, so the sitting is now suspended. */
|
|
98
|
+
readonly suspended?: boolean;
|
|
99
|
+
}
|
|
100
|
+
| { readonly ok: false; readonly reason: string; readonly entry?: HansardEntry };
|
|
101
|
+
|
|
102
|
+
/* -------------------------------------------------------------------------- */
|
|
103
|
+
/* Helpers */
|
|
104
|
+
/* -------------------------------------------------------------------------- */
|
|
105
|
+
|
|
106
|
+
const readIf = async (path: string): Promise<string | null> => {
|
|
107
|
+
try {
|
|
108
|
+
return await readFile(path, 'utf8');
|
|
109
|
+
} catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const git = (dir: string, args: readonly string[], spawnFn: typeof spawn): Promise<string> =>
|
|
115
|
+
new Promise((resolve) => {
|
|
116
|
+
const child = spawnFn('git', [...args], {
|
|
117
|
+
cwd: dir,
|
|
118
|
+
shell: false,
|
|
119
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
120
|
+
});
|
|
121
|
+
let output = '';
|
|
122
|
+
child.stdout?.on('data', (c: Buffer) => {
|
|
123
|
+
output += c.toString();
|
|
124
|
+
});
|
|
125
|
+
child.on('close', () => resolve(output.trim()));
|
|
126
|
+
child.on('error', () => resolve(''));
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
/** Uncommitted work in the tree. */
|
|
130
|
+
const dirtyFiles = async (dir: string, spawnFn: typeof spawn): Promise<string[]> =>
|
|
131
|
+
(await git(dir, ['status', '--porcelain'], spawnFn))
|
|
132
|
+
.split('\n')
|
|
133
|
+
.map((l) => l.slice(3).trim())
|
|
134
|
+
.filter((l) => l.length > 0);
|
|
135
|
+
|
|
136
|
+
/** Current HEAD, or empty on a repo with no commits. */
|
|
137
|
+
const head = (dir: string, spawnFn: typeof spawn): Promise<string> =>
|
|
138
|
+
git(dir, ['rev-parse', 'HEAD'], spawnFn);
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Files the agent touched — committed *or* left in the tree.
|
|
142
|
+
*
|
|
143
|
+
* Both halves are necessary. The Standing Orders tell agents "commit your
|
|
144
|
+
* result; uncommitted work does not exist", so a well-behaved agent leaves a
|
|
145
|
+
* clean tree and a new commit — and a working-tree diff alone would report that
|
|
146
|
+
* it did nothing. The first live session did exactly this: the agent wrote and
|
|
147
|
+
* committed a Motion, and the runner recorded "files touched: none".
|
|
148
|
+
*
|
|
149
|
+
* Asking git rather than tracking writes ourselves, because the agent is an
|
|
150
|
+
* opaque process and the repository is the authority on what changed.
|
|
151
|
+
*/
|
|
152
|
+
const filesTouched = async (
|
|
153
|
+
dir: string,
|
|
154
|
+
beforeHead: string,
|
|
155
|
+
beforeDirty: readonly string[],
|
|
156
|
+
spawnFn: typeof spawn,
|
|
157
|
+
): Promise<string[]> => {
|
|
158
|
+
const afterHead = await head(dir, spawnFn);
|
|
159
|
+
const committed =
|
|
160
|
+
afterHead !== '' && beforeHead !== '' && afterHead !== beforeHead
|
|
161
|
+
? (await git(dir, ['diff', '--name-only', `${beforeHead}..${afterHead}`], spawnFn))
|
|
162
|
+
.split('\n')
|
|
163
|
+
.filter((l) => l.length > 0)
|
|
164
|
+
: [];
|
|
165
|
+
|
|
166
|
+
const afterDirty = await dirtyFiles(dir, spawnFn);
|
|
167
|
+
const newlyDirty = afterDirty.filter((f) => !beforeDirty.includes(f));
|
|
168
|
+
|
|
169
|
+
return [...new Set([...committed, ...newlyDirty])];
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
/** Last N entries of the Hansard, as context for a stateless agent. */
|
|
173
|
+
const recentRecord = (hansard: string, entries = 3): string => {
|
|
174
|
+
const parts = hansard.split(/^## /m).slice(1);
|
|
175
|
+
return parts
|
|
176
|
+
.slice(-entries)
|
|
177
|
+
.map((p) => `## ${p.trim()}`)
|
|
178
|
+
.join('\n\n');
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
/* -------------------------------------------------------------------------- */
|
|
182
|
+
/* Run */
|
|
183
|
+
/* -------------------------------------------------------------------------- */
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Run one turn of a session: seat an agent, give it the business, record what
|
|
187
|
+
* it did.
|
|
188
|
+
*
|
|
189
|
+
* Refuses rather than proceeds when the session is not CONVENED. Every actor
|
|
190
|
+
* reads STATE.json before acting; a runner that ignored it would be the one
|
|
191
|
+
* participant in the session exempt from its own governance.
|
|
192
|
+
*/
|
|
193
|
+
export const runTurn = async (options: RunOptions): Promise<RunOutcome> => {
|
|
194
|
+
const spawnFn = options.spawnFn ?? spawn;
|
|
195
|
+
|
|
196
|
+
const agent: AgentSpec | null = findAgent(options.agent_id);
|
|
197
|
+
if (agent === null) {
|
|
198
|
+
return { ok: false, reason: `unknown agent: ${options.agent_id}` };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const stateRaw = await readIf(join(options.dir, 'STATE.json'));
|
|
202
|
+
const state: SessionStateFile | null = stateRaw === null ? null : parseState(stateRaw);
|
|
203
|
+
if (state === null) {
|
|
204
|
+
return { ok: false, reason: `no readable STATE.json in ${options.dir}` };
|
|
205
|
+
}
|
|
206
|
+
if (state.state !== 'CONVENED') {
|
|
207
|
+
return {
|
|
208
|
+
ok: false,
|
|
209
|
+
reason: `session is ${state.state}${
|
|
210
|
+
state.suspension === null ? '' : ` (${state.suspension.cause})`
|
|
211
|
+
} — agents act only while CONVENED`,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const charterRaw = await readIf(join(options.dir, 'CHARTER.md'));
|
|
216
|
+
if (charterRaw === null) return { ok: false, reason: 'no CHARTER.md — not a session repo' };
|
|
217
|
+
const parsed = parseCharter(charterRaw);
|
|
218
|
+
if (!parsed.ok) return { ok: false, reason: 'CHARTER.md does not parse' };
|
|
219
|
+
const charter: Charter = parsed.charter;
|
|
220
|
+
|
|
221
|
+
// Slots available for this constituency, per the Charter.
|
|
222
|
+
const slots = charter.constituencies
|
|
223
|
+
.filter((c) => c.role === options.role)
|
|
224
|
+
.reduce((total, c) => total + c.slots, 0);
|
|
225
|
+
if (slots === 0) {
|
|
226
|
+
return { ok: false, reason: `Charter seats no ${options.role} constituency` };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// A received broadcast is authoritative over anything this process would
|
|
230
|
+
// synthesize: it carries the slot count the broadcaster published, and
|
|
231
|
+
// inventing our own would let two peers disagree about how many seats remain.
|
|
232
|
+
const envelopeSource = [
|
|
233
|
+
`# [${state.session_guid}]`,
|
|
234
|
+
`## target-actor: ${options.role}`,
|
|
235
|
+
`## slots-remaining: ${slots}`,
|
|
236
|
+
`## protocol: ${charter.protocol}`,
|
|
237
|
+
'## prompt: |',
|
|
238
|
+
...options.task.split('\n').map((l) => ` ${l}`),
|
|
239
|
+
'',
|
|
240
|
+
].join('\n');
|
|
241
|
+
|
|
242
|
+
// Capability gate. The architecture is explicit that the engine "validates
|
|
243
|
+
// model compliance at Writ Drop and refuses to spawn a mismatched model
|
|
244
|
+
// regardless of operator assignment" — so a mismatch is refused here, before
|
|
245
|
+
// an agent is spawned, not noticed afterwards.
|
|
246
|
+
const seat = charter.constituencies.find((c) => c.role === options.role);
|
|
247
|
+
const profileSource = await readIf(join(options.dir, 'actors', `${options.actor}.md`));
|
|
248
|
+
if (seat !== undefined && profileSource !== null) {
|
|
249
|
+
const profile = parseProfile(profileSource, options.actor);
|
|
250
|
+
if (profile !== null) {
|
|
251
|
+
const capability = checkCapability(profile, seat);
|
|
252
|
+
if (!capability.ok) {
|
|
253
|
+
const failures = capability.issues
|
|
254
|
+
.filter((i) => i.severity === 'fail')
|
|
255
|
+
.map((i) => i.message)
|
|
256
|
+
.join('; ');
|
|
257
|
+
return { ok: false, reason: `capability mismatch — ${failures}` };
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
let envelope: Envelope;
|
|
263
|
+
if (options.envelope !== undefined) {
|
|
264
|
+
envelope = options.envelope;
|
|
265
|
+
if (envelope.target_actor !== options.role) {
|
|
266
|
+
return {
|
|
267
|
+
ok: false,
|
|
268
|
+
reason: `broadcast targets ${envelope.target_actor}, this agent stands for ${options.role}`,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
} else {
|
|
272
|
+
const envelopeResult = parseEnvelope(envelopeSource);
|
|
273
|
+
if (!envelopeResult.ok) {
|
|
274
|
+
return { ok: false, reason: 'failed to build a valid broadcast envelope' };
|
|
275
|
+
}
|
|
276
|
+
envelope = envelopeResult.envelope;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Elect into the constituency. Local scope only — the Hansard commit is the
|
|
280
|
+
// global arbiter, and this lock merely grants the right to attempt it.
|
|
281
|
+
const election: ElectionOptions = {
|
|
282
|
+
fs: nodeLockFs,
|
|
283
|
+
lockDir: options.lock_dir ?? join(options.dir, '.politik', 'locks'),
|
|
284
|
+
staleAfterMs: 60 * 60 * 1000,
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
const outcome = await standForElection(
|
|
288
|
+
envelope,
|
|
289
|
+
options.actor,
|
|
290
|
+
options.role,
|
|
291
|
+
election,
|
|
292
|
+
options.now,
|
|
293
|
+
);
|
|
294
|
+
|
|
295
|
+
if (!outcome.elected) {
|
|
296
|
+
return {
|
|
297
|
+
ok: false,
|
|
298
|
+
reason:
|
|
299
|
+
outcome.reason === 'DEFERRED'
|
|
300
|
+
? `constituency held by ${outcome.holder?.agent ?? 'another agent'}`
|
|
301
|
+
: outcome.reason,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
try {
|
|
306
|
+
const hansard = (await readIf(join(options.dir, 'HANSARD.md'))) ?? '';
|
|
307
|
+
|
|
308
|
+
const prompt = composePrompt({
|
|
309
|
+
envelope,
|
|
310
|
+
role: options.role,
|
|
311
|
+
verbs: options.verbs ?? ['READ', 'WRITE', 'ESCALATE'],
|
|
312
|
+
protocol: charter.protocol,
|
|
313
|
+
standing_orders: charter.body,
|
|
314
|
+
hansard_excerpt: recentRecord(hansard),
|
|
315
|
+
escalation_enabled: charter.session.escalation !== 'disabled',
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
const beforeHead = await head(options.dir, spawnFn);
|
|
319
|
+
const beforeDirty = await dirtyFiles(options.dir, spawnFn);
|
|
320
|
+
|
|
321
|
+
const measure = options.measure !== false && agent.json_args !== undefined;
|
|
322
|
+
const sleepFn = options.sleepFn ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));
|
|
323
|
+
const policy = {
|
|
324
|
+
auto_retry_max: charter.fault_handling.auto_retry_max,
|
|
325
|
+
auto_retry_delay_minutes: charter.fault_handling.auto_retry_delay_minutes,
|
|
326
|
+
auto_recoverable: DEFAULT_FAULT_HANDLING.auto_recoverable,
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
// PATH_A: a transient fault retries without waking anyone. Every attempt is
|
|
330
|
+
// recorded, so a session that succeeded on the third try does not read as
|
|
331
|
+
// one that succeeded cleanly.
|
|
332
|
+
let result = await spawnAgent(agent, prompt, {
|
|
333
|
+
cwd: options.dir,
|
|
334
|
+
timeout_ms: options.timeout_ms,
|
|
335
|
+
spawnFn,
|
|
336
|
+
extraArgs: measure ? agent.json_args : undefined,
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
let attempts = 1;
|
|
340
|
+
let classification: Classification | null = null;
|
|
341
|
+
const faultEntries: HansardEntry[] = [];
|
|
342
|
+
|
|
343
|
+
while (!result.ok) {
|
|
344
|
+
classification = classify(result);
|
|
345
|
+
const decision = shouldRetry(classification, attempts, policy);
|
|
346
|
+
|
|
347
|
+
faultEntries.push(
|
|
348
|
+
faultRecord({
|
|
349
|
+
at: options.now,
|
|
350
|
+
actor: options.actor,
|
|
351
|
+
role: options.role,
|
|
352
|
+
action: `spawn ${agent.id}`,
|
|
353
|
+
classification,
|
|
354
|
+
...(decision.retry ? { attempt: attempts, of: policy.auto_retry_max } : {}),
|
|
355
|
+
}),
|
|
356
|
+
);
|
|
357
|
+
|
|
358
|
+
if (!decision.retry) break;
|
|
359
|
+
|
|
360
|
+
await sleepFn(decision.delay_ms);
|
|
361
|
+
attempts += 1;
|
|
362
|
+
result = await spawnAgent(agent, prompt, {
|
|
363
|
+
cwd: options.dir,
|
|
364
|
+
timeout_ms: options.timeout_ms,
|
|
365
|
+
spawnFn,
|
|
366
|
+
extraArgs: measure ? agent.json_args : undefined,
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (result.ok && attempts > 1) {
|
|
371
|
+
faultEntries.push(
|
|
372
|
+
autoResolvedRecord(options.now, options.actor, options.role, attempts),
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Structured output carries the answer inside a JSON envelope; unwrap it so
|
|
377
|
+
// the Hansard records what the agent said, not how it was transported.
|
|
378
|
+
const usage: Usage | null = measure ? parseUsage(agent.id, result.stdout) : null;
|
|
379
|
+
const answer = (measure ? parseResultText(agent.id, result.stdout) : null) ?? result.stdout;
|
|
380
|
+
|
|
381
|
+
const touched = await filesTouched(options.dir, beforeHead, beforeDirty, spawnFn);
|
|
382
|
+
|
|
383
|
+
// Files the RECORD agent owns exclusively (POLITIK-ARCHITECTURE.md
|
|
384
|
+
// § File Sovereignty Rules). An actor writing to them is a Standing Orders
|
|
385
|
+
// violation, and it must be recorded rather than silently tolerated —
|
|
386
|
+
// a record an actor can write is not a record.
|
|
387
|
+
const OWNED_BY_RECORD = ['HANSARD.md', 'STATE.json', 'LEDGER.md'];
|
|
388
|
+
const violations = touched.filter((f) => OWNED_BY_RECORD.includes(f));
|
|
389
|
+
|
|
390
|
+
// An agent that hits a decision above its authority is told (composePrompt,
|
|
391
|
+
// Rules of the Floor) to file a Point of Order instead of proceeding. On a
|
|
392
|
+
// hosted session the point-of-order workflow catches the pushed file and
|
|
393
|
+
// suspends; a local session has no such watcher, so the runner closes the
|
|
394
|
+
// loop: a new file under escalations/ — a ruling excepted, since that is the
|
|
395
|
+
// Speaker's own reply — is an agent-filed Point of Order, and the sitting
|
|
396
|
+
// suspends pending a ruling exactly as the CLI `escalate` path does.
|
|
397
|
+
const escalationFiles = touched.filter(
|
|
398
|
+
(f) => f.startsWith('escalations/') && !f.slice('escalations/'.length).startsWith('ruling'),
|
|
399
|
+
);
|
|
400
|
+
// A protocol declaring no escalation (ADR-0006) has no mechanism to resolve a
|
|
401
|
+
// Point of Order, so an agent's escalation file is recorded but does not
|
|
402
|
+
// suspend — suspending would deadlock the sitting in a state it cannot lift.
|
|
403
|
+
const escalationDisabled = charter.session.escalation === 'disabled';
|
|
404
|
+
const agentEscalated = escalationFiles.length > 0 && !escalationDisabled;
|
|
405
|
+
const escalationIgnored = escalationFiles.length > 0 && escalationDisabled;
|
|
406
|
+
|
|
407
|
+
// Hard Containment Rule. Checked after the turn because it is detection,
|
|
408
|
+
// not prevention — a spawned process runs with the OS's permissions and
|
|
409
|
+
// nothing here can stop it. The Hansard records what happened, which is the
|
|
410
|
+
// framework's answer to most of what it cannot prevent.
|
|
411
|
+
const containment = checkContainment(options.dir, touched, `${result.stdout}\n${answer}`);
|
|
412
|
+
|
|
413
|
+
const entry: HansardEntry = {
|
|
414
|
+
type: result.ok ? 'MOTION_TABLED' : 'SESSION_FAULT',
|
|
415
|
+
at: options.now,
|
|
416
|
+
actor: options.actor,
|
|
417
|
+
role: options.role,
|
|
418
|
+
fields: {
|
|
419
|
+
Agent: agent.id,
|
|
420
|
+
Outcome: result.timed_out
|
|
421
|
+
? 'TIMED OUT'
|
|
422
|
+
: result.ok
|
|
423
|
+
? 'completed'
|
|
424
|
+
: `exit ${String(result.exit_code)}`,
|
|
425
|
+
'Elapsed ms': String(result.elapsed_ms),
|
|
426
|
+
'Files touched': touched.length > 0 ? touched.join(', ') : 'none',
|
|
427
|
+
...(violations.length > 0
|
|
428
|
+
? {
|
|
429
|
+
'Standing Orders violation': `actor wrote to ${violations.join(', ')} — owned by RECORD`,
|
|
430
|
+
}
|
|
431
|
+
: {}),
|
|
432
|
+
...(agentEscalated
|
|
433
|
+
? {
|
|
434
|
+
'Point of Order': `actor filed ${escalationFiles.join(', ')} — the sitting is suspended pending a Speaker ruling`,
|
|
435
|
+
}
|
|
436
|
+
: {}),
|
|
437
|
+
...(escalationIgnored
|
|
438
|
+
? {
|
|
439
|
+
'Point of Order': `actor filed ${escalationFiles.join(', ')} — ignored: this protocol declares no escalation`,
|
|
440
|
+
}
|
|
441
|
+
: {}),
|
|
442
|
+
},
|
|
443
|
+
body: result.ok
|
|
444
|
+
? answer.trim().slice(0, 2000)
|
|
445
|
+
: `Agent failed.\n\n${result.stderr.trim().slice(0, 1000)}`,
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
// Faults are recorded before the turn's own entry: they happened first, and
|
|
449
|
+
// a reader should see the retries that led to the outcome.
|
|
450
|
+
let record = hansard;
|
|
451
|
+
for (const fault of faultEntries) record = appendEntry(record, fault);
|
|
452
|
+
record = appendEntry(record, entry);
|
|
453
|
+
|
|
454
|
+
// A breach suspends the sitting: logged immediately, escalated to the
|
|
455
|
+
// Speaker, paused pending a ruling (POLITIK-ARCHITECTURE.md § Hard
|
|
456
|
+
// Containment Rule). The Point of Order flow already does exactly that, so
|
|
457
|
+
// the breach reuses it rather than inventing a parallel path.
|
|
458
|
+
if (!containment.contained) {
|
|
459
|
+
record = appendEntry(
|
|
460
|
+
record,
|
|
461
|
+
breachEntry(containment, options.now, options.actor, options.role),
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
await writeFile(join(options.dir, 'HANSARD.md'), record, 'utf8');
|
|
466
|
+
|
|
467
|
+
// The Clerk appends after every act. A turn that produced no ledger row
|
|
468
|
+
// would be work the session cannot account for.
|
|
469
|
+
if (charter.ledger.enabled) {
|
|
470
|
+
const ledgerPath = join(options.dir, charter.ledger.path);
|
|
471
|
+
const ledger = (await readIf(ledgerPath)) ?? '';
|
|
472
|
+
await writeFile(
|
|
473
|
+
ledgerPath,
|
|
474
|
+
appendLedgerRow(ledger, {
|
|
475
|
+
at: options.now,
|
|
476
|
+
actor: options.actor,
|
|
477
|
+
role: options.role,
|
|
478
|
+
item: touched.length > 0 ? touched.join(' ') : entry.type,
|
|
479
|
+
elapsed_ms: result.elapsed_ms,
|
|
480
|
+
usage,
|
|
481
|
+
}),
|
|
482
|
+
'utf8',
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// The slot is consumed by the Hansard commit, not by winning the lock.
|
|
487
|
+
claimSlot(envelope);
|
|
488
|
+
|
|
489
|
+
// Quorum is carried forward untouched. A turn is not a Division, and
|
|
490
|
+
// `present` counts actors eligible to vote — it was previously being
|
|
491
|
+
// overwritten with the leftover broadcast slot count, which is a different
|
|
492
|
+
// quantity entirely and made the figure meaningless.
|
|
493
|
+
// The sitting suspends on a containment breach or an agent-filed Point of
|
|
494
|
+
// Order — both pause pending a Speaker ruling, and both carry the same
|
|
495
|
+
// POINT_OF_ORDER cause. A breach names no escalation file; an agent's Point
|
|
496
|
+
// of Order does, so its path is recorded as the escalation reference.
|
|
497
|
+
const suspend = !containment.contained || agentEscalated;
|
|
498
|
+
const nextState = createState({
|
|
499
|
+
session_guid: state.session_guid,
|
|
500
|
+
protocol: state.protocol,
|
|
501
|
+
state: suspend ? 'SUSPENDED' : 'CONVENED',
|
|
502
|
+
...(suspend
|
|
503
|
+
? {
|
|
504
|
+
suspension: {
|
|
505
|
+
cause: 'POINT_OF_ORDER' as const,
|
|
506
|
+
since: options.now,
|
|
507
|
+
record_ref: 'HANSARD.md',
|
|
508
|
+
escalation_ref: agentEscalated ? (escalationFiles[0] ?? null) : null,
|
|
509
|
+
},
|
|
510
|
+
}
|
|
511
|
+
: {}),
|
|
512
|
+
quorum: state.quorum,
|
|
513
|
+
hansard_head: state.hansard_head,
|
|
514
|
+
updated_at: options.now,
|
|
515
|
+
});
|
|
516
|
+
await writeFile(join(options.dir, 'STATE.json'), serializeState(nextState), 'utf8');
|
|
517
|
+
|
|
518
|
+
if (!containment.contained) {
|
|
519
|
+
return {
|
|
520
|
+
ok: false,
|
|
521
|
+
reason: `containment breach — ${containment.breaches.map((b) => b.evidence).join(', ')}; the sitting is suspended pending a Speaker ruling`,
|
|
522
|
+
entry,
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
return result.ok
|
|
527
|
+
? { ok: true, result, entry, files_touched: touched, ...(agentEscalated ? { suspended: true } : {}) }
|
|
528
|
+
: { ok: false, reason: `agent failed: exit ${String(result.exit_code)}`, entry };
|
|
529
|
+
} finally {
|
|
530
|
+
// Always release, including on a throw — a lock held by a dead turn would
|
|
531
|
+
// strand the constituency until the stale window expires.
|
|
532
|
+
await bowOut(envelope, options.actor, options.role, election);
|
|
533
|
+
}
|
|
534
|
+
};
|