@cordfuse/politik 0.3.1 → 0.5.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 +4 -2
- package/PROTOCOLS.md +39 -3
- package/README.md +67 -5
- package/RESEARCH.md +2 -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/protocols/scrum.yml +87 -0
- package/src/agents.ts +33 -1
- package/src/charter.ts +29 -0
- package/src/cli.ts +685 -29
- package/src/containment.ts +5 -2
- package/src/git.ts +12 -5
- 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/runner.ts +76 -13
- package/src/templates/parliamentary.ts +96 -2
package/src/containment.ts
CHANGED
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
* Attribution: Steve Krisjanovs, Cordfuse
|
|
31
31
|
*/
|
|
32
32
|
|
|
33
|
-
import { isAbsolute, relative, resolve } from 'node:path';
|
|
33
|
+
import { isAbsolute, relative, resolve, sep } from 'node:path';
|
|
34
34
|
|
|
35
35
|
import type { Role } from './canon.ts';
|
|
36
36
|
import type { HansardEntry } from './hansard.ts';
|
|
@@ -63,7 +63,10 @@ export interface ContainmentCheck {
|
|
|
63
63
|
export const isInside = (root: string, path: string): boolean => {
|
|
64
64
|
const target = isAbsolute(path) ? path : resolve(root, path);
|
|
65
65
|
const rel = relative(resolve(root), target);
|
|
66
|
-
|
|
66
|
+
// Only a parent-directory segment escapes. An ordinary filename such as
|
|
67
|
+
// "..cache" starts with two dots but is still inside the session.
|
|
68
|
+
const escapes = rel === '..' || rel.startsWith(`..${sep}`);
|
|
69
|
+
return !escapes && !isAbsolute(rel);
|
|
67
70
|
};
|
|
68
71
|
|
|
69
72
|
/**
|
package/src/git.ts
CHANGED
|
@@ -60,6 +60,7 @@ export const commitRecord = async (
|
|
|
60
60
|
message: string,
|
|
61
61
|
paths: readonly string[] = ['HANSARD.md', 'STATE.json'],
|
|
62
62
|
spawnFn: typeof spawn = spawn,
|
|
63
|
+
opts: { readonly sign?: boolean } = {},
|
|
63
64
|
): Promise<CommitResult> => {
|
|
64
65
|
const isRepo = await git(dir, ['rev-parse', '--is-inside-work-tree'], spawnFn);
|
|
65
66
|
if (isRepo.code !== 0) {
|
|
@@ -79,7 +80,10 @@ export const commitRecord = async (
|
|
|
79
80
|
|
|
80
81
|
const add = await git(dir, ['add', '--', ...present], spawnFn);
|
|
81
82
|
if (add.code !== 0) {
|
|
82
|
-
|
|
83
|
+
// Not "nothing to stage": an empty change is caught below. A failing
|
|
84
|
+
// `git add` means git could not write the index (a read-only .git in a
|
|
85
|
+
// sandboxed harness, a held index.lock) and the act is not on the record.
|
|
86
|
+
return { committed: false, sha: null, reason: 'git add failed' };
|
|
83
87
|
}
|
|
84
88
|
|
|
85
89
|
const staged = await git(dir, ['diff', '--cached', '--name-only'], spawnFn);
|
|
@@ -87,9 +91,12 @@ export const commitRecord = async (
|
|
|
87
91
|
return { committed: false, sha: null, reason: 'no changes to record' };
|
|
88
92
|
}
|
|
89
93
|
|
|
90
|
-
const commit = await git(dir, ['commit', '-m', message], spawnFn);
|
|
94
|
+
const commit = await git(dir, ['commit', ...(opts.sign === true ? ['-S'] : []), '-m', message], spawnFn);
|
|
91
95
|
if (commit.code !== 0) {
|
|
92
|
-
|
|
96
|
+
// A required signature that cannot be made must not degrade to an unsigned
|
|
97
|
+
// record (ADR-0011 §5): unstage, so nothing half-done is left behind.
|
|
98
|
+
if (opts.sign === true) await git(dir, ['reset', '--quiet', '--', ...present], spawnFn);
|
|
99
|
+
return { committed: false, sha: null, reason: opts.sign === true ? 'signing failed' : 'commit failed' };
|
|
93
100
|
}
|
|
94
101
|
|
|
95
102
|
const sha = await git(dir, ['rev-parse', 'HEAD'], spawnFn);
|
|
@@ -129,7 +136,7 @@ export const initSessionRepo = async (
|
|
|
129
136
|
// Speaker without rewriting the parent repo's config. Exclude `*.tmp` — an
|
|
130
137
|
// atomic write interrupted mid-flight can orphan one, and it must never enter
|
|
131
138
|
// the record.
|
|
132
|
-
await git(dir, ['add', '.', ':(exclude)*.tmp'], spawnFn);
|
|
139
|
+
await git(dir, ['add', '.', ':(exclude)*.tmp', ':(exclude).politik/pending'], spawnFn);
|
|
133
140
|
const commit = await git(
|
|
134
141
|
dir,
|
|
135
142
|
['-c', `user.name=${speaker}`, '-c', `user.email=${speaker}@politik.local`,
|
|
@@ -151,7 +158,7 @@ export const initSessionRepo = async (
|
|
|
151
158
|
}
|
|
152
159
|
await git(dir, ['config', 'user.name', speaker], spawnFn);
|
|
153
160
|
await git(dir, ['config', 'user.email', `${speaker}@politik.local`], spawnFn);
|
|
154
|
-
await git(dir, ['add', '-A', '.', ':(exclude)*.tmp'], spawnFn);
|
|
161
|
+
await git(dir, ['add', '-A', '.', ':(exclude)*.tmp', ':(exclude).politik/pending'], spawnFn);
|
|
155
162
|
const commit = await git(dir, ['commit', '-m', `writ drop: session ${guid}`], spawnFn);
|
|
156
163
|
if (commit.code !== 0) return { committed: false, sha: null, reason: 'repo initialized, nothing to commit' };
|
|
157
164
|
const sha = await git(dir, ['rev-parse', 'HEAD'], spawnFn);
|
package/src/init.ts
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
validateCharter,
|
|
19
19
|
parseCharter,
|
|
20
20
|
charterFingerprint,
|
|
21
|
+
instructionsFingerprint,
|
|
21
22
|
type Charter,
|
|
22
23
|
type CharterIssue,
|
|
23
24
|
type ProtocolContext,
|
|
@@ -42,6 +43,11 @@ export interface WritDropInput {
|
|
|
42
43
|
readonly speaker: string;
|
|
43
44
|
/** Resolved protocol, when available. Enables ADR-0002 rules 2 and 5. */
|
|
44
45
|
readonly protocol?: ProtocolContext;
|
|
46
|
+
/**
|
|
47
|
+
* The session's instruction files present at Writ Drop (ADR-0010 §4). Sealed
|
|
48
|
+
* onto the WRIT_DROP entry so a later rewrite is detected.
|
|
49
|
+
*/
|
|
50
|
+
readonly instruction_files?: ReadonlyArray<{ readonly path: string; readonly content: string }>;
|
|
45
51
|
}
|
|
46
52
|
|
|
47
53
|
export type WritDropResult =
|
|
@@ -95,7 +101,12 @@ const hansard = (input: WritDropInput, guid: string): string =>
|
|
|
95
101
|
at: input.now,
|
|
96
102
|
actor: input.speaker,
|
|
97
103
|
role: 'AUTHORITY',
|
|
98
|
-
fields: {
|
|
104
|
+
fields: {
|
|
105
|
+
'Charter SHA256': charterFingerprint(input.charter_source),
|
|
106
|
+
...(input.instruction_files === undefined || input.instruction_files.length === 0
|
|
107
|
+
? {}
|
|
108
|
+
: { 'Instructions SHA256': instructionsFingerprint(input.instruction_files) }),
|
|
109
|
+
},
|
|
99
110
|
body: `Writ dropped. Session ${guid} convened under the attached Charter.`,
|
|
100
111
|
});
|
|
101
112
|
|
package/src/operator.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The operator interface (ADR-0010): who is driving the CLI, and what the record
|
|
3
|
+
* should say about it.
|
|
4
|
+
*
|
|
5
|
+
* Politik does not choose a harness — the Speaker brings their own (Claude Code,
|
|
6
|
+
* Codex, agy, opencode, …). These helpers detect which one is running a command,
|
|
7
|
+
* so a constitutional act can be staged for the Speaker's confirmation and every
|
|
8
|
+
* commit can say how it was requested.
|
|
9
|
+
*
|
|
10
|
+
* Detection is best-effort by design. The backstop is the terminal: a command
|
|
11
|
+
* with no terminal on stdin is treated as automated whatever the environment
|
|
12
|
+
* says. ADR-0010's threat model is explicit that this stops a cooperative harness
|
|
13
|
+
* from acting on a mistake or an injected instruction — not a hostile agent with
|
|
14
|
+
* the human's own shell privileges.
|
|
15
|
+
*
|
|
16
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Environment variables a harness sets for the commands it runs, mapped to a
|
|
21
|
+
* short name. `AI_AGENT` is checked first and preferred: where a harness sets
|
|
22
|
+
* it, it names the harness and its version (e.g. `claude-code_2-1-283_agent`).
|
|
23
|
+
*/
|
|
24
|
+
export const HARNESS_MARKERS: ReadonlyArray<readonly [variable: string, harness: string]> = [
|
|
25
|
+
['CLAUDECODE', 'claude-code'],
|
|
26
|
+
['CODEX_SANDBOX', 'codex'],
|
|
27
|
+
['CODEX_SANDBOX_NETWORK_DISABLED', 'codex'],
|
|
28
|
+
['CODEX_THREAD_ID', 'codex'],
|
|
29
|
+
['ANTIGRAVITY_CONVERSATION_ID', 'agy'],
|
|
30
|
+
['OPENCODE', 'opencode'],
|
|
31
|
+
['OPENCODE_PID', 'opencode'],
|
|
32
|
+
['GEMINI_CLI', 'gemini-cli'],
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
36
|
+
|
|
37
|
+
/** The harness running this process, or null if none is detectable. */
|
|
38
|
+
export const detectHarness = (env: Env): string | null => {
|
|
39
|
+
const named = env['AI_AGENT']?.trim();
|
|
40
|
+
if (named !== undefined && named !== '') return named;
|
|
41
|
+
for (const [variable, harness] of HARNESS_MARKERS) {
|
|
42
|
+
const value = env[variable];
|
|
43
|
+
if (value !== undefined && value !== '') return harness;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* How a command was requested, for the provenance trailer: the harness if one is
|
|
50
|
+
* detected, otherwise `terminal` when a human could be typing, otherwise `script`.
|
|
51
|
+
*/
|
|
52
|
+
export const requestedVia = (env: Env, interactive: boolean): string =>
|
|
53
|
+
detectHarness(env) ?? (interactive ? 'terminal' : 'script');
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Whether a person is plausibly typing at this process: a terminal on stdin and
|
|
57
|
+
* no harness in the environment. Anything else is automated.
|
|
58
|
+
*/
|
|
59
|
+
export const isSpeakerAtTerminal = (env: Env, interactive: boolean): boolean =>
|
|
60
|
+
interactive && detectHarness(env) === null;
|
|
61
|
+
|
|
62
|
+
/** The trailer value recorded when a staged act was confirmed by the Speaker. */
|
|
63
|
+
export const CONFIRMED_BY_SPEAKER = 'speaker-at-terminal';
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Git trailers appended to every governance commit.
|
|
67
|
+
*
|
|
68
|
+
* `via` says who asked; `confirmedBy` is present only for an act that was staged
|
|
69
|
+
* and then confirmed. Trailers keep the commit subject — the line every existing
|
|
70
|
+
* tool and test reads — exactly as it was.
|
|
71
|
+
*/
|
|
72
|
+
export const provenanceTrailers = (
|
|
73
|
+
via: string,
|
|
74
|
+
confirmedBy: string | null = null,
|
|
75
|
+
operator: string | null = null,
|
|
76
|
+
): string =>
|
|
77
|
+
[
|
|
78
|
+
`Politik-Requested-Via: ${via}`,
|
|
79
|
+
...(confirmedBy === null ? [] : [`Politik-Confirmed-By: ${confirmedBy}`]),
|
|
80
|
+
// ADR-0011 §5: the person operating this clone, so a shared record says who acted.
|
|
81
|
+
...(operator === null ? [] : [`Politik-Operator: ${operator}`]),
|
|
82
|
+
].join('\n');
|
package/src/pending.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pending acts — the Speaker's confirmation (ADR-0010 §2).
|
|
3
|
+
*
|
|
4
|
+
* Under `speaker_confirmation: required`, a constitutional act (assent, rule,
|
|
5
|
+
* prorogue) requested by an AI harness or a script is not executed. It is staged
|
|
6
|
+
* here, and only `politik confirm <id>`, run by the Speaker at a terminal,
|
|
7
|
+
* executes it. Nothing staged ever reaches the record: these files live under
|
|
8
|
+
* `.politik/pending/`, which no governance commit stages, and are deleted once
|
|
9
|
+
* confirmed or rejected.
|
|
10
|
+
*
|
|
11
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
12
|
+
*/
|
|
13
|
+
import { randomBytes } from 'node:crypto';
|
|
14
|
+
import { existsSync } from 'node:fs';
|
|
15
|
+
import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { deletePendingRef, readPendingRefs, syncConfig, writePendingRef } from './remote.ts';
|
|
18
|
+
|
|
19
|
+
/** The acts that exercise the Speaker's constitutional authority. */
|
|
20
|
+
export const CONSTITUTIONAL_ACTS = ['assent', 'rule', 'prorogue'] as const;
|
|
21
|
+
export type ConstitutionalAct = (typeof CONSTITUTIONAL_ACTS)[number];
|
|
22
|
+
|
|
23
|
+
export const isConstitutionalAct = (name: string): name is ConstitutionalAct =>
|
|
24
|
+
(CONSTITUTIONAL_ACTS as readonly string[]).includes(name);
|
|
25
|
+
|
|
26
|
+
export interface PendingAct {
|
|
27
|
+
/** Short id the Speaker types to confirm, e.g. `assent-3f9a2c`. */
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly act: ConstitutionalAct;
|
|
30
|
+
/** The exact arguments, replayed verbatim by `politik confirm`. */
|
|
31
|
+
readonly argv: readonly string[];
|
|
32
|
+
/** One plain-language line describing the effect. */
|
|
33
|
+
readonly summary: string;
|
|
34
|
+
/** Who asked: a harness name, or `script`. Recorded as the provenance trailer. */
|
|
35
|
+
readonly requested_via: string;
|
|
36
|
+
readonly requested_at: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Where a session's staged acts live. Never committed. */
|
|
40
|
+
export const pendingDir = (sessionDir: string): string => join(sessionDir, '.politik', 'pending');
|
|
41
|
+
|
|
42
|
+
/** The session's GUID, which namespaces its shared pending refs (ADR-0011 §4). */
|
|
43
|
+
const sessionGuid = async (sessionDir: string): Promise<string | null> => {
|
|
44
|
+
try {
|
|
45
|
+
const raw = JSON.parse(await readFile(join(sessionDir, 'STATE.json'), 'utf8')) as { session_guid?: unknown };
|
|
46
|
+
return typeof raw.session_guid === 'string' && /^[A-Za-z0-9._-]+$/.test(raw.session_guid) ? raw.session_guid : null;
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const ID_PATTERN = /^[a-z]+-[0-9a-f]{6}$/;
|
|
53
|
+
|
|
54
|
+
/** True for a well-formed pending id — guards against path traversal on confirm/reject. */
|
|
55
|
+
export const isPendingId = (id: string): boolean => ID_PATTERN.test(id);
|
|
56
|
+
|
|
57
|
+
const newId = (act: ConstitutionalAct): string => `${act}-${randomBytes(3).toString('hex')}`;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Stage an act. In a shared session (ADR-0011) it is pushed as a pending ref so
|
|
61
|
+
* the Speaker sees it from any machine; throws if it cannot be shared, so an act
|
|
62
|
+
* is never staged where the Speaker cannot reach it. Otherwise it is written
|
|
63
|
+
* atomically to `.politik/pending/`.
|
|
64
|
+
*/
|
|
65
|
+
export const stagePending = async (
|
|
66
|
+
sessionDir: string,
|
|
67
|
+
input: Omit<PendingAct, 'id'>,
|
|
68
|
+
): Promise<PendingAct> => {
|
|
69
|
+
const cfg = await syncConfig(sessionDir);
|
|
70
|
+
if (cfg !== null) {
|
|
71
|
+
const guid = await sessionGuid(sessionDir);
|
|
72
|
+
if (guid === null) throw new Error('cannot share a pending act: STATE.json has no session GUID');
|
|
73
|
+
const pending: PendingAct = { id: newId(input.act), ...input };
|
|
74
|
+
const shared = await writePendingRef(sessionDir, cfg, guid, pending.id, `${JSON.stringify(pending, null, 2)}\n`);
|
|
75
|
+
if (!shared.ok) throw new Error(`could not share the pending act with ${cfg.remote}: ${shared.reason}`);
|
|
76
|
+
return pending;
|
|
77
|
+
}
|
|
78
|
+
const dir = pendingDir(sessionDir);
|
|
79
|
+
await mkdir(dir, { recursive: true });
|
|
80
|
+
// Ignore the folder's own contents, including this file, so a staged act never
|
|
81
|
+
// shows as untracked work or gets swept into a commit by a broad `git add`.
|
|
82
|
+
const ignore = join(dir, '.gitignore');
|
|
83
|
+
if (!existsSync(ignore)) await writeFile(ignore, '*\n', 'utf8');
|
|
84
|
+
const pending: PendingAct = { id: newId(input.act), ...input };
|
|
85
|
+
const path = join(dir, `${pending.id}.json`);
|
|
86
|
+
await writeFile(`${path}.tmp`, `${JSON.stringify(pending, null, 2)}\n`, 'utf8');
|
|
87
|
+
await rename(`${path}.tmp`, path);
|
|
88
|
+
return pending;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const parsePending = (raw: string): PendingAct | null => {
|
|
92
|
+
try {
|
|
93
|
+
const v = JSON.parse(raw) as Partial<PendingAct>;
|
|
94
|
+
if (typeof v.id !== 'string' || !isPendingId(v.id)) return null;
|
|
95
|
+
if (typeof v.act !== 'string' || !isConstitutionalAct(v.act)) return null;
|
|
96
|
+
if (!Array.isArray(v.argv) || !v.argv.every((a) => typeof a === 'string')) return null;
|
|
97
|
+
return {
|
|
98
|
+
id: v.id,
|
|
99
|
+
act: v.act,
|
|
100
|
+
argv: v.argv,
|
|
101
|
+
summary: typeof v.summary === 'string' ? v.summary : '',
|
|
102
|
+
requested_via: typeof v.requested_via === 'string' ? v.requested_via : 'unknown',
|
|
103
|
+
requested_at: typeof v.requested_at === 'string' ? v.requested_at : '',
|
|
104
|
+
};
|
|
105
|
+
} catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** Every well-formed staged act, oldest first. Shared sessions read the pending refs. */
|
|
111
|
+
export const listPending = async (sessionDir: string): Promise<readonly PendingAct[]> => {
|
|
112
|
+
if ((await syncConfig(sessionDir)) !== null) {
|
|
113
|
+
const guid = await sessionGuid(sessionDir);
|
|
114
|
+
if (guid === null) return [];
|
|
115
|
+
return (await readPendingRefs(sessionDir, guid))
|
|
116
|
+
.map(parsePending)
|
|
117
|
+
.filter((a): a is PendingAct => a !== null)
|
|
118
|
+
.sort((a, b) => a.requested_at.localeCompare(b.requested_at));
|
|
119
|
+
}
|
|
120
|
+
const dir = pendingDir(sessionDir);
|
|
121
|
+
if (!existsSync(dir)) return [];
|
|
122
|
+
const acts: PendingAct[] = [];
|
|
123
|
+
for (const file of (await readdir(dir)).filter((f) => f.endsWith('.json')).sort()) {
|
|
124
|
+
const act = parsePending(await readFile(join(dir, file), 'utf8'));
|
|
125
|
+
if (act !== null) acts.push(act);
|
|
126
|
+
}
|
|
127
|
+
return acts.sort((a, b) => a.requested_at.localeCompare(b.requested_at));
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
export const readPending = async (sessionDir: string, id: string): Promise<PendingAct | null> => {
|
|
131
|
+
if (!isPendingId(id)) return null;
|
|
132
|
+
if ((await syncConfig(sessionDir)) !== null) {
|
|
133
|
+
return (await listPending(sessionDir)).find((a) => a.id === id) ?? null;
|
|
134
|
+
}
|
|
135
|
+
const path = join(pendingDir(sessionDir), `${id}.json`);
|
|
136
|
+
if (!existsSync(path)) return null;
|
|
137
|
+
return parsePending(await readFile(path, 'utf8'));
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export const removePending = async (sessionDir: string, id: string): Promise<void> => {
|
|
141
|
+
if (!isPendingId(id)) return;
|
|
142
|
+
const cfg = await syncConfig(sessionDir);
|
|
143
|
+
if (cfg !== null) {
|
|
144
|
+
const guid = await sessionGuid(sessionDir);
|
|
145
|
+
if (guid !== null) await deletePendingRef(sessionDir, cfg, guid, id);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
await rm(join(pendingDir(sessionDir), `${id}.json`), { force: true });
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The argv with any `--dir` value replaced, so a staged act replays against the
|
|
153
|
+
* session it was staged in even when `confirm` runs from another working
|
|
154
|
+
* directory.
|
|
155
|
+
*/
|
|
156
|
+
export const withDir = (argv: readonly string[], dir: string): readonly string[] => {
|
|
157
|
+
const out: string[] = [];
|
|
158
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
159
|
+
const a = argv[i] ?? '';
|
|
160
|
+
if (a === '--dir') { i += 1; continue; }
|
|
161
|
+
if (a.startsWith('--dir=')) continue;
|
|
162
|
+
out.push(a);
|
|
163
|
+
}
|
|
164
|
+
return ['--dir', dir, ...out];
|
|
165
|
+
};
|
package/src/remote.ts
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared sessions across machines (ADR-0011): the git plumbing.
|
|
3
|
+
*
|
|
4
|
+
* A session becomes shared by configuring a git remote and turning on sync. The
|
|
5
|
+
* configuration is per-clone git config — it describes this machine, not the
|
|
6
|
+
* proceeding — so nothing here touches the session's files:
|
|
7
|
+
*
|
|
8
|
+
* politik.sync true when this clone syncs with a remote
|
|
9
|
+
* politik.remote the remote's name (default: origin)
|
|
10
|
+
* politik.branch the branch the record lives on
|
|
11
|
+
* politik.handle the seat handle of the person operating this clone
|
|
12
|
+
*
|
|
13
|
+
* Attribution: Steve Krisjanovs, Cordfuse
|
|
14
|
+
*/
|
|
15
|
+
import { spawn } from 'node:child_process';
|
|
16
|
+
|
|
17
|
+
export interface GitResult { readonly code: number; readonly out: string; readonly err: string }
|
|
18
|
+
|
|
19
|
+
/** Run git, capturing stdout and stderr, optionally feeding stdin. */
|
|
20
|
+
export const gitx = (cwd: string, args: readonly string[], input?: string): Promise<GitResult> =>
|
|
21
|
+
new Promise((resolve) => {
|
|
22
|
+
// stdin is only a pipe when there is input to feed; otherwise git gets none,
|
|
23
|
+
// so a git that exits early can never fault us with EPIPE.
|
|
24
|
+
const child = spawn('git', [...args], {
|
|
25
|
+
cwd, shell: false, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
|
|
26
|
+
});
|
|
27
|
+
let out = '';
|
|
28
|
+
let err = '';
|
|
29
|
+
child.stdout?.on('data', (c: Buffer) => { out += c.toString(); });
|
|
30
|
+
child.stderr?.on('data', (c: Buffer) => { err += c.toString(); });
|
|
31
|
+
child.on('close', (code) => resolve({ code: code ?? 1, out: out.trim(), err: err.trim() }));
|
|
32
|
+
child.on('error', () => resolve({ code: 1, out: '', err: 'git unavailable' }));
|
|
33
|
+
if (input !== undefined && child.stdin !== null) {
|
|
34
|
+
child.stdin.on('error', () => { /* git exited before reading; its exit code reports it */ });
|
|
35
|
+
child.stdin.end(input);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const config = async (dir: string, key: string): Promise<string | null> => {
|
|
40
|
+
const r = await gitx(dir, ['config', '--get', key]);
|
|
41
|
+
return r.code === 0 && r.out !== '' ? r.out : null;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export interface SyncConfig {
|
|
45
|
+
readonly remote: string;
|
|
46
|
+
readonly branch: string;
|
|
47
|
+
/** The seat handle of the person operating this clone, if known. */
|
|
48
|
+
readonly handle: string | null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** This clone's sync configuration, or null when the session is not shared. */
|
|
52
|
+
export const syncConfig = async (dir: string): Promise<SyncConfig | null> => {
|
|
53
|
+
if ((await config(dir, 'politik.sync')) !== 'true') return null;
|
|
54
|
+
const remote = (await config(dir, 'politik.remote')) ?? 'origin';
|
|
55
|
+
const branch = (await config(dir, 'politik.branch')) ?? (await currentBranch(dir)) ?? 'main';
|
|
56
|
+
return { remote, branch, handle: await operatorHandle(dir) };
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** The seat handle for this clone: politik.handle, else git user.name. */
|
|
60
|
+
export const operatorHandle = async (dir: string): Promise<string | null> =>
|
|
61
|
+
(await config(dir, 'politik.handle')) ?? (await config(dir, 'user.name'));
|
|
62
|
+
|
|
63
|
+
/** `Name <email>` of the person operating this clone, for the provenance trailer. */
|
|
64
|
+
export const operatorIdentity = async (dir: string): Promise<string | null> => {
|
|
65
|
+
const name = await config(dir, 'user.name');
|
|
66
|
+
const email = await config(dir, 'user.email');
|
|
67
|
+
if (name === null && email === null) return null;
|
|
68
|
+
return [name, email === null ? null : `<${email}>`].filter((p) => p !== null).join(' ');
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export const currentBranch = async (dir: string): Promise<string | null> => {
|
|
72
|
+
const r = await gitx(dir, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
73
|
+
return r.code === 0 && r.out !== '' && r.out !== 'HEAD' ? r.out : null;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export const headSha = async (dir: string): Promise<string | null> => {
|
|
77
|
+
const r = await gitx(dir, ['rev-parse', 'HEAD']);
|
|
78
|
+
return r.code === 0 ? r.out : null;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
export const isRepo = async (dir: string): Promise<boolean> =>
|
|
82
|
+
(await gitx(dir, ['rev-parse', '--is-inside-work-tree'])).code === 0;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Turn sharing on: point the remote at `url`, record the configuration, and
|
|
86
|
+
* publish the current history. Reverts the configuration if publishing fails, so
|
|
87
|
+
* a half-configured clone never believes it is shared.
|
|
88
|
+
*/
|
|
89
|
+
export const enableSync = async (
|
|
90
|
+
dir: string,
|
|
91
|
+
url: string,
|
|
92
|
+
opts: { readonly remote?: string; readonly handle?: string | null } = {},
|
|
93
|
+
): Promise<{ readonly ok: boolean; readonly message: string }> => {
|
|
94
|
+
if (!(await isRepo(dir))) return { ok: false, message: `${dir} is not a git repository — convene the session (politik init) first` };
|
|
95
|
+
const branch = await currentBranch(dir);
|
|
96
|
+
if (branch === null) return { ok: false, message: 'not on a branch — check out the branch the record lives on' };
|
|
97
|
+
const remote = opts.remote ?? 'origin';
|
|
98
|
+
const existing = await gitx(dir, ['remote', 'get-url', remote]);
|
|
99
|
+
const set = existing.code === 0
|
|
100
|
+
? await gitx(dir, ['remote', 'set-url', remote, url])
|
|
101
|
+
: await gitx(dir, ['remote', 'add', remote, url]);
|
|
102
|
+
if (set.code !== 0) return { ok: false, message: `could not set remote ${remote}: ${set.err}` };
|
|
103
|
+
|
|
104
|
+
const published = await gitx(dir, ['push', '--set-upstream', remote, `HEAD:refs/heads/${branch}`]);
|
|
105
|
+
if (published.code !== 0) {
|
|
106
|
+
return { ok: false, message: `could not publish to ${url}: ${firstLine(published.err)}` };
|
|
107
|
+
}
|
|
108
|
+
await gitx(dir, ['config', 'politik.sync', 'true']);
|
|
109
|
+
await gitx(dir, ['config', 'politik.remote', remote]);
|
|
110
|
+
await gitx(dir, ['config', 'politik.branch', branch]);
|
|
111
|
+
if (opts.handle !== undefined && opts.handle !== null) await gitx(dir, ['config', 'politik.handle', opts.handle]);
|
|
112
|
+
return { ok: true, message: `shared via ${remote} (${url}) on branch ${branch}` };
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/** Configure sync on a fresh clone made by `politik join`. */
|
|
116
|
+
export const configureClone = async (dir: string, handle: string | null): Promise<SyncConfig | null> => {
|
|
117
|
+
const branch = await currentBranch(dir);
|
|
118
|
+
if (branch === null) return null;
|
|
119
|
+
// Acts commit under this clone's git identity. A machine with none configured
|
|
120
|
+
// gets the seat handle, the same convention Writ Drop uses for the Speaker.
|
|
121
|
+
if (handle !== null && (await config(dir, 'user.name')) === null) {
|
|
122
|
+
await gitx(dir, ['config', 'user.name', handle]);
|
|
123
|
+
await gitx(dir, ['config', 'user.email', `${handle}@politik.local`]);
|
|
124
|
+
}
|
|
125
|
+
await gitx(dir, ['config', 'politik.sync', 'true']);
|
|
126
|
+
await gitx(dir, ['config', 'politik.remote', 'origin']);
|
|
127
|
+
await gitx(dir, ['config', 'politik.branch', branch]);
|
|
128
|
+
if (handle !== null) await gitx(dir, ['config', 'politik.handle', handle]);
|
|
129
|
+
return syncConfig(dir);
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
export const disableSync = async (dir: string): Promise<void> => {
|
|
133
|
+
await gitx(dir, ['config', '--unset', 'politik.sync']);
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const firstLine = (s: string): string => s.split('\n').find((l) => l.trim() !== '')?.trim() ?? s;
|
|
137
|
+
|
|
138
|
+
/** Fetch the record's branches and the shared pending acts. */
|
|
139
|
+
export const fetchRemote = async (
|
|
140
|
+
dir: string,
|
|
141
|
+
cfg: SyncConfig,
|
|
142
|
+
): Promise<{ readonly ok: boolean; readonly reason: string }> => {
|
|
143
|
+
const r = await gitx(dir, [
|
|
144
|
+
'fetch', '--quiet', '--prune', cfg.remote,
|
|
145
|
+
`+refs/heads/*:refs/remotes/${cfg.remote}/*`,
|
|
146
|
+
`+${PENDING_REF_ROOT}*:${PENDING_REF_ROOT}*`,
|
|
147
|
+
]);
|
|
148
|
+
return r.code === 0 ? { ok: true, reason: 'fetched' } : { ok: false, reason: firstLine(r.err) };
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
export type FastForward = 'up-to-date' | 'fast-forwarded' | 'ahead' | 'diverged' | 'no-remote-branch' | 'blocked';
|
|
152
|
+
|
|
153
|
+
/** Bring the local record up to the shared one, without ever merging. */
|
|
154
|
+
export const fastForward = async (dir: string, cfg: SyncConfig): Promise<FastForward> => {
|
|
155
|
+
const remoteRef = `refs/remotes/${cfg.remote}/${cfg.branch}`;
|
|
156
|
+
if ((await gitx(dir, ['rev-parse', '--verify', '--quiet', remoteRef])).code !== 0) return 'no-remote-branch';
|
|
157
|
+
const counts = await gitx(dir, ['rev-list', '--left-right', '--count', `HEAD...${remoteRef}`]);
|
|
158
|
+
const [ahead, behind] = counts.out.split(/\s+/).map(Number);
|
|
159
|
+
if (ahead === undefined || behind === undefined || Number.isNaN(ahead) || Number.isNaN(behind)) return 'blocked';
|
|
160
|
+
if (ahead === 0 && behind === 0) return 'up-to-date';
|
|
161
|
+
if (ahead > 0 && behind > 0) return 'diverged';
|
|
162
|
+
if (ahead > 0) return 'ahead';
|
|
163
|
+
const ff = await gitx(dir, ['merge', '--ff-only', '--quiet', remoteRef]);
|
|
164
|
+
return ff.code === 0 ? 'fast-forwarded' : 'blocked';
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
/** Push the record. `rejected` means someone else pushed first. */
|
|
168
|
+
export const pushRecord = async (
|
|
169
|
+
dir: string,
|
|
170
|
+
cfg: SyncConfig,
|
|
171
|
+
): Promise<{ readonly ok: boolean; readonly rejected: boolean; readonly reason: string }> => {
|
|
172
|
+
const r = await gitx(dir, ['push', '--porcelain', cfg.remote, `HEAD:refs/heads/${cfg.branch}`]);
|
|
173
|
+
if (r.code === 0) return { ok: true, rejected: false, reason: 'pushed' };
|
|
174
|
+
const text = `${r.out}\n${r.err}`;
|
|
175
|
+
// Lost races: an ordinary non-fast-forward, or — when another push lands while
|
|
176
|
+
// ours is in flight — the receiving side refusing to move the ref.
|
|
177
|
+
const rejected = /\[rejected\]|\[remote rejected\]|non-fast-forward|fetch first|stale info|failed to update ref|cannot lock ref/
|
|
178
|
+
.test(text);
|
|
179
|
+
return { ok: false, rejected, reason: firstLine(r.err || r.out) };
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Discard local commits made since `sha`, keeping unrelated uncommitted work.
|
|
184
|
+
* `--keep` refuses rather than destroy local changes that would be overwritten.
|
|
185
|
+
*/
|
|
186
|
+
export const discardTo = async (dir: string, sha: string): Promise<boolean> =>
|
|
187
|
+
(await gitx(dir, ['reset', '--keep', sha])).code === 0;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* `politik sync`: reconcile the local record with the shared one. Rebases only
|
|
191
|
+
* when the two have genuinely diverged, and aborts cleanly on conflict.
|
|
192
|
+
*/
|
|
193
|
+
export const syncNow = async (
|
|
194
|
+
dir: string,
|
|
195
|
+
cfg: SyncConfig,
|
|
196
|
+
): Promise<{ readonly ok: boolean; readonly message: string }> => {
|
|
197
|
+
const f = await fetchRemote(dir, cfg);
|
|
198
|
+
if (!f.ok) return { ok: false, message: `cannot reach ${cfg.remote}: ${f.reason}` };
|
|
199
|
+
let state = await fastForward(dir, cfg);
|
|
200
|
+
if (state === 'diverged') {
|
|
201
|
+
const rebase = await gitx(dir, ['rebase', `refs/remotes/${cfg.remote}/${cfg.branch}`]);
|
|
202
|
+
if (rebase.code !== 0) {
|
|
203
|
+
await gitx(dir, ['rebase', '--abort']);
|
|
204
|
+
return {
|
|
205
|
+
ok: false,
|
|
206
|
+
message: 'the local and shared records have diverged and cannot be replayed automatically. '
|
|
207
|
+
+ 'Inspect with `git log --oneline --graph --all` and resolve by hand.',
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
state = 'ahead';
|
|
211
|
+
}
|
|
212
|
+
if (state === 'blocked') return { ok: false, message: 'could not fast-forward — uncommitted changes conflict with the shared record' };
|
|
213
|
+
if (state === 'ahead' || state === 'no-remote-branch') {
|
|
214
|
+
const p = await pushRecord(dir, cfg);
|
|
215
|
+
if (!p.ok) return { ok: false, message: `could not push: ${p.reason}` };
|
|
216
|
+
return { ok: true, message: 'local acts shared' };
|
|
217
|
+
}
|
|
218
|
+
return { ok: true, message: state === 'fast-forwarded' ? 'brought up to date' : 'already up to date' };
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
/* -------------------------------------------------------------------------- */
|
|
222
|
+
/* Shared pending acts (ADR-0011 §4) */
|
|
223
|
+
/* -------------------------------------------------------------------------- */
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Root of the refs holding staged acts. Each is `<root><session-guid>/<id>`,
|
|
227
|
+
* pointing at a commit whose tree holds `pending.json`. These refs travel with
|
|
228
|
+
* the session but are never on its branch: nothing staged is the record.
|
|
229
|
+
*/
|
|
230
|
+
export const PENDING_REF_ROOT = 'refs/politik/pending/';
|
|
231
|
+
|
|
232
|
+
const pendingRef = (guid: string, id: string): string => `${PENDING_REF_ROOT}${guid}/${id}`;
|
|
233
|
+
|
|
234
|
+
export const writePendingRef = async (
|
|
235
|
+
dir: string,
|
|
236
|
+
cfg: SyncConfig,
|
|
237
|
+
guid: string,
|
|
238
|
+
id: string,
|
|
239
|
+
json: string,
|
|
240
|
+
): Promise<{ readonly ok: boolean; readonly reason: string }> => {
|
|
241
|
+
const blob = await gitx(dir, ['hash-object', '-w', '--stdin'], json);
|
|
242
|
+
if (blob.code !== 0) return { ok: false, reason: blob.err };
|
|
243
|
+
const tree = await gitx(dir, ['mktree'], `100644 blob ${blob.out}\tpending.json\n`);
|
|
244
|
+
if (tree.code !== 0) return { ok: false, reason: tree.err };
|
|
245
|
+
const commit = await gitx(dir, ['commit-tree', tree.out, '-m', `pending ${id}`]);
|
|
246
|
+
if (commit.code !== 0) return { ok: false, reason: commit.err };
|
|
247
|
+
const ref = pendingRef(guid, id);
|
|
248
|
+
const upd = await gitx(dir, ['update-ref', ref, commit.out]);
|
|
249
|
+
if (upd.code !== 0) return { ok: false, reason: upd.err };
|
|
250
|
+
const push = await gitx(dir, ['push', '--quiet', cfg.remote, `${ref}:${ref}`]);
|
|
251
|
+
if (push.code !== 0) {
|
|
252
|
+
await gitx(dir, ['update-ref', '-d', ref]);
|
|
253
|
+
return { ok: false, reason: firstLine(push.err) };
|
|
254
|
+
}
|
|
255
|
+
return { ok: true, reason: 'shared' };
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
/** The JSON of every staged act for this session, from the local refs. */
|
|
259
|
+
export const readPendingRefs = async (dir: string, guid: string): Promise<readonly string[]> => {
|
|
260
|
+
const refs = await gitx(dir, ['for-each-ref', '--format=%(refname)', `${PENDING_REF_ROOT}${guid}/`]);
|
|
261
|
+
if (refs.code !== 0 || refs.out === '') return [];
|
|
262
|
+
const out: string[] = [];
|
|
263
|
+
for (const ref of refs.out.split('\n')) {
|
|
264
|
+
const show = await gitx(dir, ['show', `${ref}:pending.json`]);
|
|
265
|
+
if (show.code === 0) out.push(show.out);
|
|
266
|
+
}
|
|
267
|
+
return out;
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
export const deletePendingRef = async (dir: string, cfg: SyncConfig, guid: string, id: string): Promise<void> => {
|
|
271
|
+
const ref = pendingRef(guid, id);
|
|
272
|
+
await gitx(dir, ['update-ref', '-d', ref]);
|
|
273
|
+
await gitx(dir, ['push', '--quiet', cfg.remote, `:${ref}`]);
|
|
274
|
+
};
|