@cordfuse/politik 0.3.1 → 0.4.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/README.md +51 -0
- package/docs/adr/0010-operator-interface.md +145 -0
- package/docs/adr/0011-shared-sessions.md +129 -0
- package/package.json +1 -1
- package/src/charter.ts +29 -0
- package/src/cli.ts +679 -29
- package/src/containment.ts +5 -2
- package/src/git.ts +8 -4
- package/src/init.ts +12 -1
- package/src/operator.ts +82 -0
- package/src/pending.ts +165 -0
- package/src/remote.ts +274 -0
- package/src/templates/parliamentary.ts +95 -2
package/src/cli.ts
CHANGED
|
@@ -8,20 +8,32 @@
|
|
|
8
8
|
* Attribution: Steve Krisjanovs, Cordfuse
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import { readFileSync } from 'node:fs';
|
|
12
|
-
import { readFile, writeFile, mkdir, rename } from 'node:fs/promises';
|
|
11
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
12
|
+
import { readFile, readdir, writeFile, mkdir, rename, rm } from 'node:fs/promises';
|
|
13
13
|
import { dirname, join, relative, resolve } from 'node:path';
|
|
14
14
|
import { fileURLToPath } from 'node:url';
|
|
15
15
|
import { parseArgs } from 'node:util';
|
|
16
16
|
|
|
17
17
|
import { isRole, type Role } from './canon.ts';
|
|
18
|
-
import { charterFingerprint, parseCharter, validateCharter } from './charter.ts';
|
|
18
|
+
import { charterFingerprint, instructionsFingerprint, parseCharter, validateCharter } from './charter.ts';
|
|
19
19
|
import { dropWrit } from './init.ts';
|
|
20
20
|
import { initSessionRepo } from './git.ts';
|
|
21
21
|
import { parseState, serializeState, type SessionStateFile } from './state.ts';
|
|
22
|
-
import { scaffoldTemplates } from './templates/parliamentary.ts';
|
|
22
|
+
import { INSTRUCTION_FILES, bootstrapTemplate, pointerFiles, scaffoldTemplates } from './templates/parliamentary.ts';
|
|
23
23
|
import { generateProtocol, lintSource } from './protocol-sdk.ts';
|
|
24
24
|
import { diagnose } from './doctor.ts';
|
|
25
|
+
import {
|
|
26
|
+
isPendingId, listPending, readPending, removePending, stagePending, withDir,
|
|
27
|
+
type ConstitutionalAct,
|
|
28
|
+
} from './pending.ts';
|
|
29
|
+
import { createInterface } from 'node:readline/promises';
|
|
30
|
+
import {
|
|
31
|
+
configureClone, disableSync, discardTo, enableSync, fastForward, fetchRemote, gitx, headSha,
|
|
32
|
+
operatorHandle, operatorIdentity, pushRecord, syncConfig, syncNow,
|
|
33
|
+
} from './remote.ts';
|
|
34
|
+
import {
|
|
35
|
+
CONFIRMED_BY_SPEAKER, detectHarness, isSpeakerAtTerminal, provenanceTrailers, requestedVia,
|
|
36
|
+
} from './operator.ts';
|
|
25
37
|
import { runTurn } from './runner.ts';
|
|
26
38
|
import { GitTransport } from './transport.ts';
|
|
27
39
|
import { conflictEntry, detectRecordConflicts, openConflicts, resolveConflict } from './conflict.ts';
|
|
@@ -78,12 +90,21 @@ const USAGE = `politik — governed multi-agent sessions on git
|
|
|
78
90
|
|
|
79
91
|
Usage
|
|
80
92
|
politik version
|
|
81
|
-
politik
|
|
93
|
+
politik new <dir> # start here: folder + instructions for your AI harness
|
|
94
|
+
politik scaffold [--dir <dir>] [--protocol parliamentary] [--quorum <n>] [--parent <dir>]
|
|
95
|
+
[--speaker-confirmation required|off]
|
|
82
96
|
politik doctor
|
|
97
|
+
politik pending [--dir <dir>] [--json] # constitutional acts staged for the Speaker
|
|
98
|
+
politik confirm <id> [--dir <dir>] # the Speaker, at a terminal: execute a staged act
|
|
99
|
+
politik reject <id> [--dir <dir>] # discard a staged act
|
|
100
|
+
politik remote [<url>] [--as <handle>] [--off] # share this session through a git remote
|
|
101
|
+
politik join <url> [<dir>] --as <handle> # take a seat in a shared session from this machine
|
|
102
|
+
politik sync [--dir <dir>] # reconcile this clone with the shared record
|
|
103
|
+
politik protocol list # the shipped protocols
|
|
83
104
|
politik protocol lint <manifest.yml>
|
|
84
105
|
politik protocol new <name> [--mode <mode>] [--out <dir>]
|
|
85
106
|
politik validate <charter.md> [--protocol <name>]
|
|
86
|
-
politik init --charter <path> --speaker <handle> [--dir <dir>] [--guid <id>] [--standalone]
|
|
107
|
+
politik init --charter <path> --speaker <handle> [--dir <dir>] [--guid <id>] [--standalone] [--remote <url>]
|
|
87
108
|
politik run --agent <id> --actor <h> --role <ROLE> (--task <text> | --claim)
|
|
88
109
|
politik division call --motion <id> --actor <h> --role <ROLE> [--reviewers a,b]
|
|
89
110
|
politik division vote --motion <id> --actor <h> --role <ROLE> --vote AYE|NO|ABSTAIN
|
|
@@ -108,10 +129,10 @@ Usage
|
|
|
108
129
|
politik broadcast --target <ROLE> --slots <n> --task <text> [--dir <dir>]
|
|
109
130
|
politik motion link --motion <id> --pr <n> [--url <u>]
|
|
110
131
|
politik ledger [--dir <dir>]
|
|
111
|
-
politik status [--dir <dir>]
|
|
132
|
+
politik status [--dir <dir>] [--json]
|
|
112
133
|
politik hansard [--dir <dir>] # the record, in the protocol's vocabulary
|
|
113
134
|
politik integrity [--dir <dir>] # scan the record for bad-faith patterns
|
|
114
|
-
politik prorogue --dir <dir> --actor <handle> --role <ROLE> --trigger <TRIGGER>
|
|
135
|
+
politik prorogue [--dir <dir>] --actor <handle> --role <ROLE> --trigger <TRIGGER>
|
|
115
136
|
politik standings [--dir <dir>] [--by win-loss|survival] # score a competitive protocol
|
|
116
137
|
politik pair --format swiss|round-robin|single-elim [--dir <dir>] # pair the next round of MATCHes
|
|
117
138
|
politik match report --match <id> --winner <contestant> [--actor <referee>]
|
|
@@ -154,8 +175,23 @@ Commands
|
|
|
154
175
|
/* Output */
|
|
155
176
|
/* -------------------------------------------------------------------------- */
|
|
156
177
|
|
|
157
|
-
|
|
158
|
-
|
|
178
|
+
/**
|
|
179
|
+
* Output is buffered while a shared-session act is attempted (ADR-0011 §2): if the
|
|
180
|
+
* push is rejected the attempt is discarded and redone, and the operator must only
|
|
181
|
+
* ever see the attempt that was actually recorded.
|
|
182
|
+
*/
|
|
183
|
+
let outputBuffer: Array<readonly ['out' | 'err', string]> | null = null;
|
|
184
|
+
const out = (line = '') => {
|
|
185
|
+
if (outputBuffer !== null) outputBuffer.push(['out', line]);
|
|
186
|
+
else process.stdout.write(`${line}\n`);
|
|
187
|
+
};
|
|
188
|
+
const err = (line: string) => {
|
|
189
|
+
if (outputBuffer !== null) outputBuffer.push(['err', line]);
|
|
190
|
+
else process.stderr.write(`${line}\n`);
|
|
191
|
+
};
|
|
192
|
+
const flushOutput = (lines: ReadonlyArray<readonly ['out' | 'err', string]>): void => {
|
|
193
|
+
for (const [stream, line] of lines) (stream === 'out' ? process.stdout : process.stderr).write(`${line}\n`);
|
|
194
|
+
};
|
|
159
195
|
|
|
160
196
|
/**
|
|
161
197
|
* A supplied --role/--target must name a CANON role; an absent one falls back to
|
|
@@ -167,7 +203,8 @@ const err = (line: string) => process.stderr.write(`${line}\n`);
|
|
|
167
203
|
const badRole = (value: string | undefined): boolean => value !== undefined && !isRole(value);
|
|
168
204
|
|
|
169
205
|
/** Exit codes: 0 success, 1 refusal (invalid input), 2 usage error. */
|
|
170
|
-
|
|
206
|
+
/** PENDING (ADR-0010): the act was staged for the Speaker's confirmation, not recorded. */
|
|
207
|
+
const EXIT = { OK: 0, REFUSED: 1, USAGE: 2, PENDING: 3 } as const;
|
|
171
208
|
|
|
172
209
|
/* -------------------------------------------------------------------------- */
|
|
173
210
|
/* Helpers */
|
|
@@ -213,6 +250,7 @@ const cmdScaffold = async (argv: readonly string[]): Promise<number> => {
|
|
|
213
250
|
termination: { type: 'string' },
|
|
214
251
|
escalation: { type: 'string' },
|
|
215
252
|
parent: { type: 'string' },
|
|
253
|
+
'speaker-confirmation': { type: 'string' },
|
|
216
254
|
},
|
|
217
255
|
});
|
|
218
256
|
|
|
@@ -235,6 +273,11 @@ const cmdScaffold = async (argv: readonly string[]): Promise<number> => {
|
|
|
235
273
|
return EXIT.USAGE;
|
|
236
274
|
}
|
|
237
275
|
|
|
276
|
+
const speakerConfirmation = values['speaker-confirmation'] ?? 'required';
|
|
277
|
+
if (speakerConfirmation !== 'required' && speakerConfirmation !== 'off') {
|
|
278
|
+
err('scaffold: --speaker-confirmation must be required | off');
|
|
279
|
+
return EXIT.USAGE;
|
|
280
|
+
}
|
|
238
281
|
const quorum = values.quorum === undefined ? undefined : Number(values.quorum);
|
|
239
282
|
if (quorum !== undefined && (!Number.isInteger(quorum) || quorum < 1)) {
|
|
240
283
|
err('scaffold: --quorum must be an integer >= 1');
|
|
@@ -279,16 +322,403 @@ const cmdScaffold = async (argv: readonly string[]): Promise<number> => {
|
|
|
279
322
|
exit: values.exit ?? m.exit,
|
|
280
323
|
termination: values.termination ?? m.termination,
|
|
281
324
|
escalation: values.escalation ?? (manifest.protocol.no_escalation ? 'disabled' : 'enabled'),
|
|
325
|
+
speaker_confirmation: speakerConfirmation,
|
|
282
326
|
});
|
|
327
|
+
// Scaffold writes over same-named files (ADR-0010: it replaces the bootstrap
|
|
328
|
+
// instructions `politik new` leaves). Say so, rather than doing it silently.
|
|
329
|
+
const replaced = new Set(files.filter((f) => existsSync(join(dir, f.path))).map((f) => f.path));
|
|
283
330
|
await writeFiles(dir, files);
|
|
284
331
|
|
|
285
332
|
out(`SCAFFOLDED ${protocol}`);
|
|
286
|
-
for (const file of files) out(` ${file.path}`);
|
|
333
|
+
for (const file of files) out(` ${file.path}${replaced.has(file.path) ? ' (replaced existing file)' : ''}`);
|
|
287
334
|
out('');
|
|
288
335
|
out(`Edit the Standing Orders, then: politik init --charter ${join(dir, 'CHARTER.md')} --speaker <handle>`);
|
|
289
336
|
return EXIT.OK;
|
|
290
337
|
};
|
|
291
338
|
|
|
339
|
+
/**
|
|
340
|
+
* `politik new <dir>` — the operator's front door (ADR-0010 §1).
|
|
341
|
+
*
|
|
342
|
+
* Creates the folder and writes bootstrap instructions for whichever harness the
|
|
343
|
+
* operator opens there; the harness runs first-time setup as a conversation and
|
|
344
|
+
* calls `scaffold` and `init` itself. Deliberately does almost nothing: protocol,
|
|
345
|
+
* quorum and seats are decided in that conversation, not by flags here.
|
|
346
|
+
*/
|
|
347
|
+
const cmdNew = async (argv: readonly string[]): Promise<number> => {
|
|
348
|
+
const target = argv[0];
|
|
349
|
+
if (target === undefined || target.startsWith('-')) {
|
|
350
|
+
err('new: a folder name is required — politik new <dir>');
|
|
351
|
+
return EXIT.USAGE;
|
|
352
|
+
}
|
|
353
|
+
if (existsSync(target) && (await readdir(target)).length > 0) {
|
|
354
|
+
err(`new: ${target} already exists and is not empty. To set up a session in an existing folder, run: politik scaffold --dir ${target}`);
|
|
355
|
+
return EXIT.REFUSED;
|
|
356
|
+
}
|
|
357
|
+
const files = [{ path: 'AGENTS.md', content: bootstrapTemplate() }, ...pointerFiles()];
|
|
358
|
+
await writeFiles(target, files);
|
|
359
|
+
|
|
360
|
+
out(`NEW SESSION FOLDER ${target}`);
|
|
361
|
+
for (const file of files) out(` ${file.path}`);
|
|
362
|
+
out('');
|
|
363
|
+
out(`Next: cd ${target} and open your AI harness (claude, codex, agy, opencode…).`);
|
|
364
|
+
out('It will walk you through choosing a protocol, writing the Charter, and convening the session.');
|
|
365
|
+
return EXIT.OK;
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
/* -------------------------------------------------------------------------- */
|
|
370
|
+
/* Shared sessions across machines (ADR-0011) */
|
|
371
|
+
/* -------------------------------------------------------------------------- */
|
|
372
|
+
|
|
373
|
+
/** Nesting depth of sync: only the outermost governance command syncs. */
|
|
374
|
+
let syncDepth = 0;
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Run a governance act against a shared session: fetch and fast-forward, act,
|
|
378
|
+
* push. If the push is rejected because someone acted first, discard the local
|
|
379
|
+
* attempt, catch up, and recompute — up to three attempts — showing only the
|
|
380
|
+
* output of the attempt that was recorded. An unshared session, or a nested call,
|
|
381
|
+
* runs the act directly.
|
|
382
|
+
*/
|
|
383
|
+
const withSync = async (
|
|
384
|
+
dir: string,
|
|
385
|
+
exec: () => Promise<number>,
|
|
386
|
+
opts: { readonly retry: boolean },
|
|
387
|
+
): Promise<number> => {
|
|
388
|
+
const cfg = syncDepth > 0 ? null : await syncConfig(dir);
|
|
389
|
+
if (cfg === null) return exec();
|
|
390
|
+
syncDepth += 1;
|
|
391
|
+
try {
|
|
392
|
+
const attempts = opts.retry ? 3 : 1;
|
|
393
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
394
|
+
const fetched = await fetchRemote(dir, cfg);
|
|
395
|
+
if (!fetched.ok) {
|
|
396
|
+
err(`Refused: this is a shared session and ${cfg.remote} cannot be reached (${fetched.reason}).`);
|
|
397
|
+
err(' Acting offline would let acts land out of order. Reads still work; try again when connected.');
|
|
398
|
+
return EXIT.REFUSED;
|
|
399
|
+
}
|
|
400
|
+
const ff = await fastForward(dir, cfg);
|
|
401
|
+
if (ff === 'diverged' || ff === 'blocked') {
|
|
402
|
+
err(ff === 'diverged'
|
|
403
|
+
? 'Refused: the local and shared records have diverged. Run: politik sync'
|
|
404
|
+
: 'Refused: cannot catch up with the shared record — uncommitted changes conflict with it.');
|
|
405
|
+
return EXIT.REFUSED;
|
|
406
|
+
}
|
|
407
|
+
if (ff === 'ahead') {
|
|
408
|
+
const caughtUp = await pushRecord(dir, cfg);
|
|
409
|
+
if (!caughtUp.ok) { err(`Refused: earlier local acts are not shared yet and could not be pushed (${caughtUp.reason}). Run: politik sync`); return EXIT.REFUSED; }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const start = await headSha(dir);
|
|
413
|
+
outputBuffer = [];
|
|
414
|
+
let code: number;
|
|
415
|
+
try { code = await exec(); } catch (error) { flushOutput(outputBuffer); outputBuffer = null; throw error; }
|
|
416
|
+
const lines = outputBuffer;
|
|
417
|
+
outputBuffer = null;
|
|
418
|
+
|
|
419
|
+
const end = await headSha(dir);
|
|
420
|
+
if (end === start) { flushOutput(lines); return code; }
|
|
421
|
+
|
|
422
|
+
const pushed = await pushRecord(dir, cfg);
|
|
423
|
+
if (pushed.ok) { flushOutput(lines); return code; }
|
|
424
|
+
|
|
425
|
+
if (pushed.rejected && opts.retry && attempt < attempts && start !== null) {
|
|
426
|
+
if (await discardTo(dir, start)) continue;
|
|
427
|
+
flushOutput(lines);
|
|
428
|
+
err('Recorded locally, but someone else acted first and the attempt could not be redone safely. Run: politik sync');
|
|
429
|
+
return code;
|
|
430
|
+
}
|
|
431
|
+
flushOutput(lines);
|
|
432
|
+
err(pushed.rejected
|
|
433
|
+
? 'Recorded locally, but not shared yet — someone else acted first. Run: politik sync'
|
|
434
|
+
: `Recorded locally, but could not reach ${cfg.remote} to share it (${pushed.reason}). Run: politik sync`);
|
|
435
|
+
return code;
|
|
436
|
+
}
|
|
437
|
+
err(`Refused: the shared session is busy — ${attempts} attempts were overtaken by other acts. Try again.`);
|
|
438
|
+
return EXIT.REFUSED;
|
|
439
|
+
} finally {
|
|
440
|
+
syncDepth -= 1;
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
/** Before a read: catch up with the shared record if possible, silently if not. */
|
|
445
|
+
const refreshForRead = async (dir: string): Promise<void> => {
|
|
446
|
+
const cfg = await syncConfig(dir);
|
|
447
|
+
if (cfg === null) return;
|
|
448
|
+
if ((await fetchRemote(dir, cfg)).ok) await fastForward(dir, cfg);
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
/** `politik remote [<url>] [--as <handle>] [--off]` — make a session shared, or show how it is. */
|
|
452
|
+
const cmdRemote = async (argv: readonly string[]): Promise<number> => {
|
|
453
|
+
const { values, positionals } = parseArgs({
|
|
454
|
+
args: [...argv], allowPositionals: true,
|
|
455
|
+
options: { dir: { type: 'string' }, as: { type: 'string' }, off: { type: 'boolean' }, name: { type: 'string' } },
|
|
456
|
+
});
|
|
457
|
+
const dir = values.dir ?? '.';
|
|
458
|
+
if (values.off === true) {
|
|
459
|
+
await disableSync(dir);
|
|
460
|
+
out('Sync off — this clone no longer pushes or pulls the record. The remote is unchanged.');
|
|
461
|
+
return EXIT.OK;
|
|
462
|
+
}
|
|
463
|
+
const url = positionals[0];
|
|
464
|
+
if (url === undefined) {
|
|
465
|
+
const cfg = await syncConfig(dir);
|
|
466
|
+
if (cfg === null) { out('Not shared. Share it with: politik remote <url>'); return EXIT.OK; }
|
|
467
|
+
const where = await gitx(dir, ['remote', 'get-url', cfg.remote]);
|
|
468
|
+
out(`shared via ${cfg.remote} — ${where.out || '(no url)'}`);
|
|
469
|
+
out(`branch ${cfg.branch}`);
|
|
470
|
+
out(`you are ${cfg.handle ?? '(unknown — set with: politik remote --as <handle>)'}`);
|
|
471
|
+
return EXIT.OK;
|
|
472
|
+
}
|
|
473
|
+
if ((await readIfPresent(join(dir, 'STATE.json'))) === null) {
|
|
474
|
+
err(`remote: ${dir} is not a convened session — run politik init first`);
|
|
475
|
+
return EXIT.USAGE;
|
|
476
|
+
}
|
|
477
|
+
const handle = values.as ?? (await writDropSpeaker(dir));
|
|
478
|
+
const result = await enableSync(dir, url, { remote: values.name ?? 'origin', handle });
|
|
479
|
+
if (!result.ok) { err(`remote: ${result.message}`); return EXIT.REFUSED; }
|
|
480
|
+
out(`SHARED — ${result.message}`);
|
|
481
|
+
if (handle !== null) out(` you are ${handle}`);
|
|
482
|
+
out(` Others join with: politik join ${url} <dir> --as <their handle>`);
|
|
483
|
+
return EXIT.OK;
|
|
484
|
+
};
|
|
485
|
+
|
|
486
|
+
/** The Speaker named on the WRIT_DROP entry. */
|
|
487
|
+
const writDropSpeaker = async (dir: string): Promise<string | null> => {
|
|
488
|
+
const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
|
|
489
|
+
for (const entry of parseEntries(hansard)) {
|
|
490
|
+
if (entry.type === RECORD_TYPES.WRIT_DROP) return entry.actor;
|
|
491
|
+
}
|
|
492
|
+
return null;
|
|
493
|
+
};
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* `politik join <url> [dir] --as <handle>` — take a seat in a shared session from
|
|
497
|
+
* this machine: clone it, check it is a session with intact seals, turn on sync.
|
|
498
|
+
*/
|
|
499
|
+
const cmdJoin = async (argv: readonly string[]): Promise<number> => {
|
|
500
|
+
const { values, positionals } = parseArgs({
|
|
501
|
+
args: [...argv], allowPositionals: true, options: { as: { type: 'string' } },
|
|
502
|
+
});
|
|
503
|
+
const url = positionals[0];
|
|
504
|
+
if (url === undefined) { err('join: a remote url is required — politik join <url> [dir] --as <handle>'); return EXIT.USAGE; }
|
|
505
|
+
const dir = positionals[1] ?? (url.replace(/\/+$/, '').split(/[/:]/).pop() ?? 'session').replace(/\.git$/, '');
|
|
506
|
+
if (existsSync(dir) && (await readdir(dir)).length > 0) {
|
|
507
|
+
err(`join: ${dir} already exists and is not empty`);
|
|
508
|
+
return EXIT.REFUSED;
|
|
509
|
+
}
|
|
510
|
+
const clone = await gitx('.', ['clone', '--quiet', url, dir]);
|
|
511
|
+
if (clone.code !== 0) { err(`join: could not clone ${url}: ${clone.err.split('\n')[0] ?? ''}`); return EXIT.REFUSED; }
|
|
512
|
+
await gitx(dir, ['fetch', '--quiet', 'origin', '+refs/politik/pending/*:refs/politik/pending/*']);
|
|
513
|
+
// A bare remote whose HEAD names a branch that was never pushed clones with
|
|
514
|
+
// nothing checked out. If the remote has exactly one branch, that is the record.
|
|
515
|
+
if ((await gitx(dir, ['rev-parse', '--verify', '--quiet', 'HEAD'])).code !== 0) {
|
|
516
|
+
const branches = (await gitx(dir, ['for-each-ref', '--format=%(refname:lstrip=3)', 'refs/remotes/origin/'])).out
|
|
517
|
+
.split('\n').filter((b) => b !== '' && b !== 'HEAD');
|
|
518
|
+
if (branches.length === 1 && branches[0] !== undefined) {
|
|
519
|
+
await gitx(dir, ['checkout', '--quiet', '-b', branches[0], '--track', `origin/${branches[0]}`]);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
if ((await readIfPresent(join(dir, 'STATE.json'))) === null) {
|
|
524
|
+
err(`join: ${url} was cloned to ${dir}, but its root is not a convened session.`);
|
|
525
|
+
err(' If it is a tree of sessions, cd into the node you want and run: politik remote --as <handle> --dir .');
|
|
526
|
+
return EXIT.REFUSED;
|
|
527
|
+
}
|
|
528
|
+
const tampered = await instructionsViolation(dir);
|
|
529
|
+
if (tampered !== null) { err(`join: ${tampered}`); return EXIT.REFUSED; }
|
|
530
|
+
|
|
531
|
+
const cfg = await configureClone(dir, values.as ?? null);
|
|
532
|
+
if (cfg === null) { err('join: the clone is not on a branch'); return EXIT.REFUSED; }
|
|
533
|
+
out(`JOINED ${dir} — shared via ${cfg.remote}, branch ${cfg.branch}`);
|
|
534
|
+
out(` you are ${cfg.handle ?? '(unknown — set with: politik remote --as <handle>)'}`);
|
|
535
|
+
out('');
|
|
536
|
+
out(`Next: cd ${dir} and open your AI harness (claude, codex, agy, opencode…).`);
|
|
537
|
+
return EXIT.OK;
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
/** `politik sync` — reconcile this clone's record with the shared one. */
|
|
541
|
+
const cmdSync = async (argv: readonly string[]): Promise<number> => {
|
|
542
|
+
const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' } } });
|
|
543
|
+
const dir = values.dir ?? '.';
|
|
544
|
+
const cfg = await syncConfig(dir);
|
|
545
|
+
if (cfg === null) { out('Not shared — nothing to sync. Share it with: politik remote <url>'); return EXIT.OK; }
|
|
546
|
+
const result = await syncNow(dir, cfg);
|
|
547
|
+
if (!result.ok) { err(`sync: ${result.message}`); return EXIT.REFUSED; }
|
|
548
|
+
out(`SYNCED — ${result.message}`);
|
|
549
|
+
return EXIT.OK;
|
|
550
|
+
};
|
|
551
|
+
|
|
552
|
+
/* -------------------------------------------------------------------------- */
|
|
553
|
+
/* The Speaker's confirmation (ADR-0010 §2) */
|
|
554
|
+
/* -------------------------------------------------------------------------- */
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* Set only by `politik confirm`, in-process, after the Speaker has typed the act's
|
|
558
|
+
* id at a terminal. There is deliberately no flag or environment variable that
|
|
559
|
+
* sets it: a harness cannot pass its way past the gate.
|
|
560
|
+
*/
|
|
561
|
+
let speakerConfirmed = false;
|
|
562
|
+
|
|
563
|
+
/** Read one line from the terminal. Only ever called when stdin is a TTY. */
|
|
564
|
+
const askSpeaker = async (prompt: string): Promise<string> => {
|
|
565
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
566
|
+
try { return (await rl.question(prompt)).trim(); } finally { rl.close(); }
|
|
567
|
+
};
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Gate a constitutional act. Returns null when it may proceed, or an exit code
|
|
571
|
+
* when it must not run now.
|
|
572
|
+
*
|
|
573
|
+
* Under `speaker_confirmation: required`: a person at a terminal (no harness
|
|
574
|
+
* detected) is asked inline; anything else — an AI harness, a script, a pipe — has
|
|
575
|
+
* the act staged for `politik confirm` and nothing reaches the record. A Charter
|
|
576
|
+
* without the setting (every pre-ADR-0010 session) is never gated.
|
|
577
|
+
*/
|
|
578
|
+
const awaitSpeaker = async (
|
|
579
|
+
act: ConstitutionalAct,
|
|
580
|
+
argv: readonly string[],
|
|
581
|
+
dir: string,
|
|
582
|
+
summary: string,
|
|
583
|
+
): Promise<number | null> => {
|
|
584
|
+
if (speakerConfirmed) return null;
|
|
585
|
+
const charterRaw = await readIfPresent(join(dir, 'CHARTER.md'));
|
|
586
|
+
const parsed = charterRaw === null ? null : parseCharter(charterRaw);
|
|
587
|
+
if (parsed === null || !parsed.ok || parsed.charter.session.speaker_confirmation !== 'required') return null;
|
|
588
|
+
|
|
589
|
+
const interactive = process.stdin.isTTY === true;
|
|
590
|
+
if (isSpeakerAtTerminal(process.env, interactive)) {
|
|
591
|
+
out(`Constitutional act — this will be permanently recorded in the Hansard:`);
|
|
592
|
+
out(` ${summary}`);
|
|
593
|
+
const typed = await askSpeaker(`Type "${act}" to confirm: `);
|
|
594
|
+
if (typed === act) return null;
|
|
595
|
+
err('Not confirmed — nothing was recorded.');
|
|
596
|
+
return EXIT.REFUSED;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const sessionDir = resolve(dir);
|
|
600
|
+
let pending;
|
|
601
|
+
try {
|
|
602
|
+
pending = await stagePending(sessionDir, {
|
|
603
|
+
act,
|
|
604
|
+
argv: withDir(argv, sessionDir),
|
|
605
|
+
summary,
|
|
606
|
+
requested_via: requestedVia(process.env, interactive),
|
|
607
|
+
requested_at: nowStamp(),
|
|
608
|
+
});
|
|
609
|
+
} catch (error) {
|
|
610
|
+
err(`Refused: ${error instanceof Error ? error.message : String(error)}. Nothing was staged or recorded.`);
|
|
611
|
+
return EXIT.REFUSED;
|
|
612
|
+
}
|
|
613
|
+
out(`STAGED — ${summary}`);
|
|
614
|
+
out(` pending act: ${pending.id}`);
|
|
615
|
+
out(' Nothing is recorded yet. This is the Speaker\'s decision: they confirm it in');
|
|
616
|
+
out(' their own terminal (not through an AI harness):');
|
|
617
|
+
out(` politik confirm ${pending.id}${dir === '.' ? '' : ` --dir ${dir}`}`);
|
|
618
|
+
out(` To discard it instead: politik reject ${pending.id}${dir === '.' ? '' : ` --dir ${dir}`}`);
|
|
619
|
+
return EXIT.PENDING;
|
|
620
|
+
};
|
|
621
|
+
|
|
622
|
+
/** `politik pending [--dir] [--json]` — staged acts awaiting the Speaker. */
|
|
623
|
+
const cmdPending = async (argv: readonly string[]): Promise<number> => {
|
|
624
|
+
const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' }, json: { type: 'boolean' } } });
|
|
625
|
+
await refreshForRead(values.dir ?? '.');
|
|
626
|
+
const acts = await listPending(resolve(values.dir ?? '.'));
|
|
627
|
+
if (values.json === true) { out(JSON.stringify(acts, null, 2)); return EXIT.OK; }
|
|
628
|
+
if (acts.length === 0) { out('No pending acts.'); return EXIT.OK; }
|
|
629
|
+
out(`PENDING ACTS (${acts.length}) — confirm each with: politik confirm <id>`);
|
|
630
|
+
for (const a of acts) {
|
|
631
|
+
out(` ${a.id} ${a.summary}`);
|
|
632
|
+
out(` requested via ${a.requested_via} at ${a.requested_at}`);
|
|
633
|
+
}
|
|
634
|
+
return EXIT.OK;
|
|
635
|
+
};
|
|
636
|
+
|
|
637
|
+
/** The `--actor` a staged act names. */
|
|
638
|
+
const actorOf = (argv: readonly string[]): string | null => {
|
|
639
|
+
const i = argv.indexOf('--actor');
|
|
640
|
+
return i >= 0 ? argv[i + 1] ?? null : null;
|
|
641
|
+
};
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* `politik confirm <id>` — the Speaker executes a staged act.
|
|
645
|
+
*
|
|
646
|
+
* Refuses without a terminal or under a detected harness, shows exactly what will
|
|
647
|
+
* run, and requires the act's id to be typed back. Only then is the act replayed
|
|
648
|
+
* and committed, with provenance naming who requested it and that the Speaker
|
|
649
|
+
* confirmed it.
|
|
650
|
+
*/
|
|
651
|
+
const cmdConfirm = async (argv: readonly string[]): Promise<number> => {
|
|
652
|
+
const { values, positionals } = parseArgs({
|
|
653
|
+
args: [...argv], options: { dir: { type: 'string' } }, allowPositionals: true,
|
|
654
|
+
});
|
|
655
|
+
const id = positionals[0];
|
|
656
|
+
if (id === undefined || !isPendingId(id)) { err('confirm: a pending act id is required — see: politik pending'); return EXIT.USAGE; }
|
|
657
|
+
|
|
658
|
+
const harness = detectHarness(process.env);
|
|
659
|
+
if (!isSpeakerAtTerminal(process.env, process.stdin.isTTY === true)) {
|
|
660
|
+
err(`confirm: refused — this must be run by the Speaker at a terminal, not by ${harness ?? 'a script or pipe'}.`);
|
|
661
|
+
err(` Open your own terminal and run: politik confirm ${id}${values.dir === undefined ? '' : ` --dir ${values.dir}`}`);
|
|
662
|
+
return EXIT.REFUSED;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
const sessionDir = resolve(values.dir ?? '.');
|
|
666
|
+
await refreshForRead(sessionDir);
|
|
667
|
+
const pending = await readPending(sessionDir, id);
|
|
668
|
+
if (pending === null) { err(`confirm: no pending act ${id} in ${sessionDir}`); return EXIT.USAGE; }
|
|
669
|
+
|
|
670
|
+
// ADR-0011 §4: in a shared session only the seat the act names may confirm it.
|
|
671
|
+
if ((await syncConfig(sessionDir)) !== null) {
|
|
672
|
+
const actor = actorOf(pending.argv);
|
|
673
|
+
const me = await operatorHandle(sessionDir);
|
|
674
|
+
if (actor !== null && me !== actor) {
|
|
675
|
+
err(`confirm: refused — ${id} is ${actor}'s act to confirm, and this clone is operated by ${me ?? 'an unknown seat'}.`);
|
|
676
|
+
err(' Set who you are with: politik remote --as <handle>');
|
|
677
|
+
return EXIT.REFUSED;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
out(`Constitutional act — this will be permanently recorded in the Hansard:`);
|
|
682
|
+
out(` ${pending.summary}`);
|
|
683
|
+
out(` command: politik ${pending.act} ${withDir(pending.argv, sessionDir).join(' ')}`);
|
|
684
|
+
out(` requested via: ${pending.requested_via} at ${pending.requested_at}`);
|
|
685
|
+
const typed = await askSpeaker(`Type ${id} to confirm: `);
|
|
686
|
+
if (typed !== id) { err('Not confirmed — nothing was recorded. The act is still pending.'); return EXIT.REFUSED; }
|
|
687
|
+
|
|
688
|
+
speakerConfirmed = true;
|
|
689
|
+
actProvenance = { via: pending.requested_via, confirmedBy: CONFIRMED_BY_SPEAKER };
|
|
690
|
+
try {
|
|
691
|
+
// Replay against this machine's copy of the session: a pending act shared from
|
|
692
|
+
// another machine names that machine's path (ADR-0011 §4).
|
|
693
|
+
const argv = withDir(pending.argv, sessionDir);
|
|
694
|
+
const code = await withSync(sessionDir, () => run([pending.act, ...argv]), { retry: true });
|
|
695
|
+
if (code === EXIT.OK) {
|
|
696
|
+
await removePending(sessionDir, id);
|
|
697
|
+
out(`CONFIRMED — ${id}`);
|
|
698
|
+
} else {
|
|
699
|
+
err(`confirm: the act did not complete — ${id} is still pending (discard it with: politik reject ${id})`);
|
|
700
|
+
}
|
|
701
|
+
return code;
|
|
702
|
+
} finally {
|
|
703
|
+
speakerConfirmed = false;
|
|
704
|
+
actProvenance = null;
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
|
|
708
|
+
/** `politik reject <id>` — discard a staged act. Nothing was recorded, so nothing is. */
|
|
709
|
+
const cmdReject = async (argv: readonly string[]): Promise<number> => {
|
|
710
|
+
const { values, positionals } = parseArgs({
|
|
711
|
+
args: [...argv], options: { dir: { type: 'string' } }, allowPositionals: true,
|
|
712
|
+
});
|
|
713
|
+
const id = positionals[0];
|
|
714
|
+
if (id === undefined || !isPendingId(id)) { err('reject: a pending act id is required — see: politik pending'); return EXIT.USAGE; }
|
|
715
|
+
const sessionDir = resolve(values.dir ?? '.');
|
|
716
|
+
if ((await readPending(sessionDir, id)) === null) { err(`reject: no pending act ${id} in ${sessionDir}`); return EXIT.USAGE; }
|
|
717
|
+
await removePending(sessionDir, id);
|
|
718
|
+
out(`REJECTED — ${id} discarded; nothing was recorded`);
|
|
719
|
+
return EXIT.OK;
|
|
720
|
+
};
|
|
721
|
+
|
|
292
722
|
/** Probe the host and report whether a session can run here. */
|
|
293
723
|
const cmdDoctor = async (): Promise<number> => {
|
|
294
724
|
const diagnosis = await diagnose();
|
|
@@ -308,6 +738,20 @@ const cmdDoctor = async (): Promise<number> => {
|
|
|
308
738
|
const cmdProtocol = async (argv: readonly string[]): Promise<number> => {
|
|
309
739
|
const [verb, ...rest] = argv;
|
|
310
740
|
|
|
741
|
+
if (verb === 'list') {
|
|
742
|
+
// The shipped protocols, so a harness guiding first-time setup can offer real
|
|
743
|
+
// choices instead of guessing names (ADR-0010).
|
|
744
|
+
const dir = join(dirname(fileURLToPath(import.meta.url)), '..', 'protocols');
|
|
745
|
+
const names = (await readdir(dir)).filter((f) => f.endsWith('.yml')).sort();
|
|
746
|
+
for (const file of names) {
|
|
747
|
+
const src = (await readIfPresent(join(dir, file))) ?? '';
|
|
748
|
+
const blurb = (src.split('\n').find((l) => l.startsWith('#')) ?? '')
|
|
749
|
+
.replace(/^#\s*/, '').split(/(?<=\.)\s/)[0] ?? '';
|
|
750
|
+
out(` ${file.replace(/\.yml$/, '').padEnd(28)} ${blurb}`);
|
|
751
|
+
}
|
|
752
|
+
return EXIT.OK;
|
|
753
|
+
}
|
|
754
|
+
|
|
311
755
|
if (verb === 'lint') {
|
|
312
756
|
const path = rest[0];
|
|
313
757
|
if (path === undefined) {
|
|
@@ -427,6 +871,7 @@ const cmdInit = async (argv: readonly string[]): Promise<number> => {
|
|
|
427
871
|
guid: { type: 'string' },
|
|
428
872
|
protocol: { type: 'string' },
|
|
429
873
|
standalone: { type: 'boolean' },
|
|
874
|
+
remote: { type: 'string' },
|
|
430
875
|
},
|
|
431
876
|
});
|
|
432
877
|
|
|
@@ -441,16 +886,17 @@ const cmdInit = async (argv: readonly string[]): Promise<number> => {
|
|
|
441
886
|
return EXIT.USAGE;
|
|
442
887
|
}
|
|
443
888
|
|
|
889
|
+
// `--dir` is the standard flag; `--out` stays an accepted alias here.
|
|
890
|
+
const dir = values.dir ?? values.out ?? '.';
|
|
891
|
+
|
|
444
892
|
const result = dropWrit({
|
|
445
893
|
charter_source: source,
|
|
446
894
|
session_guid: values.guid ?? crypto.randomUUID(),
|
|
447
895
|
now: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
|
|
448
896
|
speaker: values.speaker,
|
|
449
897
|
protocol: values.protocol === undefined ? undefined : { name: values.protocol },
|
|
898
|
+
instruction_files: await readInstructionFiles(dir),
|
|
450
899
|
});
|
|
451
|
-
|
|
452
|
-
// `--dir` is the standard flag; `--out` stays an accepted alias here.
|
|
453
|
-
const dir = values.dir ?? values.out ?? '.';
|
|
454
900
|
await writeFiles(dir, result.files);
|
|
455
901
|
|
|
456
902
|
if (!result.ok) {
|
|
@@ -477,6 +923,14 @@ const cmdInit = async (argv: readonly string[]): Promise<number> => {
|
|
|
477
923
|
out(` state ${result.state.state}`);
|
|
478
924
|
out(` files ${result.files.length} written to ${dir}`);
|
|
479
925
|
out(` git ${repo.reason}${repo.sha ? ` (${repo.sha.slice(0, 7)})` : ''}`);
|
|
926
|
+
|
|
927
|
+
// ADR-0011: share the session from the Writ Drop, with the Speaker as this
|
|
928
|
+
// clone's seat. The session is open either way; a failed publish is reported.
|
|
929
|
+
if (values.remote !== undefined) {
|
|
930
|
+
const shared = await enableSync(dir, values.remote, { handle: values.speaker });
|
|
931
|
+
if (shared.ok) out(` shared ${shared.message}`);
|
|
932
|
+
else { err(` shared NOT shared — ${shared.message}. Retry with: politik remote ${values.remote}`); return EXIT.REFUSED; }
|
|
933
|
+
}
|
|
480
934
|
return EXIT.OK;
|
|
481
935
|
};
|
|
482
936
|
|
|
@@ -563,6 +1017,78 @@ const immutableCharterViolation = async (
|
|
|
563
1017
|
].join(' ');
|
|
564
1018
|
};
|
|
565
1019
|
|
|
1020
|
+
/** The instruction files present in a session directory (ADR-0010 §4). */
|
|
1021
|
+
const readInstructionFiles = async (
|
|
1022
|
+
dir: string,
|
|
1023
|
+
): Promise<ReadonlyArray<{ readonly path: string; readonly content: string }>> => {
|
|
1024
|
+
const files: Array<{ path: string; content: string }> = [];
|
|
1025
|
+
for (const path of INSTRUCTION_FILES) {
|
|
1026
|
+
const content = await readIfPresent(join(dir, path));
|
|
1027
|
+
if (content !== null) files.push({ path, content });
|
|
1028
|
+
}
|
|
1029
|
+
return files;
|
|
1030
|
+
};
|
|
1031
|
+
|
|
1032
|
+
/**
|
|
1033
|
+
* Refuse governance when the session's instruction files have changed since Writ
|
|
1034
|
+
* Drop (ADR-0010 §4).
|
|
1035
|
+
*
|
|
1036
|
+
* These are the files the Speaker's own harness loads on entering the session. An
|
|
1037
|
+
* agent that rewrites — or plants — one has tried to reprogram the governor's
|
|
1038
|
+
* tool, so this applies under every protocol, not only immutable-charter ones.
|
|
1039
|
+
* Null when the act may proceed: an intact set, or a session sealed before
|
|
1040
|
+
* ADR-0010 (no fingerprint to compare against).
|
|
1041
|
+
*/
|
|
1042
|
+
const instructionsViolation = async (dir: string): Promise<string | null> => {
|
|
1043
|
+
const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
|
|
1044
|
+
let recorded: string | null = null;
|
|
1045
|
+
for (const entry of parseEntries(hansard)) {
|
|
1046
|
+
if (entry.type === RECORD_TYPES.WRIT_DROP) { recorded = entry.fields['Instructions SHA256'] ?? null; break; }
|
|
1047
|
+
}
|
|
1048
|
+
if (recorded === null) return null;
|
|
1049
|
+
const files = await readInstructionFiles(dir);
|
|
1050
|
+
const now = instructionsFingerprint(files);
|
|
1051
|
+
if (now === recorded) return null;
|
|
1052
|
+
return [
|
|
1053
|
+
`Refused: this session's instruction files (${INSTRUCTION_FILES.join(', ')}) have changed since`,
|
|
1054
|
+
`Writ Drop (${recorded.slice(0, 12)} → ${now.slice(0, 12)}). These are the instructions the Speaker's`,
|
|
1055
|
+
'own AI harness loads here; an agent may have tried to rewrite them. Inspect with `git diff`',
|
|
1056
|
+
'and restore them from the Writ Drop commit before continuing.',
|
|
1057
|
+
].join(' ');
|
|
1058
|
+
};
|
|
1059
|
+
|
|
1060
|
+
/**
|
|
1061
|
+
* Commands that only read, or that set a session up before Writ Drop. Every other
|
|
1062
|
+
* command is governance and refuses to run while the instruction files are
|
|
1063
|
+
* tampered (ADR-0010 §4); these stay available so the Speaker can see what
|
|
1064
|
+
* happened and repair it.
|
|
1065
|
+
*/
|
|
1066
|
+
const UNGUARDED_COMMANDS: ReadonlySet<string | undefined> = new Set([
|
|
1067
|
+
undefined, '-h', '--help', 'help', 'version', '--version',
|
|
1068
|
+
'new', 'scaffold', 'init', 'doctor', 'protocol', 'validate',
|
|
1069
|
+
'status', 'hansard', 'ledger', 'integrity', 'pending', 'reject',
|
|
1070
|
+
'registry', 'cascade', 'standings',
|
|
1071
|
+
'remote', 'join', 'sync',
|
|
1072
|
+
]);
|
|
1073
|
+
|
|
1074
|
+
/** Read-only commands that catch up with a shared record first (ADR-0011 §2). */
|
|
1075
|
+
const REFRESH_BEFORE: ReadonlySet<string | undefined> = new Set([
|
|
1076
|
+
'status', 'hansard', 'ledger', 'integrity', 'standings',
|
|
1077
|
+
]);
|
|
1078
|
+
|
|
1079
|
+
/** Governance commands not retried on a rejected push: re-running them has effects. */
|
|
1080
|
+
const NOT_RETRIED: ReadonlySet<string | undefined> = new Set(['run']);
|
|
1081
|
+
|
|
1082
|
+
/** The `--dir` a command line targets, defaulting to the working directory. */
|
|
1083
|
+
const dirArg = (argv: readonly string[]): string => {
|
|
1084
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
1085
|
+
const a = argv[i] ?? '';
|
|
1086
|
+
if (a === '--dir') return argv[i + 1] ?? '.';
|
|
1087
|
+
if (a.startsWith('--dir=')) return a.slice('--dir='.length);
|
|
1088
|
+
}
|
|
1089
|
+
return '.';
|
|
1090
|
+
};
|
|
1091
|
+
|
|
566
1092
|
/**
|
|
567
1093
|
* Guard a governance write: prints the refusal and returns false if an
|
|
568
1094
|
* immutable Charter has been tampered with, true when the act may proceed.
|
|
@@ -635,18 +1161,62 @@ const logAct = async (dir: string, actor: string, role: Role, item: string): Pro
|
|
|
635
1161
|
* interrupt can never land between telling the operator "success" and the record
|
|
636
1162
|
* actually existing: every command writes, commits, then reports.
|
|
637
1163
|
*/
|
|
638
|
-
|
|
1164
|
+
/**
|
|
1165
|
+
* Provenance for the act in flight (ADR-0010 §3). Normally derived from this
|
|
1166
|
+
* process; `politik confirm` overrides it so a staged act records who originally
|
|
1167
|
+
* requested it and that the Speaker confirmed it.
|
|
1168
|
+
*/
|
|
1169
|
+
let actProvenance: { readonly via: string; readonly confirmedBy: string | null } | null = null;
|
|
1170
|
+
|
|
1171
|
+
const currentProvenance = (): { readonly via: string; readonly confirmedBy: string | null } =>
|
|
1172
|
+
actProvenance ?? { via: requestedVia(process.env, process.stdin.isTTY === true), confirmedBy: null };
|
|
1173
|
+
|
|
1174
|
+
const commitAct = async (
|
|
639
1175
|
dir: string,
|
|
640
1176
|
message: string,
|
|
641
1177
|
extra: readonly string[] = [],
|
|
642
|
-
): Promise<CommitResult> =>
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
1178
|
+
): Promise<CommitResult> => {
|
|
1179
|
+
const { via, confirmedBy } = currentProvenance();
|
|
1180
|
+
const operator = await operatorIdentity(dir);
|
|
1181
|
+
// ADR-0011 §5: a confirmed act is signed with the confirming person's key when
|
|
1182
|
+
// the Charter requires it, so confirmation cannot be forged without that key.
|
|
1183
|
+
const sign = confirmedBy !== null && (await charterRequiresSignedConfirmations(dir));
|
|
1184
|
+
const paths = ['HANSARD.md', 'STATE.json', 'LEDGER.md', '.politik/LEDGER.md', ...extra];
|
|
1185
|
+
const result = await commitRecord(dir, `${message}\n\n${provenanceTrailers(via, confirmedBy, operator)}`, paths, undefined, { sign });
|
|
1186
|
+
if (sign && !result.committed && result.reason === 'signing failed') {
|
|
1187
|
+
// The act must not survive unsigned (ADR-0011 §5): put every record file back
|
|
1188
|
+
// as it was, so the working tree matches the last signed state, then refuse.
|
|
1189
|
+
for (const path of paths) {
|
|
1190
|
+
if ((await gitx(dir, ['ls-files', '--error-unmatch', '--', path])).code === 0) {
|
|
1191
|
+
await gitx(dir, ['checkout', 'HEAD', '--', path]);
|
|
1192
|
+
} else if (existsSync(join(dir, path))) {
|
|
1193
|
+
await rm(join(dir, path), { force: true });
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
throw new Error('the confirmation could not be signed with your git signing key — nothing was recorded');
|
|
1197
|
+
}
|
|
1198
|
+
return result;
|
|
1199
|
+
};
|
|
1200
|
+
|
|
1201
|
+
/**
|
|
1202
|
+
* Commits in this session that record a Speaker confirmation but whose signature
|
|
1203
|
+
* does not verify (`%G?` other than G or U). Verification uses the clone's git
|
|
1204
|
+
* configuration — for SSH signatures, `gpg.ssh.allowedSignersFile`.
|
|
1205
|
+
*/
|
|
1206
|
+
const unverifiedConfirmations = async (dir: string): Promise<readonly string[]> => {
|
|
1207
|
+
const log = await gitx(dir, ['log', '--format=%H%x09%G?%x09%(trailers:key=Politik-Confirmed-By,valueonly,separator=%x2C)', '--', '.']);
|
|
1208
|
+
if (log.code !== 0 || log.out === '') return [];
|
|
1209
|
+
return log.out.split('\n')
|
|
1210
|
+
.map((line) => line.split('\t'))
|
|
1211
|
+
.filter(([, status, confirmed]) => (confirmed ?? '').trim() !== '' && status !== 'G' && status !== 'U')
|
|
1212
|
+
.map(([sha]) => sha ?? '');
|
|
1213
|
+
};
|
|
1214
|
+
|
|
1215
|
+
const charterRequiresSignedConfirmations = async (dir: string): Promise<boolean> => {
|
|
1216
|
+
const raw = await readIfPresent(join(dir, 'CHARTER.md'));
|
|
1217
|
+
const parsed = raw === null ? null : parseCharter(raw);
|
|
1218
|
+
return parsed !== null && parsed.ok && parsed.charter.session.signed_confirmations === 'required';
|
|
1219
|
+
};
|
|
650
1220
|
|
|
651
1221
|
/** Print a commit's outcome. Call only AFTER the commit, as part of the report. */
|
|
652
1222
|
const reportCommit = (result: CommitResult): void => {
|
|
@@ -887,6 +1457,9 @@ const cmdAssent = async (argv: readonly string[]): Promise<number> => {
|
|
|
887
1457
|
if (values.motion === undefined || values.actor === undefined) {
|
|
888
1458
|
err('assent: --motion and --actor are required'); return EXIT.USAGE;
|
|
889
1459
|
}
|
|
1460
|
+
const gated = await awaitSpeaker('assent', argv, dir,
|
|
1461
|
+
`Assent to motion "${values.motion}" as ${values.actor} — enact it`);
|
|
1462
|
+
if (gated !== null) return gated;
|
|
890
1463
|
|
|
891
1464
|
try {
|
|
892
1465
|
const outcome = tallyDivision(hansard, values.motion, charter.session.quorum);
|
|
@@ -1367,6 +1940,9 @@ const cmdRule = async (argv: readonly string[]): Promise<number> => {
|
|
|
1367
1940
|
return EXIT.USAGE;
|
|
1368
1941
|
}
|
|
1369
1942
|
if (badRole(values.role)) { err(`rule: "${values.role}" is not a CANON role`); return EXIT.USAGE; }
|
|
1943
|
+
const gated = await awaitSpeaker('rule', argv, dir,
|
|
1944
|
+
`Rule ${(values.outcome ?? 'UPHELD').toUpperCase()} on point of order #${values.seq ?? '1'} as ${values.actor}: "${values.body}"`);
|
|
1945
|
+
if (gated !== null) return gated;
|
|
1370
1946
|
|
|
1371
1947
|
const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
|
|
1372
1948
|
|
|
@@ -1753,8 +2329,22 @@ const cmdIntegrity = async (argv: readonly string[]): Promise<number> => {
|
|
|
1753
2329
|
const { state, hansard } = await loadSession(dir);
|
|
1754
2330
|
if (state === null) { err(`integrity: ${dir} is not a session repo`); return EXIT.USAGE; }
|
|
1755
2331
|
|
|
2332
|
+
// ADR-0010 §4: a tampered instruction set is the most serious finding there is
|
|
2333
|
+
// — it targets the Speaker's own harness — so it leads, and fails the check.
|
|
2334
|
+
const tampered = await instructionsViolation(dir);
|
|
2335
|
+
if (tampered !== null) out(` [HIGH] instructions-tampered — ${tampered}`);
|
|
2336
|
+
|
|
2337
|
+
// ADR-0011 §5: under signed_confirmations, every confirmed act must carry a
|
|
2338
|
+
// signature that verifies. Report each one that does not.
|
|
2339
|
+
const unsigned = (await charterRequiresSignedConfirmations(dir)) ? await unverifiedConfirmations(dir) : [];
|
|
2340
|
+
for (const sha of unsigned) {
|
|
2341
|
+
out(` [HIGH] confirmation-unsigned — ${sha.slice(0, 8)} records a Speaker confirmation without a verifying signature`);
|
|
2342
|
+
}
|
|
2343
|
+
const failedSeal = tampered !== null || unsigned.length > 0;
|
|
2344
|
+
|
|
1756
2345
|
const findings = reviewIntegrity(hansard);
|
|
1757
2346
|
if (findings.length === 0) {
|
|
2347
|
+
if (failedSeal) return EXIT.REFUSED;
|
|
1758
2348
|
out('no bad-faith patterns detected — the record is clean');
|
|
1759
2349
|
return EXIT.OK;
|
|
1760
2350
|
}
|
|
@@ -1765,7 +2355,7 @@ const cmdIntegrity = async (argv: readonly string[]): Promise<number> => {
|
|
|
1765
2355
|
out('');
|
|
1766
2356
|
out(`${vices.length} vice finding(s), ${virtues.length} virtue(s). Surfaced to the Speaker; no action taken — the Speaker rules.`);
|
|
1767
2357
|
// A high-severity vice exits non-zero so a watching Speaker/CI is alerted.
|
|
1768
|
-
return vices.some((f) => f.severity === 'high') ? EXIT.REFUSED : EXIT.OK;
|
|
2358
|
+
return failedSeal || vices.some((f) => f.severity === 'high') ? EXIT.REFUSED : EXIT.OK;
|
|
1769
2359
|
};
|
|
1770
2360
|
|
|
1771
2361
|
/** `politik hansard` — the record, rendered in the protocol's vocabulary. */
|
|
@@ -1789,7 +2379,7 @@ const cmdHansard = async (argv: readonly string[]): Promise<number> => {
|
|
|
1789
2379
|
};
|
|
1790
2380
|
|
|
1791
2381
|
const cmdStatus = async (argv: readonly string[]): Promise<number> => {
|
|
1792
|
-
const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' } } });
|
|
2382
|
+
const { values } = parseArgs({ args: [...argv], options: { dir: { type: 'string' }, json: { type: 'boolean' } } });
|
|
1793
2383
|
const dir = values.dir ?? '.';
|
|
1794
2384
|
|
|
1795
2385
|
const raw = await readIfPresent(join(dir, 'STATE.json'));
|
|
@@ -1804,6 +2394,31 @@ const cmdStatus = async (argv: readonly string[]): Promise<number> => {
|
|
|
1804
2394
|
return EXIT.REFUSED;
|
|
1805
2395
|
}
|
|
1806
2396
|
|
|
2397
|
+
const pending = await listPending(resolve(dir));
|
|
2398
|
+
const hansardRaw = await readIfPresent(join(dir, 'HANSARD.md'));
|
|
2399
|
+
const entries = hansardRaw === null ? [] : parseEntries(hansardRaw);
|
|
2400
|
+
|
|
2401
|
+
// ADR-0010: a stable machine-readable view, so a harness answering the Speaker
|
|
2402
|
+
// reads fields rather than scraping text.
|
|
2403
|
+
if (values.json === true) {
|
|
2404
|
+
const last = entries.at(-1);
|
|
2405
|
+
out(JSON.stringify({
|
|
2406
|
+
session: state.session_guid,
|
|
2407
|
+
protocol: state.protocol,
|
|
2408
|
+
state: state.state,
|
|
2409
|
+
suspension: state.suspension,
|
|
2410
|
+
quorum: state.quorum,
|
|
2411
|
+
updated_at: state.updated_at,
|
|
2412
|
+
updated_by: state.updated_by,
|
|
2413
|
+
record: {
|
|
2414
|
+
entries: entries.length,
|
|
2415
|
+
last: last === undefined ? null : { type: last.type, actor: last.actor, at: last.at },
|
|
2416
|
+
},
|
|
2417
|
+
pending: pending.map((p) => ({ id: p.id, act: p.act, summary: p.summary })),
|
|
2418
|
+
}, null, 2));
|
|
2419
|
+
return EXIT.OK;
|
|
2420
|
+
}
|
|
2421
|
+
|
|
1807
2422
|
out(`session ${state.session_guid}`);
|
|
1808
2423
|
out(`protocol ${state.protocol}`);
|
|
1809
2424
|
out(`state ${state.state}`);
|
|
@@ -1813,13 +2428,14 @@ const cmdStatus = async (argv: readonly string[]): Promise<number> => {
|
|
|
1813
2428
|
out(`quorum ${state.quorum.present} of ${state.quorum.required}`);
|
|
1814
2429
|
out(`updated ${state.updated_at} by ${state.updated_by}`);
|
|
1815
2430
|
|
|
1816
|
-
|
|
1817
|
-
if (hansard !== null) {
|
|
1818
|
-
const entries = parseEntries(hansard);
|
|
2431
|
+
if (hansardRaw !== null) {
|
|
1819
2432
|
out(`record ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'}`);
|
|
1820
2433
|
const last = entries.at(-1);
|
|
1821
2434
|
if (last !== undefined) out(`last ${last.type} by ${last.actor} at ${last.at}`);
|
|
1822
2435
|
}
|
|
2436
|
+
if (pending.length > 0) {
|
|
2437
|
+
out(`pending ${pending.length} act${pending.length === 1 ? '' : 's'} awaiting the Speaker — politik pending`);
|
|
2438
|
+
}
|
|
1823
2439
|
return EXIT.OK;
|
|
1824
2440
|
};
|
|
1825
2441
|
|
|
@@ -1851,6 +2467,9 @@ const cmdProrogue = async (argv: readonly string[]): Promise<number> => {
|
|
|
1851
2467
|
err(`prorogue: no readable STATE.json in ${dir}`);
|
|
1852
2468
|
return EXIT.USAGE;
|
|
1853
2469
|
}
|
|
2470
|
+
const gated = await awaitSpeaker('prorogue', argv, dir,
|
|
2471
|
+
`Prorogue the session as ${values.actor} (trigger: ${values.trigger ?? 'TRIGGER_SPEAKER'}) — seal the Hansard`);
|
|
2472
|
+
if (gated !== null) return gated;
|
|
1854
2473
|
|
|
1855
2474
|
const hansard = (await readIfPresent(join(dir, 'HANSARD.md'))) ?? '';
|
|
1856
2475
|
const trigger = (values.trigger ?? 'TRIGGER_SPEAKER') as Trigger;
|
|
@@ -2190,6 +2809,23 @@ const cmdCascade = async (argv: readonly string[]): Promise<number> => {
|
|
|
2190
2809
|
export const run = async (argv: readonly string[]): Promise<number> => {
|
|
2191
2810
|
const [command, ...rest] = argv;
|
|
2192
2811
|
|
|
2812
|
+
if (!UNGUARDED_COMMANDS.has(command)) {
|
|
2813
|
+
const violation = await instructionsViolation(dirArg(rest));
|
|
2814
|
+
if (violation !== null) { err(violation); return EXIT.REFUSED; }
|
|
2815
|
+
}
|
|
2816
|
+
|
|
2817
|
+
// ADR-0011: governance on a shared session syncs around the act. `confirm`
|
|
2818
|
+
// syncs around its own replay (after the Speaker has typed the id), so it is
|
|
2819
|
+
// not wrapped here.
|
|
2820
|
+
if (REFRESH_BEFORE.has(command)) await refreshForRead(dirArg(rest));
|
|
2821
|
+
if (!UNGUARDED_COMMANDS.has(command) && command !== 'confirm') {
|
|
2822
|
+
return withSync(dirArg(rest), () => dispatch(command, rest), { retry: !NOT_RETRIED.has(command) });
|
|
2823
|
+
}
|
|
2824
|
+
return dispatch(command, rest);
|
|
2825
|
+
};
|
|
2826
|
+
|
|
2827
|
+
const dispatch = async (command: string | undefined, rest: readonly string[]): Promise<number> => {
|
|
2828
|
+
|
|
2193
2829
|
switch (command) {
|
|
2194
2830
|
case undefined:
|
|
2195
2831
|
case '-h':
|
|
@@ -2201,6 +2837,20 @@ export const run = async (argv: readonly string[]): Promise<number> => {
|
|
|
2201
2837
|
case '--version':
|
|
2202
2838
|
out(VERSION);
|
|
2203
2839
|
return EXIT.OK;
|
|
2840
|
+
case 'new':
|
|
2841
|
+
return cmdNew(rest);
|
|
2842
|
+
case 'pending':
|
|
2843
|
+
return cmdPending(rest);
|
|
2844
|
+
case 'confirm':
|
|
2845
|
+
return cmdConfirm(rest);
|
|
2846
|
+
case 'reject':
|
|
2847
|
+
return cmdReject(rest);
|
|
2848
|
+
case 'remote':
|
|
2849
|
+
return cmdRemote(rest);
|
|
2850
|
+
case 'join':
|
|
2851
|
+
return cmdJoin(rest);
|
|
2852
|
+
case 'sync':
|
|
2853
|
+
return cmdSync(rest);
|
|
2204
2854
|
case 'scaffold':
|
|
2205
2855
|
return cmdScaffold(rest);
|
|
2206
2856
|
case 'doctor':
|