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