@prplkane/roundtable 0.6.3 → 0.6.6
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/CHANGELOG.md +52 -0
- package/LICENSE +21 -21
- package/README.md +11 -4
- package/SECURITY.md +21 -2
- package/docs/workflow.md +122 -8
- package/package.json +1 -1
- package/scripts/mcp.mjs +4 -2
- package/skills/roundtable/SKILL.md +6 -2
- package/src/adapters/acp.js +201 -0
- package/src/adapters/agy.js +7 -7
- package/src/adapters/claude.js +6 -6
- package/src/adapters/codex.js +6 -6
- package/src/adapters/config.js +11 -1
- package/src/adapters/index.js +2 -1
- package/src/agent-client.js +15 -3
- package/src/doctor.js +15 -3
- package/src/engine.js +2 -2
- package/src/export.js +307 -307
- package/src/local-server.js +32 -4
- package/src/notes.js +8 -4
- package/src/prompts.js +1 -1
- package/src/review-view.js +4 -2
- package/src/seats.js +19 -4
- package/src/server.js +42 -10
- package/src/snapshot.js +10 -3
- package/src/terminal.js +36 -12
- package/src/ui/app.js +18 -8
- package/src/ui/design/preset-dusk.css +91 -91
- package/src/ui/design/tokens.css +129 -129
- package/src/validate.js +4 -1
package/src/export.js
CHANGED
|
@@ -1,307 +1,307 @@
|
|
|
1
|
-
// Decision records: one plain-markdown file per debate, written into a codebase so an agent
|
|
2
|
-
// that can read the repo (sandboxed or not) can read what was decided and why, plus an index
|
|
3
|
-
// README.md listing every record. Pure functions over transcript rows, plus two file writers.
|
|
4
|
-
//
|
|
5
|
-
// decisionRecord(rows, slug) -> { markdown, meta } (pure)
|
|
6
|
-
// updateIndex(existing, meta) -> new index text, or null when the file is not ours (pure)
|
|
7
|
-
// validateTarget(target) -> absolute path of an existing directory, or throws
|
|
8
|
-
// exportDebate(rows, slug, target) -> { path, indexPath, meta } (writes both files)
|
|
9
|
-
//
|
|
10
|
-
// The exporter writes only into files it can prove it wrote: a record whose front matter names
|
|
11
|
-
// this slug under `roundtable:`, and an index region between two marker comments. Everything
|
|
12
|
-
// outside the region is kept byte for byte; any other file in the way is refused, never
|
|
13
|
-
// replaced.
|
|
14
|
-
import { existsSync, statSync, lstatSync, realpathSync, readFileSync, writeFileSync, openSync, closeSync, fchmodSync, renameSync, unlinkSync } from 'node:fs';
|
|
15
|
-
import { randomUUID } from 'node:crypto';
|
|
16
|
-
import os from 'node:os';
|
|
17
|
-
import path from 'node:path';
|
|
18
|
-
import { rebuildDebate, normaliseRows } from './store.js';
|
|
19
|
-
import { rollup } from './engine.js';
|
|
20
|
-
import { optionIds, optionId, optionLabel, recommendationPick, verdictSections, VERDICT_HEADERS } from './contract.js';
|
|
21
|
-
import { normLabel } from './validate.js';
|
|
22
|
-
import { noteRecord, noteAuthor } from './notes.js';
|
|
23
|
-
|
|
24
|
-
// The chairman's sections, same tolerance as the board (markdown emphasis around the header).
|
|
25
|
-
export function parseVerdict(text) {
|
|
26
|
-
const sections = verdictSections(text);
|
|
27
|
-
const out = {};
|
|
28
|
-
for (const h of VERDICT_HEADERS) out[h] = (sections[h] || []).map((l) => l.trim()).filter(Boolean).join('\n');
|
|
29
|
-
out.parsed = Object.keys(sections).length > 0;
|
|
30
|
-
return out;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// A 0.2.0 verdict has no grammar line. Its first line counts only when it begins with one exact
|
|
34
|
-
// option label followed by punctuation or nothing ("Ship now, on balance."), longest label first,
|
|
35
|
-
// so "Ship later, ..." never reads as "Ship" and "Do not use Postgres" never reads as Postgres.
|
|
36
|
-
function leadingOption(line, options) {
|
|
37
|
-
const s = normLabel(line || '');
|
|
38
|
-
for (const o of [...optionIds(options)].sort((a, b) => b.label.length - a.label.length)) {
|
|
39
|
-
const l = normLabel(o.label);
|
|
40
|
-
if (s === l || (s.startsWith(l) && /^[\s]*[,.;:!?(\u2014\u2013-]/.test(s.slice(l.length)))) return o.id;
|
|
41
|
-
}
|
|
42
|
-
return null;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// Which option the debate chose, as its label:
|
|
46
|
-
// - the option on the recommendation's first line;
|
|
47
|
-
// - 'no pick' when the chairman wrote none: an abstention is never filled in from the seats;
|
|
48
|
-
// - for a legacy verdict (no grammar) or a missing one, the option every seat ended on, and only
|
|
49
|
-
// when every seat has an eligible final stance;
|
|
50
|
-
// - otherwise 'no consensus'. Substring presence never counts.
|
|
51
|
-
// finalStances: one per seat, an option id or label, or null for a seat with no eligible stance.
|
|
52
|
-
export function chosenOption(options, recommendation, finalStances, { legacy = true } = {}) {
|
|
53
|
-
const first = String(recommendation || '').split(/\r?\n/).find((l) => l.trim()) || '';
|
|
54
|
-
const pick = recommendationPick(first, options) ?? (legacy ? leadingOption(first, options) : null);
|
|
55
|
-
if (pick === 'none') return 'no pick';
|
|
56
|
-
if (pick) return optionLabel(pick, options);
|
|
57
|
-
if (!legacy) return 'no consensus';
|
|
58
|
-
const ids = finalStances.map((s) => (s == null ? null : optionId(s, options)));
|
|
59
|
-
if (ids.length && ids.every(Boolean) && new Set(ids).size === 1) return optionLabel(ids[0], options);
|
|
60
|
-
return 'no consensus';
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
const STOPPED = new Set(['human', 'wall-clock', 'budget', 'all-failed', 'seats-down']);
|
|
64
|
-
const yaml = (v) => (typeof v === 'string' && /[:#"'\n]|^\s|\s$/.test(v) ? JSON.stringify(v) : String(v));
|
|
65
|
-
const k = (n) => (n || 0).toLocaleString('en-US');
|
|
66
|
-
|
|
67
|
-
export function decisionRecord(rows, slug, { warnings = [], metadataOnly = false } = {}) {
|
|
68
|
-
rows = normaliseRows(rows);
|
|
69
|
-
const rb = rebuildDebate(rows);
|
|
70
|
-
if (!rb) throw new Error('No field-notes row: nothing to export.');
|
|
71
|
-
const fn = rb.fieldNotes;
|
|
72
|
-
const options = fn.options || [];
|
|
73
|
-
const verdictRow = rb.verdict;
|
|
74
|
-
const v = parseVerdict(verdictRow?.skipped ? '' : verdictRow?.text);
|
|
75
|
-
const date = (rows.find((r) => r.t)?.t || new Date().toISOString()).slice(0, 10);
|
|
76
|
-
const seats = rb.seats;
|
|
77
|
-
const finalRound = rb.rounds.length - 1;
|
|
78
|
-
// A seat's final stance: its last reply's, where only a PASS carries an earlier stance forward.
|
|
79
|
-
// A failed or off-contract last reply leaves the seat with no eligible stance (null).
|
|
80
|
-
const finalStance = (seat) => {
|
|
81
|
-
for (let i = finalRound; i >= 0; i--) {
|
|
82
|
-
const r = rb.rounds[i]?.find((x) => (x.seat.id ?? `${x.seat.vendor}:${x.seat.lens}`) === (seat.id ?? `${seat.vendor}:${seat.lens}`));
|
|
83
|
-
if (!r) continue;
|
|
84
|
-
if (r.failed || !r.valid) return null;
|
|
85
|
-
if (r.stanceKey !== 'PASS') return r.stanceKey;
|
|
86
|
-
}
|
|
87
|
-
return null;
|
|
88
|
-
};
|
|
89
|
-
const head = rows.find((r) => r.type === 'field-notes');
|
|
90
|
-
const finals = seats.map(finalStance);
|
|
91
|
-
// the tally, counted in code from the final stances (the chairman's own is kept for comparison)
|
|
92
|
-
const counts = {};
|
|
93
|
-
for (const f of finals) { const k = f ? optionLabel(f, options) : 'no eligible stance'; counts[k] = (counts[k] || 0) + 1; }
|
|
94
|
-
const tallyCount = Object.keys(counts).length ? `Final: ${Object.entries(counts).sort((x, y) => y[1] - x[1]).map(([k, n]) => `${k} ${n}`).join(', ')}.` : '';
|
|
95
|
-
const legacy = !(head?.schemaVersion >= 3);
|
|
96
|
-
// a failed verdict (the chairman never met the grammar) is diagnostic text: it never chooses
|
|
97
|
-
const failedVerdict = !!(verdictRow?.failed && !verdictRow.skipped);
|
|
98
|
-
const chosen = failedVerdict ? 'no verdict' : chosenOption(options, v.RECOMMENDATION, finals, { legacy });
|
|
99
|
-
// The AI recommends; only a human decides. `accepted` comes from an `accepted` row (POST
|
|
100
|
-
// .../accept) and may differ from the recommendation; both are written.
|
|
101
|
-
const acceptedRow = [...rows].reverse().find((r) => r.type === 'accepted');
|
|
102
|
-
const accepted = acceptedRow ? (acceptedRow.option === 'none' ? 'no option' : optionLabel(acceptedRow.option, options)) : null;
|
|
103
|
-
const recommended = chosen;
|
|
104
|
-
const status = accepted ? 'accepted' : failedVerdict ? 'no verdict' : !rb.finished || !verdictRow || verdictRow.skipped || STOPPED.has(rb.stopReason) ? 'stopped' : chosen === 'no consensus' || chosen === 'no pick' ? 'split' : 'recommended';
|
|
105
|
-
const usage = rollup(rows);
|
|
106
|
-
const recoveryMessages = [...new Set([...rb.recoveryWarnings, ...warnings].map((w) => w.message).filter(Boolean))];
|
|
107
|
-
const meta = { title: fn.decision, date, slug, status, chosen: accepted ?? chosen, recommended, accepted, stopReason: rb.stopReason, file: `${slug}.md` };
|
|
108
|
-
if (metadataOnly) return { meta, summary: { decision: fn.decision, finished: rb.finished, seats: seats.length, rounds: rb.rounds.length, usage: usage.total, warning: recoveryMessages.at(-1) || null } };
|
|
109
|
-
|
|
110
|
-
// where the seat ran is part of the record: a CLI on a subscription, or an API endpoint by URL
|
|
111
|
-
const where = (s) => (s.endpoint ? `API ${s.endpoint}` : 'CLI');
|
|
112
|
-
const seatLine = (s) => [s.label || s.vendor, where(s), s.lens, s.mood?.preset === 'custom' ? `custom: ${s.mood.text}` : (s.mood?.preset || 'grill'), s.model || 'default model', s.effort || 'default effort'].join(', ');
|
|
113
|
-
const front = [
|
|
114
|
-
'---',
|
|
115
|
-
`title: ${yaml(fn.decision)}`,
|
|
116
|
-
`date: ${date}`,
|
|
117
|
-
`slug: ${slug}`,
|
|
118
|
-
`status: ${status}`,
|
|
119
|
-
`stop_reason: ${rb.stopReason || 'none'}`,
|
|
120
|
-
'options:',
|
|
121
|
-
...options.map((o) => ` - ${yaml(o)}`),
|
|
122
|
-
`chosen: ${yaml(accepted ?? chosen)}`,
|
|
123
|
-
`recommended: ${yaml(recommended)}`,
|
|
124
|
-
...(acceptedRow ? [`accepted: ${yaml(accepted)}`, `accepted_on: ${String(acceptedRow.t || '').slice(0, 10) || 'unknown'}`] : []),
|
|
125
|
-
'seats:',
|
|
126
|
-
...seats.map((s) => ` - ${yaml(seatLine(s))}`),
|
|
127
|
-
`chairman: ${rb.chairman?.vendor || 'none'}${rb.chairman?.endpoint ? ` at ${rb.chairman.endpoint}` : ''}${rb.chairman?.model ? ` (${rb.chairman.model})` : ''}`,
|
|
128
|
-
`rounds: ${rb.rounds.length}`,
|
|
129
|
-
`roundtable: ${slug}`,
|
|
130
|
-
'---',
|
|
131
|
-
];
|
|
132
|
-
const section = (title, body) => [`## ${title}`, '', body && body.trim() ? body.trim() : '_not given_', ''];
|
|
133
|
-
const list = (text) => text; // the chairman already writes bullets
|
|
134
|
-
const notesBody = [
|
|
135
|
-
fn.constraints ? `- **Constraints:** ${fn.constraints}` : null,
|
|
136
|
-
fn.known ? `- **Evidence, known:** ${fn.known}` : null,
|
|
137
|
-
fn.assumed ? `- **Evidence, assumed:** ${fn.assumed}` : null,
|
|
138
|
-
fn.reversibility ? `- **Reversibility:** ${fn.reversibility}` : null,
|
|
139
|
-
fn.deadline ? `- **Deadline:** ${fn.deadline}` : null,
|
|
140
|
-
].filter(Boolean).join('\n');
|
|
141
|
-
const tallyRows = seats.map((s, i) => {
|
|
142
|
-
const per = rb.rounds.map((round) => {
|
|
143
|
-
const r = round.find((x) => (x.seat.id ?? `${x.seat.vendor}:${x.seat.lens}`) === (s.id ?? `${s.vendor}:${s.lens}`));
|
|
144
|
-
return r ? (r.failed ? 'no reply' : optionLabel(r.stanceKey, options)) : '';
|
|
145
|
-
});
|
|
146
|
-
return `| ${s.label || s.vendor} · ${s.lens} | ${per.join(' | ')} | ${finals[i] ? optionLabel(finals[i], options) : 'none'} |`;
|
|
147
|
-
});
|
|
148
|
-
const tally = rb.rounds.length
|
|
149
|
-
? [`| seat | ${rb.rounds.map((_, i) => `round ${i}`).join(' | ')} | final |`, `|---|${rb.rounds.map(() => '---').join('|')}|---|`, ...tallyRows].join('\n')
|
|
150
|
-
: '';
|
|
151
|
-
const formatNotes = (notes) => notes.map((note) => `**${noteAuthor(note)}:** ${noteRecord(note).text}`).join('\n\n');
|
|
152
|
-
const humanNotes = [rb.initialNotes?.length ? `### Before round 0\n\n${formatNotes(rb.initialNotes)}` : null,
|
|
153
|
-
...rb.humanNotes.map((ns, i) => (ns?.length ? `### After round ${i}\n\n${formatNotes(ns)}` : null))].filter(Boolean).join('\n\n');
|
|
154
|
-
const costCell = (u) => (u.cost == null ? 'not reported' : `$${u.cost.toFixed(2)}${u.costCoverage && u.costCoverage.reported < u.costCoverage.of ? ` (partial: ${u.costCoverage.reported} of ${u.costCoverage.of} calls report a cost)` : ''}`);
|
|
155
|
-
const tokens = (n, u) => u.tokenCoverage?.reported === 0 ? 'unknown'
|
|
156
|
-
: `${k(n)}${u.tokenCoverage && u.tokenCoverage.reported < u.tokenCoverage.of ? ' (partial)' : ''}`;
|
|
157
|
-
const usageRows = seats.map((s) => {
|
|
158
|
-
const u = usage.bySeat[s.id ?? `${s.vendor}:${s.lens}`]?.usage;
|
|
159
|
-
return u ? `| ${s.label || s.vendor} · ${s.lens} | ${tokens(u.input, u)} | ${tokens(u.cacheRead + u.cacheWrite, u)} | ${tokens(u.output, u)} | ${costCell(u)} |` : null;
|
|
160
|
-
}).filter(Boolean);
|
|
161
|
-
const ch = usage.bySeat.chairman?.usage;
|
|
162
|
-
const researchUsage = usage.bySeat.research?.usage;
|
|
163
|
-
if (researchUsage) usageRows.push(`| searcher (${usage.bySeat.research.seat?.vendor || rb.options?.research?.vendor || 'codex'}) | ${tokens(researchUsage.input, researchUsage)} | ${tokens(researchUsage.cacheRead + researchUsage.cacheWrite, researchUsage)} | ${tokens(researchUsage.output, researchUsage)} | ${costCell(researchUsage)} |`);
|
|
164
|
-
if (ch) usageRows.push(`| chairman (${rb.chairman?.vendor || '?'}) | ${tokens(ch.input, ch)} | ${tokens(ch.cacheRead + ch.cacheWrite, ch)} | ${tokens(ch.output, ch)} | ${costCell(ch)} |`);
|
|
165
|
-
const t = usage.total;
|
|
166
|
-
const usageTable = usageRows.length
|
|
167
|
-
? ['| seat | input | cache | output | cost |', '|---|---|---|---|---|', ...usageRows, `| **debate** | ${tokens(t.input, t)} | ${tokens(t.cacheRead + t.cacheWrite, t)} | ${tokens(t.output, t)} | ${costCell(t)} |`].join('\n')
|
|
168
|
-
: '';
|
|
169
|
-
// a grammar line names an id: show its label in its place
|
|
170
|
-
const recText = v.parsed ? v.RECOMMENDATION.replace(/^\s*(opt-\d+)\b\.?/, (m, id) => `**${optionLabel(id, options)}** (${id})`) : '';
|
|
171
|
-
const recommendation = verdictRow?.skipped ? verdictRow.text : (v.parsed ? recText : (verdictRow?.text || ''));
|
|
172
|
-
|
|
173
|
-
const md = [
|
|
174
|
-
...front,
|
|
175
|
-
'',
|
|
176
|
-
`# ${fn.decision}`,
|
|
177
|
-
'',
|
|
178
|
-
acceptedRow
|
|
179
|
-
? `Accepted by the human on ${String(acceptedRow.t || date).slice(0, 10)}: **${accepted}**. Recommended by a roundtable of ${seats.length} seats on ${date}: **${recommended}** (stopped because: ${rb.stopReason || 'not stopped'}).`
|
|
180
|
-
: `Recommended by a roundtable of ${seats.length} seats on ${date}: **${recommended}** (${status}, stopped because: ${rb.stopReason || 'not stopped'}). Not yet accepted by a human.`,
|
|
181
|
-
...(acceptedRow?.note ? ['', `> ${String(acceptedRow.note).replace(/\r?\n/g, ' ')}`] : []),
|
|
182
|
-
'',
|
|
183
|
-
...(recoveryMessages.length ? section('Record recovery', recoveryMessages.join('\n\n')) : []),
|
|
184
|
-
...section('Question', `${fn.decision}\n\nOptions:\n${options.map((o) => `- ${o}`).join('\n')}`),
|
|
185
|
-
...section('Field notes', notesBody),
|
|
186
|
-
...(rb.research ? section('Shared web evidence', rb.research.status === 'done'
|
|
187
|
-
? ['Provider-supplied citations, excerpts and publication dates; not independently verified. Every seat received this saved bundle.',
|
|
188
|
-
`Gathered: ${rb.research.gatheredAt}. Reported search operations: ${rb.research.searches}.`,
|
|
189
|
-
...rb.research.sources.map((s) => `### ${s.id}: ${s.title.replace(/[\r\n]/g, ' ')}\n\n<${s.url}>\n\nPublished: ${s.publishedAt || 'not reported'}\n\n> ${s.excerpt.replace(/\r?\n/g, '\n> ')}`)].join('\n\n')
|
|
190
|
-
: rb.research.error || 'Research was interrupted; no source bundle was saved.') : []),
|
|
191
|
-
...section('Tally', [tally, tallyCount].filter(Boolean).join('\n\n')),
|
|
192
|
-
...section('Recommendation', recommendation),
|
|
193
|
-
...(v.TALLY ? section("Chairman's tally", v.TALLY) : []),
|
|
194
|
-
...section('Dissent', list(v.DISSENT)),
|
|
195
|
-
...section('Kill criteria', list(v.KILL_CRITERIA)),
|
|
196
|
-
...section('Open questions', list(v.OPEN_QUESTIONS)),
|
|
197
|
-
...section('Discussion notes', humanNotes),
|
|
198
|
-
...section('Usage', [usageTable, usage.unknownAttempts ? `${usage.unknownAttempts} call(s) did not report usable token counts. Totals include reported figures only; unknown usage is not zero.` : ''].filter(Boolean).join('\n\n')),
|
|
199
|
-
`_Exported by roundtable from debates/${slug}/transcript.jsonl._`,
|
|
200
|
-
'',
|
|
201
|
-
].join('\n');
|
|
202
|
-
return { markdown: md, meta };
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
const INDEX_INTRO = ['# Decision records', '', 'One file per roundtable debate, newest first. Written by `npm run export`; re-exporting a debate replaces its row.', ''];
|
|
206
|
-
const TABLE_HEAD = ['| date | title | chosen | status | record |', '|---|---|---|---|---|'];
|
|
207
|
-
const REGION_START = '<!-- roundtable:index -->';
|
|
208
|
-
const REGION_END = '<!-- roundtable:index:end -->';
|
|
209
|
-
const cell = (s) => String(s ?? '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
|
|
210
|
-
const isRow = (l) => /^\|\s*\d{4}-\d{2}-\d{2}\s*\|/.test(l);
|
|
211
|
-
|
|
212
|
-
// The index: create it, or replace this slug's row inside our marked region. A legacy index
|
|
213
|
-
// (written before the markers, recognised by its whole header, not by a date column) is
|
|
214
|
-
// converted, keeping what was written around its table. Returns null for any other file.
|
|
215
|
-
export function updateIndex(existing, meta) {
|
|
216
|
-
const row = `| ${meta.date} | ${cell(meta.title)} | ${cell(meta.chosen)} | ${meta.status} | [${meta.file}](./${meta.file}) |`;
|
|
217
|
-
const region = (oldRows) => {
|
|
218
|
-
const rows = oldRows.filter(isRow).filter((l) => !l.includes(`](./${meta.file})`));
|
|
219
|
-
rows.push(row);
|
|
220
|
-
rows.sort((a, b) => (b.slice(2, 12).localeCompare(a.slice(2, 12))) || a.localeCompare(b));
|
|
221
|
-
return [REGION_START, ...TABLE_HEAD, ...rows, REGION_END];
|
|
222
|
-
};
|
|
223
|
-
if (existing == null) return [...INDEX_INTRO, ...region([]), ''].join('\n');
|
|
224
|
-
const eol = existing.includes('\r\n') ? '\r\n' : '\n';
|
|
225
|
-
const lines = existing.split(/\r?\n/);
|
|
226
|
-
const start = lines.indexOf(REGION_START), end = lines.indexOf(REGION_END);
|
|
227
|
-
if (start >= 0 && end > start) return [...lines.slice(0, start), ...region(lines.slice(start + 1, end)), ...lines.slice(end + 1)].join(eol);
|
|
228
|
-
// legacy: our title, our sentence, our exact table header
|
|
229
|
-
const header = lines.indexOf(TABLE_HEAD[0]);
|
|
230
|
-
const legacy = lines[0] === INDEX_INTRO[0] && lines.some((l) => l.startsWith('One file per roundtable debate') && l.includes('Written by `npm run export`')) && header > 0 && lines[header + 1] === TABLE_HEAD[1];
|
|
231
|
-
if (!legacy) return null;
|
|
232
|
-
let after = header + 2;
|
|
233
|
-
while (after < lines.length && isRow(lines[after])) after++;
|
|
234
|
-
return [...lines.slice(0, header), ...region(lines.slice(header + 2, after)), ...lines.slice(after)].join(eol);
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// A record file is ours when its front matter names this slug under `roundtable:`; a legacy
|
|
238
|
-
// record (before that key) when it has our `slug:` line and our opening sentence.
|
|
239
|
-
export function ownsRecord(text, slug) {
|
|
240
|
-
const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] || '';
|
|
241
|
-
if (new RegExp(`^roundtable: ${slug}$`, 'm').test(front)) return true;
|
|
242
|
-
return new RegExp(`^slug: ${slug}$`, 'm').test(front) && /\nDecided by a roundtable of \d+ seats on /.test(text); // the 0.2.0 sentence
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// An existing directory, as an absolute path. Records are named from the slug, which is
|
|
246
|
-
// restricted to [a-z0-9-], so the written path can only be directly inside it.
|
|
247
|
-
// forbid: further directories the caller will not write into (the server's own debates dir).
|
|
248
|
-
export function validateTarget(target, { forbid = [] } = {}) {
|
|
249
|
-
if (!target || typeof target !== 'string') throw new Error('Export needs a target directory.');
|
|
250
|
-
let abs = path.resolve(target);
|
|
251
|
-
if (!existsSync(abs) || !statSync(abs).isDirectory()) throw new Error(`Export target is not an existing directory: ${abs}`);
|
|
252
|
-
abs = realpathSync(abs);
|
|
253
|
-
const same = (dir) => path.relative(existsSync(dir) ? realpathSync(dir) : path.resolve(dir), abs) === '';
|
|
254
|
-
if (path.parse(abs).root === abs) throw new Error(`Refusing to export into a filesystem root: ${abs}`);
|
|
255
|
-
if (same(os.homedir())) throw new Error(`Refusing to export into the home directory: ${abs}. Pick a decisions folder inside a project.`);
|
|
256
|
-
for (const f of forbid) if (same(f)) throw new Error(`Refusing to export into ${abs}: roundtable keeps its own transcripts there.`);
|
|
257
|
-
return abs;
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
export function recordPath(target, slug, opts) {
|
|
261
|
-
if (!/^[a-z0-9-]+$/.test(slug)) throw new Error(`Bad slug: ${slug}`);
|
|
262
|
-
const abs = validateTarget(target, opts);
|
|
263
|
-
const file = path.resolve(abs, `${slug}.md`);
|
|
264
|
-
if (path.dirname(file) !== abs) throw new Error('Refusing to write outside the target directory.');
|
|
265
|
-
return file;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
// Temp file in the same directory, then rename: a reader never sees half a file.
|
|
269
|
-
function writeAtomic(file, text, mode) {
|
|
270
|
-
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
271
|
-
const fd = openSync(tmp, 'wx', mode ?? 0o666);
|
|
272
|
-
try {
|
|
273
|
-
try {
|
|
274
|
-
writeFileSync(fd, text);
|
|
275
|
-
// Creation respects umask; an existing record/index keeps its exact access bits.
|
|
276
|
-
if (mode != null && process.platform !== 'win32') fchmodSync(fd, mode);
|
|
277
|
-
} finally { closeSync(fd); }
|
|
278
|
-
renameSync(tmp, file);
|
|
279
|
-
} finally { if (existsSync(tmp)) unlinkSync(tmp); }
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
function regularOrAbsent(file) {
|
|
283
|
-
try {
|
|
284
|
-
const s = lstatSync(file);
|
|
285
|
-
if (!s.isFile() || s.isSymbolicLink()) throw new Error(`Refusing linked or non-file export destination: ${file}`);
|
|
286
|
-
return s.mode & 0o777;
|
|
287
|
-
} catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
// Every check runs before the first write, so a refusal leaves the directory untouched.
|
|
291
|
-
export function exportDebate(rows, slug, target, opts) {
|
|
292
|
-
const file = recordPath(target, slug, opts);
|
|
293
|
-
const mode = regularOrAbsent(file);
|
|
294
|
-
if (existsSync(file) && !ownsRecord(readFileSync(file, 'utf8'), slug)) throw new Error(`Refusing to replace ${file}: it was not written by roundtable for this debate.`);
|
|
295
|
-
const { markdown, meta } = decisionRecord(rows, slug, opts);
|
|
296
|
-
let indexPath = null, indexText = null, indexMode;
|
|
297
|
-
for (const name of ['README.md', 'DECISIONS.md']) {
|
|
298
|
-
const p = path.join(path.dirname(file), name);
|
|
299
|
-
const candidateMode = regularOrAbsent(p);
|
|
300
|
-
const next = updateIndex(existsSync(p) ? readFileSync(p, 'utf8') : null, meta);
|
|
301
|
-
if (next != null) { indexPath = p; indexText = next; indexMode = candidateMode; break; }
|
|
302
|
-
}
|
|
303
|
-
if (!indexPath) throw new Error(`Refusing to export into ${path.dirname(file)}: README.md and DECISIONS.md both exist and neither is a roundtable index.`);
|
|
304
|
-
writeAtomic(file, markdown, mode);
|
|
305
|
-
writeAtomic(indexPath, indexText, indexMode);
|
|
306
|
-
return { path: file, indexPath, meta };
|
|
307
|
-
}
|
|
1
|
+
// Decision records: one plain-markdown file per debate, written into a codebase so an agent
|
|
2
|
+
// that can read the repo (sandboxed or not) can read what was decided and why, plus an index
|
|
3
|
+
// README.md listing every record. Pure functions over transcript rows, plus two file writers.
|
|
4
|
+
//
|
|
5
|
+
// decisionRecord(rows, slug) -> { markdown, meta } (pure)
|
|
6
|
+
// updateIndex(existing, meta) -> new index text, or null when the file is not ours (pure)
|
|
7
|
+
// validateTarget(target) -> absolute path of an existing directory, or throws
|
|
8
|
+
// exportDebate(rows, slug, target) -> { path, indexPath, meta } (writes both files)
|
|
9
|
+
//
|
|
10
|
+
// The exporter writes only into files it can prove it wrote: a record whose front matter names
|
|
11
|
+
// this slug under `roundtable:`, and an index region between two marker comments. Everything
|
|
12
|
+
// outside the region is kept byte for byte; any other file in the way is refused, never
|
|
13
|
+
// replaced.
|
|
14
|
+
import { existsSync, statSync, lstatSync, realpathSync, readFileSync, writeFileSync, openSync, closeSync, fchmodSync, renameSync, unlinkSync } from 'node:fs';
|
|
15
|
+
import { randomUUID } from 'node:crypto';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { rebuildDebate, normaliseRows } from './store.js';
|
|
19
|
+
import { rollup } from './engine.js';
|
|
20
|
+
import { optionIds, optionId, optionLabel, recommendationPick, verdictSections, VERDICT_HEADERS } from './contract.js';
|
|
21
|
+
import { normLabel } from './validate.js';
|
|
22
|
+
import { noteRecord, noteAuthor } from './notes.js';
|
|
23
|
+
|
|
24
|
+
// The chairman's sections, same tolerance as the board (markdown emphasis around the header).
|
|
25
|
+
export function parseVerdict(text) {
|
|
26
|
+
const sections = verdictSections(text);
|
|
27
|
+
const out = {};
|
|
28
|
+
for (const h of VERDICT_HEADERS) out[h] = (sections[h] || []).map((l) => l.trim()).filter(Boolean).join('\n');
|
|
29
|
+
out.parsed = Object.keys(sections).length > 0;
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// A 0.2.0 verdict has no grammar line. Its first line counts only when it begins with one exact
|
|
34
|
+
// option label followed by punctuation or nothing ("Ship now, on balance."), longest label first,
|
|
35
|
+
// so "Ship later, ..." never reads as "Ship" and "Do not use Postgres" never reads as Postgres.
|
|
36
|
+
function leadingOption(line, options) {
|
|
37
|
+
const s = normLabel(line || '');
|
|
38
|
+
for (const o of [...optionIds(options)].sort((a, b) => b.label.length - a.label.length)) {
|
|
39
|
+
const l = normLabel(o.label);
|
|
40
|
+
if (s === l || (s.startsWith(l) && /^[\s]*[,.;:!?(\u2014\u2013-]/.test(s.slice(l.length)))) return o.id;
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Which option the debate chose, as its label:
|
|
46
|
+
// - the option on the recommendation's first line;
|
|
47
|
+
// - 'no pick' when the chairman wrote none: an abstention is never filled in from the seats;
|
|
48
|
+
// - for a legacy verdict (no grammar) or a missing one, the option every seat ended on, and only
|
|
49
|
+
// when every seat has an eligible final stance;
|
|
50
|
+
// - otherwise 'no consensus'. Substring presence never counts.
|
|
51
|
+
// finalStances: one per seat, an option id or label, or null for a seat with no eligible stance.
|
|
52
|
+
export function chosenOption(options, recommendation, finalStances, { legacy = true } = {}) {
|
|
53
|
+
const first = String(recommendation || '').split(/\r?\n/).find((l) => l.trim()) || '';
|
|
54
|
+
const pick = recommendationPick(first, options) ?? (legacy ? leadingOption(first, options) : null);
|
|
55
|
+
if (pick === 'none') return 'no pick';
|
|
56
|
+
if (pick) return optionLabel(pick, options);
|
|
57
|
+
if (!legacy) return 'no consensus';
|
|
58
|
+
const ids = finalStances.map((s) => (s == null ? null : optionId(s, options)));
|
|
59
|
+
if (ids.length && ids.every(Boolean) && new Set(ids).size === 1) return optionLabel(ids[0], options);
|
|
60
|
+
return 'no consensus';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const STOPPED = new Set(['human', 'wall-clock', 'budget', 'all-failed', 'seats-down']);
|
|
64
|
+
const yaml = (v) => (typeof v === 'string' && /[:#"'\n]|^\s|\s$/.test(v) ? JSON.stringify(v) : String(v));
|
|
65
|
+
const k = (n) => (n || 0).toLocaleString('en-US');
|
|
66
|
+
|
|
67
|
+
export function decisionRecord(rows, slug, { warnings = [], metadataOnly = false } = {}) {
|
|
68
|
+
rows = normaliseRows(rows);
|
|
69
|
+
const rb = rebuildDebate(rows);
|
|
70
|
+
if (!rb) throw new Error('No field-notes row: nothing to export.');
|
|
71
|
+
const fn = rb.fieldNotes;
|
|
72
|
+
const options = fn.options || [];
|
|
73
|
+
const verdictRow = rb.verdict;
|
|
74
|
+
const v = parseVerdict(verdictRow?.skipped ? '' : verdictRow?.text);
|
|
75
|
+
const date = (rows.find((r) => r.t)?.t || new Date().toISOString()).slice(0, 10);
|
|
76
|
+
const seats = rb.seats;
|
|
77
|
+
const finalRound = rb.rounds.length - 1;
|
|
78
|
+
// A seat's final stance: its last reply's, where only a PASS carries an earlier stance forward.
|
|
79
|
+
// A failed or off-contract last reply leaves the seat with no eligible stance (null).
|
|
80
|
+
const finalStance = (seat) => {
|
|
81
|
+
for (let i = finalRound; i >= 0; i--) {
|
|
82
|
+
const r = rb.rounds[i]?.find((x) => (x.seat.id ?? `${x.seat.vendor}:${x.seat.lens}`) === (seat.id ?? `${seat.vendor}:${seat.lens}`));
|
|
83
|
+
if (!r) continue;
|
|
84
|
+
if (r.failed || !r.valid) return null;
|
|
85
|
+
if (r.stanceKey !== 'PASS') return r.stanceKey;
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
};
|
|
89
|
+
const head = rows.find((r) => r.type === 'field-notes');
|
|
90
|
+
const finals = seats.map(finalStance);
|
|
91
|
+
// the tally, counted in code from the final stances (the chairman's own is kept for comparison)
|
|
92
|
+
const counts = {};
|
|
93
|
+
for (const f of finals) { const k = f ? optionLabel(f, options) : 'no eligible stance'; counts[k] = (counts[k] || 0) + 1; }
|
|
94
|
+
const tallyCount = Object.keys(counts).length ? `Final: ${Object.entries(counts).sort((x, y) => y[1] - x[1]).map(([k, n]) => `${k} ${n}`).join(', ')}.` : '';
|
|
95
|
+
const legacy = !(head?.schemaVersion >= 3);
|
|
96
|
+
// a failed verdict (the chairman never met the grammar) is diagnostic text: it never chooses
|
|
97
|
+
const failedVerdict = !!(verdictRow?.failed && !verdictRow.skipped);
|
|
98
|
+
const chosen = failedVerdict ? 'no verdict' : chosenOption(options, v.RECOMMENDATION, finals, { legacy });
|
|
99
|
+
// The AI recommends; only a human decides. `accepted` comes from an `accepted` row (POST
|
|
100
|
+
// .../accept) and may differ from the recommendation; both are written.
|
|
101
|
+
const acceptedRow = [...rows].reverse().find((r) => r.type === 'accepted');
|
|
102
|
+
const accepted = acceptedRow ? (acceptedRow.option === 'none' ? 'no option' : optionLabel(acceptedRow.option, options)) : null;
|
|
103
|
+
const recommended = chosen;
|
|
104
|
+
const status = accepted ? 'accepted' : failedVerdict ? 'no verdict' : !rb.finished || !verdictRow || verdictRow.skipped || STOPPED.has(rb.stopReason) ? 'stopped' : chosen === 'no consensus' || chosen === 'no pick' ? 'split' : 'recommended';
|
|
105
|
+
const usage = rollup(rows);
|
|
106
|
+
const recoveryMessages = [...new Set([...rb.recoveryWarnings, ...warnings].map((w) => w.message).filter(Boolean))];
|
|
107
|
+
const meta = { title: fn.decision, date, slug, status, chosen: accepted ?? chosen, recommended, accepted, stopReason: rb.stopReason, file: `${slug}.md` };
|
|
108
|
+
if (metadataOnly) return { meta, summary: { decision: fn.decision, finished: rb.finished, seats: seats.length, rounds: rb.rounds.length, usage: usage.total, warning: recoveryMessages.at(-1) || null } };
|
|
109
|
+
|
|
110
|
+
// where the seat ran is part of the record: a CLI on a subscription, or an API endpoint by URL
|
|
111
|
+
const where = (s) => (s.endpoint ? `API ${s.endpoint}` : 'CLI');
|
|
112
|
+
const seatLine = (s) => [s.label || s.vendor, where(s), s.lens, s.mood?.preset === 'custom' ? `custom: ${s.mood.text}` : (s.mood?.preset || 'grill'), s.model || 'default model', s.effort || 'default effort'].join(', ');
|
|
113
|
+
const front = [
|
|
114
|
+
'---',
|
|
115
|
+
`title: ${yaml(fn.decision)}`,
|
|
116
|
+
`date: ${date}`,
|
|
117
|
+
`slug: ${slug}`,
|
|
118
|
+
`status: ${status}`,
|
|
119
|
+
`stop_reason: ${rb.stopReason || 'none'}`,
|
|
120
|
+
'options:',
|
|
121
|
+
...options.map((o) => ` - ${yaml(o)}`),
|
|
122
|
+
`chosen: ${yaml(accepted ?? chosen)}`,
|
|
123
|
+
`recommended: ${yaml(recommended)}`,
|
|
124
|
+
...(acceptedRow ? [`accepted: ${yaml(accepted)}`, `accepted_on: ${String(acceptedRow.t || '').slice(0, 10) || 'unknown'}`] : []),
|
|
125
|
+
'seats:',
|
|
126
|
+
...seats.map((s) => ` - ${yaml(seatLine(s))}`),
|
|
127
|
+
`chairman: ${rb.chairman?.vendor || 'none'}${rb.chairman?.endpoint ? ` at ${rb.chairman.endpoint}` : ''}${rb.chairman?.model ? ` (${rb.chairman.model})` : ''}`,
|
|
128
|
+
`rounds: ${rb.rounds.length}`,
|
|
129
|
+
`roundtable: ${slug}`,
|
|
130
|
+
'---',
|
|
131
|
+
];
|
|
132
|
+
const section = (title, body) => [`## ${title}`, '', body && body.trim() ? body.trim() : '_not given_', ''];
|
|
133
|
+
const list = (text) => text; // the chairman already writes bullets
|
|
134
|
+
const notesBody = [
|
|
135
|
+
fn.constraints ? `- **Constraints:** ${fn.constraints}` : null,
|
|
136
|
+
fn.known ? `- **Evidence, known:** ${fn.known}` : null,
|
|
137
|
+
fn.assumed ? `- **Evidence, assumed:** ${fn.assumed}` : null,
|
|
138
|
+
fn.reversibility ? `- **Reversibility:** ${fn.reversibility}` : null,
|
|
139
|
+
fn.deadline ? `- **Deadline:** ${fn.deadline}` : null,
|
|
140
|
+
].filter(Boolean).join('\n');
|
|
141
|
+
const tallyRows = seats.map((s, i) => {
|
|
142
|
+
const per = rb.rounds.map((round) => {
|
|
143
|
+
const r = round.find((x) => (x.seat.id ?? `${x.seat.vendor}:${x.seat.lens}`) === (s.id ?? `${s.vendor}:${s.lens}`));
|
|
144
|
+
return r ? (r.failed ? 'no reply' : optionLabel(r.stanceKey, options)) : '';
|
|
145
|
+
});
|
|
146
|
+
return `| ${s.label || s.vendor} · ${s.lens} | ${per.join(' | ')} | ${finals[i] ? optionLabel(finals[i], options) : 'none'} |`;
|
|
147
|
+
});
|
|
148
|
+
const tally = rb.rounds.length
|
|
149
|
+
? [`| seat | ${rb.rounds.map((_, i) => `round ${i}`).join(' | ')} | final |`, `|---|${rb.rounds.map(() => '---').join('|')}|---|`, ...tallyRows].join('\n')
|
|
150
|
+
: '';
|
|
151
|
+
const formatNotes = (notes) => notes.map((note) => `**${noteAuthor(note)}:** ${noteRecord(note).text}`).join('\n\n');
|
|
152
|
+
const humanNotes = [rb.initialNotes?.length ? `### Before round 0\n\n${formatNotes(rb.initialNotes)}` : null,
|
|
153
|
+
...rb.humanNotes.map((ns, i) => (ns?.length ? `### After round ${i}\n\n${formatNotes(ns)}` : null))].filter(Boolean).join('\n\n');
|
|
154
|
+
const costCell = (u) => (u.cost == null ? 'not reported' : `$${u.cost.toFixed(2)}${u.costCoverage && u.costCoverage.reported < u.costCoverage.of ? ` (partial: ${u.costCoverage.reported} of ${u.costCoverage.of} calls report a cost)` : ''}`);
|
|
155
|
+
const tokens = (n, u) => u.tokenCoverage?.reported === 0 ? 'unknown'
|
|
156
|
+
: `${k(n)}${u.tokenCoverage && u.tokenCoverage.reported < u.tokenCoverage.of ? ' (partial)' : ''}`;
|
|
157
|
+
const usageRows = seats.map((s) => {
|
|
158
|
+
const u = usage.bySeat[s.id ?? `${s.vendor}:${s.lens}`]?.usage;
|
|
159
|
+
return u ? `| ${s.label || s.vendor} · ${s.lens} | ${tokens(u.input, u)} | ${tokens(u.cacheRead + u.cacheWrite, u)} | ${tokens(u.output, u)} | ${costCell(u)} |` : null;
|
|
160
|
+
}).filter(Boolean);
|
|
161
|
+
const ch = usage.bySeat.chairman?.usage;
|
|
162
|
+
const researchUsage = usage.bySeat.research?.usage;
|
|
163
|
+
if (researchUsage) usageRows.push(`| searcher (${usage.bySeat.research.seat?.vendor || rb.options?.research?.vendor || 'codex'}) | ${tokens(researchUsage.input, researchUsage)} | ${tokens(researchUsage.cacheRead + researchUsage.cacheWrite, researchUsage)} | ${tokens(researchUsage.output, researchUsage)} | ${costCell(researchUsage)} |`);
|
|
164
|
+
if (ch) usageRows.push(`| chairman (${rb.chairman?.vendor || '?'}) | ${tokens(ch.input, ch)} | ${tokens(ch.cacheRead + ch.cacheWrite, ch)} | ${tokens(ch.output, ch)} | ${costCell(ch)} |`);
|
|
165
|
+
const t = usage.total;
|
|
166
|
+
const usageTable = usageRows.length
|
|
167
|
+
? ['| seat | input | cache | output | cost |', '|---|---|---|---|---|', ...usageRows, `| **debate** | ${tokens(t.input, t)} | ${tokens(t.cacheRead + t.cacheWrite, t)} | ${tokens(t.output, t)} | ${costCell(t)} |`].join('\n')
|
|
168
|
+
: '';
|
|
169
|
+
// a grammar line names an id: show its label in its place
|
|
170
|
+
const recText = v.parsed ? v.RECOMMENDATION.replace(/^\s*(opt-\d+)\b\.?/, (m, id) => `**${optionLabel(id, options)}** (${id})`) : '';
|
|
171
|
+
const recommendation = verdictRow?.skipped ? verdictRow.text : (v.parsed ? recText : (verdictRow?.text || ''));
|
|
172
|
+
|
|
173
|
+
const md = [
|
|
174
|
+
...front,
|
|
175
|
+
'',
|
|
176
|
+
`# ${fn.decision}`,
|
|
177
|
+
'',
|
|
178
|
+
acceptedRow
|
|
179
|
+
? `Accepted by the human on ${String(acceptedRow.t || date).slice(0, 10)}: **${accepted}**. Recommended by a roundtable of ${seats.length} seats on ${date}: **${recommended}** (stopped because: ${rb.stopReason || 'not stopped'}).`
|
|
180
|
+
: `Recommended by a roundtable of ${seats.length} seats on ${date}: **${recommended}** (${status}, stopped because: ${rb.stopReason || 'not stopped'}). Not yet accepted by a human.`,
|
|
181
|
+
...(acceptedRow?.note ? ['', `> ${String(acceptedRow.note).replace(/\r?\n/g, ' ')}`] : []),
|
|
182
|
+
'',
|
|
183
|
+
...(recoveryMessages.length ? section('Record recovery', recoveryMessages.join('\n\n')) : []),
|
|
184
|
+
...section('Question', `${fn.decision}\n\nOptions:\n${options.map((o) => `- ${o}`).join('\n')}`),
|
|
185
|
+
...section('Field notes', notesBody),
|
|
186
|
+
...(rb.research ? section('Shared web evidence', rb.research.status === 'done'
|
|
187
|
+
? ['Provider-supplied citations, excerpts and publication dates; not independently verified. Every seat received this saved bundle.',
|
|
188
|
+
`Gathered: ${rb.research.gatheredAt}. Reported search operations: ${rb.research.searches}.`,
|
|
189
|
+
...rb.research.sources.map((s) => `### ${s.id}: ${s.title.replace(/[\r\n]/g, ' ')}\n\n<${s.url}>\n\nPublished: ${s.publishedAt || 'not reported'}\n\n> ${s.excerpt.replace(/\r?\n/g, '\n> ')}`)].join('\n\n')
|
|
190
|
+
: rb.research.error || 'Research was interrupted; no source bundle was saved.') : []),
|
|
191
|
+
...section('Tally', [tally, tallyCount].filter(Boolean).join('\n\n')),
|
|
192
|
+
...section('Recommendation', recommendation),
|
|
193
|
+
...(v.TALLY ? section("Chairman's tally", v.TALLY) : []),
|
|
194
|
+
...section('Dissent', list(v.DISSENT)),
|
|
195
|
+
...section('Kill criteria', list(v.KILL_CRITERIA)),
|
|
196
|
+
...section('Open questions', list(v.OPEN_QUESTIONS)),
|
|
197
|
+
...section('Discussion notes', humanNotes),
|
|
198
|
+
...section('Usage', [usageTable, usage.unknownAttempts ? `${usage.unknownAttempts} call(s) did not report usable token counts. Totals include reported figures only; unknown usage is not zero.` : ''].filter(Boolean).join('\n\n')),
|
|
199
|
+
`_Exported by roundtable from debates/${slug}/transcript.jsonl._`,
|
|
200
|
+
'',
|
|
201
|
+
].join('\n');
|
|
202
|
+
return { markdown: md, meta };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const INDEX_INTRO = ['# Decision records', '', 'One file per roundtable debate, newest first. Written by `npm run export`; re-exporting a debate replaces its row.', ''];
|
|
206
|
+
const TABLE_HEAD = ['| date | title | chosen | status | record |', '|---|---|---|---|---|'];
|
|
207
|
+
const REGION_START = '<!-- roundtable:index -->';
|
|
208
|
+
const REGION_END = '<!-- roundtable:index:end -->';
|
|
209
|
+
const cell = (s) => String(s ?? '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
|
|
210
|
+
const isRow = (l) => /^\|\s*\d{4}-\d{2}-\d{2}\s*\|/.test(l);
|
|
211
|
+
|
|
212
|
+
// The index: create it, or replace this slug's row inside our marked region. A legacy index
|
|
213
|
+
// (written before the markers, recognised by its whole header, not by a date column) is
|
|
214
|
+
// converted, keeping what was written around its table. Returns null for any other file.
|
|
215
|
+
export function updateIndex(existing, meta) {
|
|
216
|
+
const row = `| ${meta.date} | ${cell(meta.title)} | ${cell(meta.chosen)} | ${meta.status} | [${meta.file}](./${meta.file}) |`;
|
|
217
|
+
const region = (oldRows) => {
|
|
218
|
+
const rows = oldRows.filter(isRow).filter((l) => !l.includes(`](./${meta.file})`));
|
|
219
|
+
rows.push(row);
|
|
220
|
+
rows.sort((a, b) => (b.slice(2, 12).localeCompare(a.slice(2, 12))) || a.localeCompare(b));
|
|
221
|
+
return [REGION_START, ...TABLE_HEAD, ...rows, REGION_END];
|
|
222
|
+
};
|
|
223
|
+
if (existing == null) return [...INDEX_INTRO, ...region([]), ''].join('\n');
|
|
224
|
+
const eol = existing.includes('\r\n') ? '\r\n' : '\n';
|
|
225
|
+
const lines = existing.split(/\r?\n/);
|
|
226
|
+
const start = lines.indexOf(REGION_START), end = lines.indexOf(REGION_END);
|
|
227
|
+
if (start >= 0 && end > start) return [...lines.slice(0, start), ...region(lines.slice(start + 1, end)), ...lines.slice(end + 1)].join(eol);
|
|
228
|
+
// legacy: our title, our sentence, our exact table header
|
|
229
|
+
const header = lines.indexOf(TABLE_HEAD[0]);
|
|
230
|
+
const legacy = lines[0] === INDEX_INTRO[0] && lines.some((l) => l.startsWith('One file per roundtable debate') && l.includes('Written by `npm run export`')) && header > 0 && lines[header + 1] === TABLE_HEAD[1];
|
|
231
|
+
if (!legacy) return null;
|
|
232
|
+
let after = header + 2;
|
|
233
|
+
while (after < lines.length && isRow(lines[after])) after++;
|
|
234
|
+
return [...lines.slice(0, header), ...region(lines.slice(header + 2, after)), ...lines.slice(after)].join(eol);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// A record file is ours when its front matter names this slug under `roundtable:`; a legacy
|
|
238
|
+
// record (before that key) when it has our `slug:` line and our opening sentence.
|
|
239
|
+
export function ownsRecord(text, slug) {
|
|
240
|
+
const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] || '';
|
|
241
|
+
if (new RegExp(`^roundtable: ${slug}$`, 'm').test(front)) return true;
|
|
242
|
+
return new RegExp(`^slug: ${slug}$`, 'm').test(front) && /\nDecided by a roundtable of \d+ seats on /.test(text); // the 0.2.0 sentence
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// An existing directory, as an absolute path. Records are named from the slug, which is
|
|
246
|
+
// restricted to [a-z0-9-], so the written path can only be directly inside it.
|
|
247
|
+
// forbid: further directories the caller will not write into (the server's own debates dir).
|
|
248
|
+
export function validateTarget(target, { forbid = [] } = {}) {
|
|
249
|
+
if (!target || typeof target !== 'string') throw new Error('Export needs a target directory.');
|
|
250
|
+
let abs = path.resolve(target);
|
|
251
|
+
if (!existsSync(abs) || !statSync(abs).isDirectory()) throw new Error(`Export target is not an existing directory: ${abs}`);
|
|
252
|
+
abs = realpathSync(abs);
|
|
253
|
+
const same = (dir) => path.relative(existsSync(dir) ? realpathSync(dir) : path.resolve(dir), abs) === '';
|
|
254
|
+
if (path.parse(abs).root === abs) throw new Error(`Refusing to export into a filesystem root: ${abs}`);
|
|
255
|
+
if (same(os.homedir())) throw new Error(`Refusing to export into the home directory: ${abs}. Pick a decisions folder inside a project.`);
|
|
256
|
+
for (const f of forbid) if (same(f)) throw new Error(`Refusing to export into ${abs}: roundtable keeps its own transcripts there.`);
|
|
257
|
+
return abs;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function recordPath(target, slug, opts) {
|
|
261
|
+
if (!/^[a-z0-9-]+$/.test(slug)) throw new Error(`Bad slug: ${slug}`);
|
|
262
|
+
const abs = validateTarget(target, opts);
|
|
263
|
+
const file = path.resolve(abs, `${slug}.md`);
|
|
264
|
+
if (path.dirname(file) !== abs) throw new Error('Refusing to write outside the target directory.');
|
|
265
|
+
return file;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Temp file in the same directory, then rename: a reader never sees half a file.
|
|
269
|
+
function writeAtomic(file, text, mode) {
|
|
270
|
+
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
271
|
+
const fd = openSync(tmp, 'wx', mode ?? 0o666);
|
|
272
|
+
try {
|
|
273
|
+
try {
|
|
274
|
+
writeFileSync(fd, text);
|
|
275
|
+
// Creation respects umask; an existing record/index keeps its exact access bits.
|
|
276
|
+
if (mode != null && process.platform !== 'win32') fchmodSync(fd, mode);
|
|
277
|
+
} finally { closeSync(fd); }
|
|
278
|
+
renameSync(tmp, file);
|
|
279
|
+
} finally { if (existsSync(tmp)) unlinkSync(tmp); }
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function regularOrAbsent(file) {
|
|
283
|
+
try {
|
|
284
|
+
const s = lstatSync(file);
|
|
285
|
+
if (!s.isFile() || s.isSymbolicLink()) throw new Error(`Refusing linked or non-file export destination: ${file}`);
|
|
286
|
+
return s.mode & 0o777;
|
|
287
|
+
} catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Every check runs before the first write, so a refusal leaves the directory untouched.
|
|
291
|
+
export function exportDebate(rows, slug, target, opts) {
|
|
292
|
+
const file = recordPath(target, slug, opts);
|
|
293
|
+
const mode = regularOrAbsent(file);
|
|
294
|
+
if (existsSync(file) && !ownsRecord(readFileSync(file, 'utf8'), slug)) throw new Error(`Refusing to replace ${file}: it was not written by roundtable for this debate.`);
|
|
295
|
+
const { markdown, meta } = decisionRecord(rows, slug, opts);
|
|
296
|
+
let indexPath = null, indexText = null, indexMode;
|
|
297
|
+
for (const name of ['README.md', 'DECISIONS.md']) {
|
|
298
|
+
const p = path.join(path.dirname(file), name);
|
|
299
|
+
const candidateMode = regularOrAbsent(p);
|
|
300
|
+
const next = updateIndex(existsSync(p) ? readFileSync(p, 'utf8') : null, meta);
|
|
301
|
+
if (next != null) { indexPath = p; indexText = next; indexMode = candidateMode; break; }
|
|
302
|
+
}
|
|
303
|
+
if (!indexPath) throw new Error(`Refusing to export into ${path.dirname(file)}: README.md and DECISIONS.md both exist and neither is a roundtable index.`);
|
|
304
|
+
writeAtomic(file, markdown, mode);
|
|
305
|
+
writeAtomic(indexPath, indexText, indexMode);
|
|
306
|
+
return { path: file, indexPath, meta };
|
|
307
|
+
}
|