@profullstack/board-saas 0.0.0-stage → 0.1.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/mail.js ADDED
@@ -0,0 +1,58 @@
1
+ // Transactional email through Resend. The fleet's pit.world key can only send from
2
+ // pit.world, so the address stays hello@pit.world and the name says who is writing.
3
+ // Every message carries the network cross-promo block (@profullstack/cross-promo).
4
+ import { promoBlock } from '@profullstack/cross-promo';
5
+
6
+ const FROM = 'Board as a Service <hello@pit.world>';
7
+ const SITE = 'board.saas.pit.world';
8
+
9
+ export function createMailer(env = process.env, fetchImpl = fetch) {
10
+ const key = env.RESEND_API_KEY;
11
+ if (!key) return null;
12
+ return async function send({ to, subject, text, html }) {
13
+ let promo = { text: '', html: '' };
14
+ try {
15
+ promo = await promoBlock({ site: SITE, audience: ['makers', 'developers'], seed: to });
16
+ } catch {
17
+ /* a mail never waits on the catalog */
18
+ }
19
+ const res = await fetchImpl('https://api.resend.com/emails', {
20
+ method: 'POST',
21
+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
22
+ body: JSON.stringify({
23
+ from: FROM,
24
+ to: [to],
25
+ subject,
26
+ text: promo.text ? `${text}\n\n${promo.text}` : text,
27
+ html: `${html}${promo.html ?? ''}`,
28
+ }),
29
+ signal: AbortSignal.timeout(15_000),
30
+ });
31
+ if (!res.ok) throw new Error(`resend ${res.status}: ${(await res.text()).slice(0, 300)}`);
32
+ };
33
+ }
34
+
35
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
36
+ const wrapHtml = (body) =>
37
+ `<div style="font:16px/1.5 system-ui,-apple-system,Segoe UI,sans-serif;color:#1d1d1b;max-width:560px">${body}</div>`;
38
+
39
+ export function codeEmail(code) {
40
+ return {
41
+ subject: `Your Board as a Service code: ${code}`,
42
+ text: `Your sign-in code is ${code}\n\nIt works for 15 minutes. If you did not ask for it, ignore this email.\n\nhttps://${SITE}`,
43
+ html: wrapHtml(
44
+ `<p>Your sign-in code:</p><p style="font-size:32px;font-weight:700;letter-spacing:6px;margin:8px 0">${esc(code)}</p><p>It works for 15 minutes. If you did not ask for it, ignore this email.</p><p><a href="https://${SITE}">${SITE}</a></p>`,
45
+ ),
46
+ };
47
+ }
48
+
49
+ export function meetingDoneEmail(meeting, url) {
50
+ const m = meeting;
51
+ return {
52
+ subject: `Board minutes: ${m.title}`,
53
+ text: `Your board met on "${m.brief.decision}".\n\nMajority: ${m.minutes.majority}\n\nChair's recommendation: ${m.minutes.recommendation}\n\nThe one question to answer: ${m.minutes.question}\n\nFull report: ${url}\n\nThe advisors are AI models, not real directors.`,
54
+ html: wrapHtml(
55
+ `<p>Your board met on <strong>${esc(m.brief.decision)}</strong>.</p><p><strong>Majority:</strong> ${esc(m.minutes.majority)}</p><p><strong>Chair's recommendation:</strong> ${esc(m.minutes.recommendation)}</p><p><strong>The one question to answer:</strong> ${esc(m.minutes.question)}</p><p><a href="${esc(url)}">Read the full report</a></p><p style="color:#5f5e5a;font-size:14px">The advisors are AI models, not real directors.</p>`,
56
+ ),
57
+ };
58
+ }
@@ -0,0 +1,24 @@
1
+ // MCP over stdio (newline-delimited JSON-RPC), proxying to the HTTP API with your key.
2
+ import { createInterface } from 'node:readline';
3
+ import { createMcpHandler } from './mcp.js';
4
+
5
+ export function serveStdio(client, { input = process.stdin, output = process.stdout } = {}) {
6
+ const handle = createMcpHandler({
7
+ runMeeting: (brief) => client.runMeeting(brief),
8
+ getMeeting: (id) => client.getMeeting(id),
9
+ });
10
+ const rl = createInterface({ input, crlfDelay: Infinity });
11
+ rl.on('line', async (line) => {
12
+ if (!line.trim()) return;
13
+ let msg;
14
+ try {
15
+ msg = JSON.parse(line);
16
+ } catch {
17
+ output.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } })}\n`);
18
+ return;
19
+ }
20
+ const out = await handle(msg);
21
+ if (out) output.write(`${JSON.stringify(out)}\n`);
22
+ });
23
+ return new Promise((resolve) => rl.on('close', resolve));
24
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,113 @@
1
+ // MCP (Model Context Protocol) over JSON-RPC 2.0, shared by the HTTP endpoint (/mcp,
2
+ // streamable HTTP, JSON responses) and the CLI's stdio bridge. Two tools: run_meeting and
3
+ // get_meeting. `impl` supplies them: the server calls its service, the CLI calls the API.
4
+ export const PROTOCOL_VERSION = '2025-06-18';
5
+
6
+ export const TOOLS = [
7
+ {
8
+ name: 'run_meeting',
9
+ description:
10
+ 'Convene the AI board (CFO, Growth Marketer, Operator, Founder-Time Strategist, Contrarian Investor, plus a chair) on a decision. Give a brief with the decision, the options and the constraints. Starts the meeting and returns its id, status and shareable URL; poll get_meeting until status is "done" (usually 2-6 minutes). First meeting per account is free, then $9 each via CoinPay: if status is "awaiting_payment", give the user checkout_url. If status is "needs_clarification", ask the user the listed questions once and call get_meeting after they answer on the meeting page or via the API. The advisors are AI models, not real directors.',
11
+ inputSchema: {
12
+ type: 'object',
13
+ properties: {
14
+ brief: { type: 'string', description: 'The decision, the options (at least two; "do nothing" counts) and the constraints (budget, time, team).' },
15
+ wait_seconds: { type: 'number', description: 'Optionally wait up to this many seconds (max 50) for the meeting to finish before returning.' },
16
+ },
17
+ required: ['brief'],
18
+ },
19
+ },
20
+ {
21
+ name: 'get_meeting',
22
+ description:
23
+ 'Read a board meeting by id: status (queued, checking, needs_clarification, awaiting_payment, running, done, failed), progress, and when done the full meeting (five verdicts, the debate, the chair\'s minutes with vote, clashes, strongest dissent, recommendation and the one open question) plus report_url and download_url.',
24
+ inputSchema: {
25
+ type: 'object',
26
+ properties: {
27
+ id: { type: 'string', description: 'The meeting id returned by run_meeting.' },
28
+ brief: { type: 'boolean', description: 'Return a short summary instead of the full meeting JSON. Default false.' },
29
+ },
30
+ required: ['id'],
31
+ },
32
+ },
33
+ ];
34
+
35
+ export function summarize(v) {
36
+ if (!v) return 'not found';
37
+ const lines = [`Meeting ${v.id}: ${v.status}`, `URL: ${v.url}`];
38
+ if (v.progress?.stage && v.status !== 'done') lines.push(`Progress: ${v.progress.stage}${v.progress.of ? ` ${v.progress.done}/${v.progress.of}` : ''}`);
39
+ if (v.checkout_url) lines.push(`Pay $${v.price_usd} to start it: ${v.checkout_url}`);
40
+ if (v.clarify) lines.push('The chair needs (asked once):', ...v.clarify.questions.map((q) => `- ${q.question}`));
41
+ if (v.error) lines.push(`Error: ${v.error}`);
42
+ if (v.meeting) {
43
+ const m = v.meeting.minutes;
44
+ lines.push('', `Majority: ${m.majority}`, '', 'Vote:', ...m.vote.map((x) => `- ${x.expert}: ${x.final}${x.changed ? ' (changed mind)' : ''}`), '', `Strongest dissent (${m.dissent.expert}): ${m.dissent.argument}`, '', `Recommendation: ${m.recommendation}`, '', `The one question: ${m.question}`, '', `Report: ${v.report_url}`, `Download: ${v.download_url}`);
45
+ }
46
+ return lines.join('\n');
47
+ }
48
+
49
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
50
+
51
+ /**
52
+ * impl = { runMeeting(brief) -> view, getMeeting(id) -> view }
53
+ * Returns a function(message) -> response | null (null for notifications).
54
+ */
55
+ export function createMcpHandler(impl, { name = 'board-saas', version = '0.1.0' } = {}) {
56
+ async function callTool(tool, args = {}) {
57
+ if (tool === 'run_meeting') {
58
+ let v = await impl.runMeeting(args.brief);
59
+ const until = Date.now() + Math.min(Number(args.wait_seconds) || 0, 50) * 1000;
60
+ while (until > Date.now() && ['queued', 'checking', 'running'].includes(v.status)) {
61
+ await sleep(3000);
62
+ v = await impl.getMeeting(v.id);
63
+ }
64
+ return { content: [{ type: 'text', text: summarize(v) }], structuredContent: strip(v) };
65
+ }
66
+ if (tool === 'get_meeting') {
67
+ const v = await impl.getMeeting(args.id);
68
+ return { content: [{ type: 'text', text: args.brief ? summarize(v) : `${summarize(v)}\n\n${JSON.stringify(v.meeting ?? {}, null, 1)}` }], structuredContent: strip(v) };
69
+ }
70
+ const e = new Error(`unknown tool: ${tool}`);
71
+ e.rpc = -32602;
72
+ throw e;
73
+ }
74
+
75
+ return async function handle(msg) {
76
+ const id = msg?.id;
77
+ const isNotification = id === undefined || id === null;
78
+ const ok = (result) => (isNotification ? null : { jsonrpc: '2.0', id, result });
79
+ const err = (code, message) => (isNotification ? null : { jsonrpc: '2.0', id, error: { code, message } });
80
+ if (!msg || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') return err(-32600, 'invalid request');
81
+ switch (msg.method) {
82
+ case 'initialize':
83
+ return ok({
84
+ protocolVersion: msg.params?.protocolVersion || PROTOCOL_VERSION,
85
+ capabilities: { tools: { listChanged: false } },
86
+ serverInfo: { name, version },
87
+ instructions: 'Board as a Service: run_meeting convenes five AI advisors and a chair on a decision brief; get_meeting reads the result. The advisors are AI models on the c0mpute network, not real directors.',
88
+ });
89
+ case 'notifications/initialized':
90
+ case 'notifications/cancelled':
91
+ return null;
92
+ case 'ping':
93
+ return ok({});
94
+ case 'tools/list':
95
+ return ok({ tools: TOOLS });
96
+ case 'tools/call':
97
+ try {
98
+ return ok(await callTool(msg.params?.name, msg.params?.arguments));
99
+ } catch (e) {
100
+ if (e.rpc) return err(e.rpc, e.message);
101
+ return ok({ content: [{ type: 'text', text: `Error: ${e.message}` }], isError: true });
102
+ }
103
+ default:
104
+ return err(-32601, `method not found: ${msg.method}`);
105
+ }
106
+ };
107
+ }
108
+
109
+ function strip(v) {
110
+ if (!v) return {};
111
+ const { meeting, ...rest } = v;
112
+ return meeting ? { ...rest, minutes: meeting.minutes, title: meeting.title } : rest;
113
+ }
package/src/meeting.js ADDED
@@ -0,0 +1,194 @@
1
+ // The meeting, exactly as the boardroom plugin's commands/meet.md runs it:
2
+ // 0. check the brief (decision, options, constraints); ask once at most
3
+ // 1. five independent verdicts in parallel (each sees only the brief)
4
+ // 2. debate in parallel (each reads all five named verdicts)
5
+ // 3. the chair's minutes (vote, clashes, strongest dissent, recommendation, one question)
6
+ // Output is meeting.json in the chair skill's shape, rendered by render-report.js.
7
+ import { EXPERTS, nameOf, persona } from './experts.js';
8
+ import { askJson } from './llm.js';
9
+ import { validateBriefCheck, validateDebate, validateMinutes, validateVerdict } from './validate.js';
10
+
11
+ export const MAX_BRIEF = 6000;
12
+
13
+ const JSON_ONLY = 'Reply with ONLY one JSON object. No prose before or after it, no code fences, no thinking out loud.';
14
+
15
+ function briefBlock(b) {
16
+ const lines = [`Decision: ${b.decision}`, 'Options:', ...b.options.map((o) => `- ${o}`), 'Constraints:', ...b.constraints.map((c) => `- ${c}`)];
17
+ if (b.assumptions?.length) lines.push('Assumptions (gaps in the brief, filled by the chair):', ...b.assumptions.map((a) => `- ${a}`));
18
+ lines.push('', `The founder's words: ${b.text}`);
19
+ return lines.join('\n');
20
+ }
21
+
22
+ /** Round 0: pull decision, options and constraints out of the brief and name what is missing. */
23
+ export async function checkBrief(model, text, { answers = null, log } = {}) {
24
+ const system = `${persona('chair')}\n\nRight now you are only checking the founder's brief before the meeting. ${JSON_ONLY}`;
25
+ const extra = answers ? `\n\nThe founder answered your clarifying questions:\n${answers}` : '';
26
+ const user = `Read this brief and pull out the three things a board meeting needs.
27
+ - decision: what is being decided, in one sentence
28
+ - options: at least two concrete choices ("do nothing" counts) - list what the founder named, do not invent new ones
29
+ - constraints: budget, time, team or any other hard limit the founder stated
30
+ Put in "missing" each of "decision", "options", "constraints" that the brief does not state.
31
+
32
+ <brief>
33
+ ${text}${extra}
34
+ </brief>
35
+
36
+ Reply with only this JSON: {"decision":"...","options":["...","..."],"constraints":["..."],"missing":[]}`;
37
+ const { value } = await askJson(model, { system, user, maxTokens: 700, validate: validateBriefCheck, log });
38
+ return value;
39
+ }
40
+
41
+ export function clarifyingQuestions(missing) {
42
+ const q = {
43
+ decision: 'What exactly are you deciding? One sentence.',
44
+ options: 'What are the options on the table? Name at least two ("do nothing" counts).',
45
+ constraints: 'What are the hard limits: budget, time, team, anything that cannot move?',
46
+ };
47
+ return missing.map((m) => ({ field: m, question: q[m] }));
48
+ }
49
+
50
+ export function assumptionsFor(missing) {
51
+ const a = {
52
+ decision: 'The decision was not stated outright; the board worked from its reading of the brief.',
53
+ options: 'Fewer than two options were given; the board weighed the stated path against doing nothing.',
54
+ constraints: 'No hard constraints were given; the board assumed a small business with limited cash and founder time.',
55
+ };
56
+ return missing.map((m) => a[m]);
57
+ }
58
+
59
+ export function round1Prompt(b, e) {
60
+ return `Board meeting, round 1. Give your independent verdict on this brief, using your own frameworks.
61
+
62
+ Brief:
63
+ ${briefBlock(b)}
64
+
65
+ Reply with only this JSON: {"expert":"${e.id}","call":"<your call in one sentence>","reasons":["<reason 1, naming its framework>","<reason 2>","<reason 3>"],"watch_out":"<the one thing you'd watch out for>"}`;
66
+ }
67
+
68
+ export function round2Prompt(b, e, verdicts) {
69
+ const vs = verdicts
70
+ .map((v) => `${nameOf(v.expert)} (${v.expert}): ${v.call} / reasons: ${v.reasons.join(' | ')} / watch out: ${v.watch_out}`)
71
+ .join('\n');
72
+ return `Board meeting, round 2. Here are all five verdicts, with names. Reply in character: who you agree with and why, who is wrong and why, and whether you have changed your mind.
73
+
74
+ Brief:
75
+ ${briefBlock(b)}
76
+
77
+ Verdicts:
78
+ ${vs}
79
+
80
+ Use these ids in "with": cfo, growth, operator, founder-time, contrarian. You are ${e.id}.
81
+ Reply with only this JSON: {"expert":"${e.id}","agrees":[{"with":"<id>","why":"..."}],"disagrees":[{"with":"<id>","why":"..."}],"changed_mind":false,"position":"<your final call in one sentence>","reply":"<2-4 sentences, in your voice>"}`;
82
+ }
83
+
84
+ export function round3Prompt(b, verdicts, debate) {
85
+ const rows = EXPERTS.map((e) => {
86
+ const v = verdicts.find((x) => x.expert === e.id);
87
+ const d = debate.find((x) => x.expert === e.id);
88
+ return `${e.name} (${e.id})
89
+ round 1 call: ${v.call}
90
+ reasons: ${v.reasons.join(' | ')}
91
+ watch out: ${v.watch_out}
92
+ round 2: ${d.reply}
93
+ agrees with: ${d.agrees.map((a) => `${a.with} (${a.why})`).join('; ') || 'nobody'}
94
+ disagrees with: ${d.disagrees.map((a) => `${a.with} (${a.why})`).join('; ') || 'nobody'}
95
+ changed mind: ${d.changed_mind ? 'yes' : 'no'}
96
+ final position: ${d.position}`;
97
+ }).join('\n\n');
98
+ return `Board meeting, round 3. Write the minutes as chair. You do not vote.
99
+
100
+ Brief:
101
+ ${briefBlock(b)}
102
+
103
+ What each member said:
104
+ ${rows}
105
+
106
+ Write:
107
+ - title: a short meeting title (under 60 characters)
108
+ - majority: the majority position after the debate, in one sentence
109
+ - clashes: 2 to 4 disagreements, each naming who was on each side ("sides") and the crux
110
+ - dissent: the strongest argument against the majority (most likely to be right, not loudest), with the member's id
111
+ - recommendation: your call in 2 to 4 sentences: what to do, at what commitment level, and the trigger for revisiting it. It must respect every hard constraint in the brief.
112
+ - question: the single question the founder still needs to answer before deciding, the one whose answer would most change the recommendation
113
+
114
+ Reply with only this JSON: {"title":"...","majority":"...","clashes":[{"topic":"...","sides":"...","crux":"..."}],"dissent":{"expert":"<id>","argument":"..."},"recommendation":"...","question":"..."}`;
115
+ }
116
+
117
+ /**
118
+ * Run rounds 1-3 on a checked brief. `brief` = {text, decision, options, constraints, assumptions}.
119
+ * `onProgress(stage, detail)` hears each step. Returns meeting.json.
120
+ */
121
+ export async function runMeeting(model, brief, { onProgress = () => {}, log = () => {}, date = new Date() } = {}) {
122
+ const system = (id) => `${persona(id)}\n\nYou are in a board meeting. ${JSON_ONLY}`;
123
+
124
+ onProgress('round1', { done: 0, of: EXPERTS.length });
125
+ let done = 0;
126
+ const verdicts = await Promise.all(
127
+ EXPERTS.map(async (e) => {
128
+ const { value } = await askJson(model, {
129
+ system: system(e.id),
130
+ user: round1Prompt(brief, e),
131
+ maxTokens: 700,
132
+ validate: (o) => validateVerdict(o, e.id),
133
+ log: (m) => log(`round 1 ${e.id}: ${m}`),
134
+ });
135
+ onProgress('round1', { done: ++done, of: EXPERTS.length, expert: e.id });
136
+ return value;
137
+ }),
138
+ );
139
+
140
+ onProgress('round2', { done: 0, of: EXPERTS.length });
141
+ done = 0;
142
+ const debate = await Promise.all(
143
+ EXPERTS.map(async (e) => {
144
+ const { value } = await askJson(model, {
145
+ system: system(e.id),
146
+ user: round2Prompt(brief, e, verdicts),
147
+ maxTokens: 800,
148
+ validate: (o) => validateDebate(o, e.id),
149
+ log: (m) => log(`round 2 ${e.id}: ${m}`),
150
+ });
151
+ onProgress('round2', { done: ++done, of: EXPERTS.length, expert: e.id });
152
+ return value;
153
+ }),
154
+ );
155
+
156
+ onProgress('round3', {});
157
+ const { value: m } = await askJson(model, {
158
+ system: `${persona('chair')}\n\n${JSON_ONLY}`,
159
+ user: round3Prompt(brief, verdicts, debate),
160
+ maxTokens: 1100,
161
+ validate: validateMinutes,
162
+ log: (msg) => log(`round 3 chair: ${msg}`),
163
+ });
164
+
165
+ // The vote table is built from what each member actually said, so the chair cannot misquote it.
166
+ const vote = EXPERTS.map((e) => {
167
+ const v = verdicts.find((x) => x.expert === e.id);
168
+ const d = debate.find((x) => x.expert === e.id);
169
+ return { expert: e.id, initial: v.call, final: d.position, changed: d.changed_mind };
170
+ });
171
+
172
+ return {
173
+ title: m.title || brief.decision.slice(0, 80),
174
+ date: date.toISOString().slice(0, 10),
175
+ brief: {
176
+ text: brief.text,
177
+ decision: brief.decision,
178
+ options: brief.options,
179
+ constraints: brief.constraints,
180
+ assumptions: brief.assumptions ?? [],
181
+ },
182
+ experts: EXPERTS,
183
+ verdicts,
184
+ debate,
185
+ minutes: {
186
+ vote,
187
+ majority: m.majority,
188
+ clashes: m.clashes,
189
+ dissent: m.dissent,
190
+ recommendation: m.recommendation,
191
+ question: m.question,
192
+ },
193
+ };
194
+ }
package/src/pages.js ADDED
@@ -0,0 +1,94 @@
1
+ // Server-rendered pages: the meeting status page (polls the API) and the report page.
2
+ import { allFooters } from './footers.js';
3
+ import { renderReport } from './render-report.js';
4
+
5
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
6
+
7
+ function topBar(id) {
8
+ return `<nav class="topbar" style="display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;justify-content:space-between;max-width:920px;margin:0 auto;padding:12px 16px;border-bottom:1px solid var(--line);font-size:.95rem">
9
+ <a href="/" style="font-weight:700;color:var(--ink);text-decoration:none">Board as a Service</a>
10
+ <span style="display:flex;gap:14px;flex-wrap:wrap"><a href="/api/v1/meetings/${esc(id)}/report.html" style="color:var(--accent)">Download report</a><a href="/api/v1/meetings/${esc(id)}/meeting.json" style="color:var(--accent)">meeting.json</a><a href="/" style="color:var(--accent)">Run your own meeting</a></span>
11
+ </nav>`;
12
+ }
13
+
14
+ const footerCss = '<style>.site-footer{max-width:920px;margin:0 auto;padding:16px;border-top:1px solid var(--line);color:var(--muted);font-size:.9rem}.site-footer a{color:var(--accent)}</style>';
15
+
16
+ export function reportPage(view) {
17
+ return renderReport(view.meeting, { topBar: topBar(view.id), footer: footerCss + allFooters() });
18
+ }
19
+
20
+ export function reportDownload(view) {
21
+ return renderReport(view.meeting);
22
+ }
23
+
24
+ export function statusPage(view) {
25
+ const brief = esc(view.brief_text);
26
+ return `<!doctype html>
27
+ <html lang="en">
28
+ <head>
29
+ <meta charset="utf-8">
30
+ <meta name="viewport" content="width=device-width, initial-scale=1">
31
+ <meta name="robots" content="noindex">
32
+ <title>Board meeting in progress</title>
33
+ <link rel="stylesheet" href="/style.css">
34
+ </head>
35
+ <body>
36
+ <main>
37
+ <p class="eyebrow"><a href="/" style="text-decoration:none">Board as a Service</a></p>
38
+ <h1 id="h">The board is meeting</h1>
39
+ <p class="honest">The advisors are AI models on the c0mpute peer network, not real directors.</p>
40
+ <section class="card">
41
+ <ol class="progress" id="steps">
42
+ <li data-s="checking">The chair checks your brief</li>
43
+ <li data-s="round1">Round 1: five independent verdicts <span id="r1"></span></li>
44
+ <li data-s="round2">Round 2: the debate <span id="r2"></span></li>
45
+ <li data-s="round3">Round 3: the chair writes the minutes</li>
46
+ </ol>
47
+ <p id="msg" class="status" role="status" aria-live="polite">Usually 2 to 6 minutes. This page updates by itself; you can close it and come back to this link, and we email you when the minutes are ready.</p>
48
+ <form id="clarify" hidden>
49
+ <p><strong>The chair needs a little more before the board can meet.</strong> This is asked once. Anything you leave blank becomes a written assumption.</p>
50
+ <div id="questions"></div>
51
+ <label for="answers">Your answers</label>
52
+ <textarea id="answers" rows="5" maxlength="3000"></textarea>
53
+ <button class="primary" type="submit">Send to the chair</button>
54
+ </form>
55
+ <p id="pay" hidden><a class="primary" id="paylink" href="#" style="display:inline-block;text-decoration:none">Pay $9 with CoinPay to start</a></p>
56
+ </section>
57
+ <h2>Your brief</h2>
58
+ <pre style="white-space:pre-wrap">${brief}</pre>
59
+ </main>
60
+ ${allFooters()}
61
+ <script>
62
+ (function(){
63
+ var id=${JSON.stringify(view.id)};
64
+ var order=['checking','round1','round2','round3','done'];
65
+ var msg=document.getElementById('msg'),h=document.getElementById('h'),cl=document.getElementById('clarify'),pay=document.getElementById('pay');
66
+ function key(){try{return localStorage.getItem('board-saas:key')}catch(e){return null}}
67
+ function show(v){
68
+ var stage=v.progress&&v.progress.stage||v.status;
69
+ if(v.status==='done'){location.reload();return true}
70
+ if(v.status==='failed'){h.textContent='The meeting could not finish';msg.textContent=v.error||'failed';msg.className='status bad';return true}
71
+ cl.hidden=v.status!=='needs_clarification';pay.hidden=v.status!=='awaiting_payment';
72
+ if(v.status==='awaiting_payment'){h.textContent='Waiting for payment';document.getElementById('paylink').href=v.checkout_url;msg.textContent='Your free meeting is used. Once CoinPay confirms the $9 payment, the board starts by itself.';}
73
+ if(v.status==='needs_clarification'&&v.clarify){h.textContent='One question from the chair';var q=document.getElementById('questions');q.innerHTML='';v.clarify.questions.forEach(function(x){var p=document.createElement('p');p.textContent='\\u2022 '+x.question;q.appendChild(p)});}
74
+ if(v.status==='queued'){msg.textContent='In the queue. The board starts as soon as a seat opens.';}
75
+ var i=order.indexOf(stage);
76
+ document.querySelectorAll('#steps li').forEach(function(li){var j=order.indexOf(li.getAttribute('data-s'));li.className=j<i?'done':(j===i?'now':'')});
77
+ if(v.progress&&v.progress.of){var el=document.getElementById(stage==='round1'?'r1':'r2');if(el)el.textContent='('+v.progress.done+'/'+v.progress.of+')';}
78
+ return v.status==='needs_clarification';
79
+ }
80
+ async function poll(){
81
+ try{var r=await fetch('/api/v1/meetings/'+id);var v=await r.json();if(show(v))return;}catch(e){}
82
+ setTimeout(poll,4000);
83
+ }
84
+ cl.addEventListener('submit',async function(ev){ev.preventDefault();
85
+ var headers={'content-type':'application/json'};var k=key();if(k)headers.authorization='Bearer '+k;
86
+ var r=await fetch('/api/v1/meetings/'+id+'/clarify',{method:'POST',headers:headers,body:JSON.stringify({answers:document.getElementById('answers').value})});
87
+ var v=await r.json();if(!r.ok){msg.textContent=v.error;msg.className='status bad';return}
88
+ cl.hidden=true;h.textContent='The board is meeting';msg.textContent='Thanks. The board is meeting now.';msg.className='status';poll();});
89
+ poll();
90
+ })();
91
+ </script>
92
+ </body>
93
+ </html>`;
94
+ }
@@ -0,0 +1,160 @@
1
+ // Render a boardroom meeting.json into one self-contained interactive HTML report.
2
+ // Ported from profullstack/boardroom scripts/render-report.mjs (same markup and styles),
3
+ // wrapped as a function, plus an honest "AI advisors" line and optional top bar / footer.
4
+ // renderReport(meeting, { topBar, footer }) -> html string
5
+ // node src/render-report.js meeting.json [report.html]
6
+ import { readFileSync, writeFileSync } from "node:fs";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ export function renderReport(m, { topBar = "", footer = "" } = {}) {
10
+ const esc = (s) =>
11
+ String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
12
+ const experts = m.experts ?? [];
13
+ const nameOf = (id) => experts.find((e) => e.id === id)?.name ?? id;
14
+ const list = (items) => (items?.length ? `<ul>${items.map((i) => `<li>${esc(i)}</li>`).join("")}</ul>` : "");
15
+
16
+ const verdictTabs = experts
17
+ .map((e, i) => `<button role="tab" id="tab-${esc(e.id)}" aria-controls="panel-${esc(e.id)}" aria-selected="${i === 0}" tabindex="${i === 0 ? 0 : -1}">${esc(e.name)}</button>`)
18
+ .join("");
19
+ const verdictPanels = experts
20
+ .map((e, i) => {
21
+ const v = (m.verdicts ?? []).find((x) => x.expert === e.id) ?? {};
22
+ return `<section role="tabpanel" id="panel-${esc(e.id)}" aria-labelledby="tab-${esc(e.id)}" ${i === 0 ? "" : "hidden"}>
23
+ <p class="lens">${esc(e.lens)}</p>
24
+ <h3 class="call">${esc(v.call)}</h3>
25
+ <ol class="reasons">${(v.reasons ?? []).map((r) => `<li>${esc(r)}</li>`).join("")}</ol>
26
+ <div class="watch"><strong>Watch out for</strong><p>${esc(v.watch_out)}</p></div>
27
+ </section>`;
28
+ })
29
+ .join("");
30
+
31
+ const rel = (arr, cls, label) =>
32
+ arr?.length
33
+ ? `<div class="rel ${cls}"><span class="tag">${label}</span>${arr
34
+ .map((a) => `<p><strong>${esc(nameOf(a.with))}</strong>: ${esc(a.why)}</p>`)
35
+ .join("")}</div>`
36
+ : "";
37
+ const debateCards = (m.debate ?? [])
38
+ .map(
39
+ (d) => `<article class="card">
40
+ <header><h3>${esc(nameOf(d.expert))}</h3><span class="badge ${d.changed_mind ? "changed" : "held"}">${d.changed_mind ? "Changed mind" : "Held position"}</span></header>
41
+ <blockquote>${esc(d.reply)}</blockquote>
42
+ ${rel(d.agrees, "agree", "Agrees with")}
43
+ ${rel(d.disagrees, "disagree", "Disagrees with")}
44
+ <p class="final"><strong>Final position:</strong> ${esc(d.position)}</p>
45
+ </article>`
46
+ )
47
+ .join("");
48
+
49
+ const mn = m.minutes ?? {};
50
+ const voteRows = (mn.vote ?? [])
51
+ .map((v) => `<tr><td>${esc(nameOf(v.expert))}</td><td>${esc(v.initial)}</td><td>${esc(v.final)}</td><td>${v.changed ? "Yes" : "No"}</td></tr>`)
52
+ .join("");
53
+ const clashes = (mn.clashes ?? [])
54
+ .map((c) => `<li><strong>${esc(c.topic)}</strong>: ${esc(c.sides)}. <em>Crux:</em> ${esc(c.crux)}</li>`)
55
+ .join("");
56
+
57
+ const b = m.brief ?? {};
58
+ const html = `<!doctype html>
59
+ <html lang="en">
60
+ <head>
61
+ <meta charset="utf-8">
62
+ <meta name="viewport" content="width=device-width, initial-scale=1">
63
+ <title>${esc(m.title || "Board meeting")}</title>
64
+ <style>
65
+ :root{--bg:#f7f6f3;--surface:#fff;--ink:#1d1d1b;--muted:#5f5e5a;--line:#e3e1db;--accent:#2f5bd3;--agree:#1f7a4d;--disagree:#b3412e;--warn:#fbf3e2;--warn-line:#e7c77a}
66
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#141413;--surface:#1f1f1d;--ink:#ecebe6;--muted:#a3a29c;--line:#34332f;--accent:#8aa8ff;--agree:#6cc79a;--disagree:#f08a76;--warn:#2b2516;--warn-line:#7a6430}}
67
+ :root[data-theme="dark"]{--bg:#141413;--surface:#1f1f1d;--ink:#ecebe6;--muted:#a3a29c;--line:#34332f;--accent:#8aa8ff;--agree:#6cc79a;--disagree:#f08a76;--warn:#2b2516;--warn-line:#7a6430}
68
+ *{box-sizing:border-box}
69
+ body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}
70
+ main{max-width:920px;margin:0 auto;padding:32px 16px 64px}
71
+ h1{font-size:1.9rem;line-height:1.2;margin:0 0 4px}
72
+ h2{font-size:1.25rem;margin:40px 0 12px;padding-top:8px;border-top:1px solid var(--line)}
73
+ .meta{color:var(--muted);margin:0 0 20px}
74
+ .brief{background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:16px 20px}
75
+ .brief dt{font-weight:600;margin-top:8px}.brief dd{margin:2px 0 0}.brief ul{margin:4px 0;padding-left:20px}
76
+ [role=tablist]{display:flex;gap:4px;overflow-x:auto;border-bottom:1px solid var(--line)}
77
+ [role=tab]{font:inherit;background:none;border:0;border-bottom:3px solid transparent;color:var(--muted);padding:10px 14px;cursor:pointer;white-space:nowrap}
78
+ [role=tab][aria-selected=true]{color:var(--ink);border-bottom-color:var(--accent);font-weight:600}
79
+ [role=tab]:focus-visible,button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
80
+ [role=tabpanel]{background:var(--surface);border:1px solid var(--line);border-top:0;border-radius:0 0 12px 12px;padding:20px}
81
+ .lens{color:var(--muted);margin:0;font-size:.9rem}
82
+ .call{font-size:1.15rem;margin:6px 0 12px}
83
+ .reasons li{margin-bottom:8px}
84
+ .watch{background:var(--warn);border:1px solid var(--warn-line);border-radius:10px;padding:10px 14px}.watch p{margin:4px 0 0}
85
+ .cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,400px),1fr));gap:14px}
86
+ .card{background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:16px 18px}
87
+ .card header{display:flex;justify-content:space-between;align-items:center;gap:8px}.card h3{margin:0;font-size:1.05rem}
88
+ .badge{font-size:.75rem;border-radius:999px;padding:2px 10px;border:1px solid var(--line);color:var(--muted);white-space:nowrap}
89
+ .badge.changed{color:var(--accent);border-color:var(--accent)}
90
+ blockquote{margin:12px 0;padding-left:12px;border-left:3px solid var(--line);font-style:italic}
91
+ .rel{margin:8px 0}.rel p{margin:4px 0}.tag{font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;font-weight:700}
92
+ .agree .tag{color:var(--agree)}.disagree .tag{color:var(--disagree)}
93
+ .final{margin:10px 0 0;padding-top:10px;border-top:1px solid var(--line)}
94
+ table{width:100%;border-collapse:collapse;background:var(--surface);border:1px solid var(--line);border-radius:12px;overflow:hidden;font-size:.95rem}
95
+ th,td{text-align:left;padding:10px 12px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--muted);font-weight:600}
96
+ .tablewrap{overflow-x:auto}
97
+ .rec{background:var(--surface);border:2px solid var(--accent);border-radius:12px;padding:16px 20px}
98
+ .rec p{margin:0 0 12px;font-size:1.05rem}
99
+ .copy{font:inherit;background:var(--accent);color:var(--bg);border:0;border-radius:8px;padding:8px 16px;cursor:pointer;font-weight:600}
100
+ .ai-note{color:var(--muted);font-size:.9rem;margin:-12px 0 20px}
101
+ .question{background:var(--warn);border:1px solid var(--warn-line);border-radius:12px;padding:14px 18px;font-size:1.05rem}
102
+ </style>
103
+ </head>
104
+ <body>
105
+ ${topBar}
106
+ <main>
107
+ <h1>${esc(m.title || "Board meeting")}</h1>
108
+ <p class="meta">Board meeting · ${esc(m.date)} · ${experts.length} members · chaired</p>\n<p class="ai-note">These advisors are AI models on the c0mpute network, not real directors. Treat this as a structured second opinion, not professional advice.</p>
109
+
110
+ <div class="brief"><dl>
111
+ <dt>Decision</dt><dd>${esc(b.decision)}</dd>
112
+ <dt>Options</dt><dd>${list(b.options)}</dd>
113
+ <dt>Constraints</dt><dd>${list(b.constraints)}</dd>
114
+ ${b.assumptions?.length ? `<dt>Assumptions the board worked from</dt><dd>${list(b.assumptions)}</dd>` : ""}
115
+ </dl></div>
116
+
117
+ <h2>Round 1: independent verdicts</h2>
118
+ <div role="tablist" aria-label="Expert verdicts">${verdictTabs}</div>
119
+ ${verdictPanels}
120
+
121
+ <h2>Round 2: debate</h2>
122
+ <div class="cards">${debateCards}</div>
123
+
124
+ <h2>Round 3: minutes</h2>
125
+ <h3>The vote</h3>
126
+ <p>${esc(mn.majority)}</p>
127
+ <div class="tablewrap"><table><thead><tr><th>Member</th><th>Round 1 call</th><th>Final call</th><th>Changed</th></tr></thead><tbody>${voteRows}</tbody></table></div>
128
+ <h3>Where they clashed</h3>
129
+ <ul>${clashes}</ul>
130
+ <h3>Strongest dissent</h3>
131
+ <p><strong>${esc(nameOf(mn.dissent?.expert))}</strong>: ${esc(mn.dissent?.argument)}</p>
132
+ <h3>Chair's recommendation</h3>
133
+ <div class="rec"><p id="rec">${esc(mn.recommendation)}</p><button class="copy" id="copy" type="button">Copy recommendation</button></div>
134
+ <h3>The one question to answer before you decide</h3>
135
+ <p class="question">${esc(mn.question)}</p>
136
+ </main>
137
+ ${footer}
138
+ <script>
139
+ const tabs=[...document.querySelectorAll('[role=tab]')];
140
+ function select(t){tabs.forEach(x=>{const on=x===t;x.setAttribute('aria-selected',on);x.tabIndex=on?0:-1;document.getElementById(x.getAttribute('aria-controls')).hidden=!on});t.focus()}
141
+ tabs.forEach((t,i)=>{t.addEventListener('click',()=>select(t));t.addEventListener('keydown',e=>{if(e.key==='ArrowRight')select(tabs[(i+1)%tabs.length]);if(e.key==='ArrowLeft')select(tabs[(i-1+tabs.length)%tabs.length])})});
142
+ document.getElementById('copy').addEventListener('click',async e=>{const text=document.getElementById('rec').textContent;const b=e.currentTarget;
143
+ try{await navigator.clipboard.writeText(text)}catch{const r=document.createRange();r.selectNodeContents(document.getElementById('rec'));const s=getSelection();s.removeAllRanges();s.addRange(r);document.execCommand('copy');s.removeAllRanges()}
144
+ b.textContent='Copied';setTimeout(()=>b.textContent='Copy recommendation',1800)});
145
+ </script>
146
+ </body>
147
+ </html>
148
+ `;
149
+ return html;
150
+ }
151
+
152
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
153
+ const [, , inPath, outPath = "report.html"] = process.argv;
154
+ if (!inPath) {
155
+ console.error("usage: render-report.js meeting.json [report.html]");
156
+ process.exit(2);
157
+ }
158
+ writeFileSync(outPath, renderReport(JSON.parse(readFileSync(inPath, "utf8"))));
159
+ console.log(`wrote ${outPath}`);
160
+ }