@mindbricks/genesis-set 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,267 @@
1
+ // What the project board shows (#9386), read from the project folder each time:
2
+ // the design flow from the mind-set pipeline, the documents under design/, the
3
+ // interview record, the blueprint and its validation, the keys (masked) and the
4
+ // next step. Nothing here writes; the keys come from the key store.
5
+ //
6
+ // The design pipeline and the schema are read from the installed mind-set
7
+ // corpus (MIND_SET_HOME or ~/.mind-set/current). design-check and validate are
8
+ // mind-set's own code, loaded from the mind-set package that genesis install
9
+ // recorded (or that sits next to this package); without it the board says the
10
+ // checks are unavailable instead of guessing.
11
+
12
+ import fs from 'node:fs';
13
+ import { createRequire } from 'node:module';
14
+ import path from 'node:path';
15
+ import { fileURLToPath, pathToFileURL } from 'node:url';
16
+
17
+ import { dataDirOf } from './config.mjs';
18
+ import { listKeys } from './key-store.mjs';
19
+
20
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
21
+
22
+ export function mindSetCorpusDir(env = process.env) {
23
+ if (env.MIND_SET_HOME) return path.join(path.resolve(env.MIND_SET_HOME), 'current');
24
+ const home = env.HOME || env.USERPROFILE || '';
25
+ return path.join(home, '.mind-set', 'current');
26
+ }
27
+
28
+ function readJson(file) {
29
+ try {
30
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ function readText(file) {
37
+ try {
38
+ return fs.readFileSync(file, 'utf8');
39
+ } catch {
40
+ return null;
41
+ }
42
+ }
43
+
44
+ /** The mind-set package folder: the env override, the one genesis install recorded, or the one next to this package. */
45
+ export function mindSetPackageDir(env = process.env) {
46
+ const candidates = [];
47
+ if (env.GENESIS_SET_MIND_SET_PACKAGE) candidates.push(path.resolve(env.GENESIS_SET_MIND_SET_PACKAGE));
48
+ const installed = readJson(path.join(dataDirOf(env), 'installed.json'));
49
+ if (installed && typeof installed.mindSetPackage === 'string') candidates.push(installed.mindSetPackage);
50
+ try {
51
+ const req = createRequire(path.join(HERE, '..', 'package.json'));
52
+ candidates.push(path.dirname(req.resolve('@mindbricks/mind-set/package.json')));
53
+ } catch {
54
+ // not next to this package (the standalone server copy)
55
+ }
56
+ return candidates.find((d) => fs.existsSync(path.join(d, 'lib', 'design-check.mjs'))) ?? null;
57
+ }
58
+
59
+ const libCache = new Map();
60
+ async function mindSetLib(env, name) {
61
+ const dir = mindSetPackageDir(env);
62
+ if (!dir) return null;
63
+ const file = path.join(dir, 'lib', name);
64
+ if (!libCache.has(file)) libCache.set(file, import(pathToFileURL(file).href).catch(() => null));
65
+ return libCache.get(file);
66
+ }
67
+
68
+ /** The design documents present: docName -> { file, size, mtime }. */
69
+ function designFiles(root) {
70
+ const dir = path.join(root, 'design');
71
+ const out = new Map();
72
+ let names = [];
73
+ try {
74
+ names = fs.readdirSync(dir);
75
+ } catch {
76
+ return out;
77
+ }
78
+ for (const n of names) {
79
+ if (!n.endsWith('.md') || n === 'README.md') continue;
80
+ const file = path.join(dir, n);
81
+ const st = fs.statSync(file);
82
+ if (st.isFile()) out.set(n.slice(0, -3), { file, size: st.size, mtime: st.mtime.toISOString() });
83
+ }
84
+ return out;
85
+ }
86
+
87
+ const STAGE_LABEL = {
88
+ source: 'Interview',
89
+ requirement: 'Requirements',
90
+ spec: 'Specification',
91
+ test: 'Test',
92
+ };
93
+
94
+ /** The interview record: its status, the OPEN items and the Coverage Ledger rows. */
95
+ export function interviewSummary(text) {
96
+ if (text === null) return null;
97
+ const lines = text.replace(/\r\n?/g, '\n').split('\n');
98
+ let status = null;
99
+ for (let i = 0; i < lines.length; i++) {
100
+ const m = lines[i].match(/^##\s+Status\s*:?\s*(.*)$/i);
101
+ if (m) {
102
+ status = (m[1] || lines.slice(i + 1).find((l) => l.trim()) || '').trim().replace(/[`*_]/g, '').toLowerCase() || null;
103
+ break;
104
+ }
105
+ }
106
+ const open = lines.filter((l) => /\bOPEN\b/.test(l) && !/^#/.test(l)).map((l) => l.replace(/^\s*[-*|]\s*/, '').trim()).slice(0, 50);
107
+ const ledger = [];
108
+ let inLedger = false;
109
+ for (const l of lines) {
110
+ if (/^##\s/.test(l)) inLedger = /coverage ledger/i.test(l);
111
+ else if (inLedger && /^\s*\|/.test(l) && !/^\s*\|?\s*:?-{2,}/.test(l)) {
112
+ const cells = l.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
113
+ ledger.push(cells);
114
+ }
115
+ }
116
+ return { status, open, ledger };
117
+ }
118
+
119
+ /** The blueprint at the project root: a summary, or the parse error. */
120
+ export function blueprintSummary(root) {
121
+ const file = path.join(root, 'blueprint.json');
122
+ const text = readText(file);
123
+ if (text === null) return null;
124
+ let bp;
125
+ try {
126
+ bp = JSON.parse(text);
127
+ } catch (e) {
128
+ return { file, error: `not valid JSON: ${e.message}` };
129
+ }
130
+ const services = Array.isArray(bp.services) ? bp.services : [];
131
+ return {
132
+ file,
133
+ name: bp?.projectSettings?.basicSettings?.name ?? null,
134
+ services: services.map((s) => ({
135
+ name: s?.serviceSettings?.serviceBasics?.name ?? '(unnamed)',
136
+ dataObjects: Array.isArray(s?.dataObjects) ? s.dataObjects.length : 0,
137
+ businessApis: Array.isArray(s?.businessLogic) ? s.businessLogic.length : Array.isArray(s?.businessApis) ? s.businessApis.length : 0,
138
+ })),
139
+ raw: bp,
140
+ };
141
+ }
142
+
143
+ async function validation(env, bp) {
144
+ if (!bp || bp.error) return null;
145
+ const lib = await mindSetLib(env, 'validate.mjs');
146
+ const schemaText = readText(path.join(mindSetCorpusDir(env), 'openappl.json'));
147
+ if (!lib || !schemaText) return { available: false };
148
+ try {
149
+ const { errors, warnings } = lib.validateBlueprint(lib.loadSchema(JSON.parse(schemaText)), bp.raw);
150
+ return {
151
+ available: true,
152
+ errors: errors.length,
153
+ warnings: warnings.length,
154
+ first: errors.slice(0, 10).map((p) => lib.formatProblem(p)),
155
+ };
156
+ } catch (e) {
157
+ return { available: false, error: e.message };
158
+ }
159
+ }
160
+
161
+ /** The flow: every pipeline document with its state, plus the fan-out specs found. */
162
+ async function flow(env, root, pipeline, files) {
163
+ if (!pipeline) return { available: false, docs: [] };
164
+ const dc = await mindSetLib(env, 'design-check.mjs');
165
+ let roster = null;
166
+ const fan = pipeline.docs.find((d) => d.fanOut);
167
+ const prefix = fan?.fanOut?.docNamePrefix ?? 'service-spec-';
168
+ if (dc && fan?.fanOut?.roster && files.has(fan.fanOut.roster)) {
169
+ try {
170
+ roster = dc.rosterNamesOf(pipeline, readText(files.get(fan.fanOut.roster).file));
171
+ } catch {
172
+ roster = null;
173
+ }
174
+ }
175
+ const check = (docName, file) => {
176
+ if (!dc) return null;
177
+ try {
178
+ const r = dc.checkDesignDraft(pipeline, docName, readText(file) ?? '', roster ? { rosterNames: roster } : {});
179
+ return { ok: r.ok, findings: (r.findings ?? []).map((f) => f.message ?? f.code).slice(0, 10) };
180
+ } catch (e) {
181
+ return { ok: false, findings: [e.message] };
182
+ }
183
+ };
184
+ const docs = [];
185
+ for (const d of pipeline.docs) {
186
+ if (d.fanOut) {
187
+ const names = roster ? roster.map((n) => `${prefix}${dc.serviceRosterKey(n)}`) : [...files.keys()].filter((n) => n.startsWith(prefix));
188
+ const extra = [...files.keys()].filter((n) => n.startsWith(prefix) && !names.includes(n));
189
+ for (const docName of [...names, ...extra]) {
190
+ const f = files.get(docName);
191
+ docs.push({ docName, stage: d.stage, class: d.class, label: STAGE_LABEL[d.class] ?? d.class, fanOut: true, conditional: false, written: Boolean(f), mtime: f?.mtime ?? null, check: f ? check(docName, f.file) : null });
192
+ }
193
+ if (names.length === 0 && extra.length === 0) {
194
+ docs.push({ docName: `${prefix}<service>`, stage: d.stage, class: d.class, label: STAGE_LABEL[d.class] ?? d.class, fanOut: true, conditional: false, written: false, placeholder: true, mtime: null, check: null });
195
+ }
196
+ continue;
197
+ }
198
+ const f = files.get(d.docName);
199
+ docs.push({
200
+ docName: d.docName,
201
+ stage: d.stage,
202
+ class: d.class,
203
+ label: STAGE_LABEL[d.class] ?? d.class,
204
+ conditional: Boolean(d.when),
205
+ written: Boolean(f),
206
+ mtime: f?.mtime ?? null,
207
+ check: f ? check(d.docName, f.file) : null,
208
+ });
209
+ }
210
+ const known = new Set(docs.map((d) => d.docName));
211
+ const other = [...files.keys()].filter((n) => !known.has(n)).sort();
212
+ return { available: true, checksAvailable: Boolean(dc), docs, other };
213
+ }
214
+
215
+ function nextStep(state) {
216
+ const { flow: f, interview, blueprint, validation: v } = state;
217
+ if (!f.available) return 'Install mind-set ("genesis install") so the board can show the design flow.';
218
+ const byName = new Map(f.docs.map((d) => [d.docName, d]));
219
+ const ir = byName.get('interview-record');
220
+ if (!ir?.written) return 'Start the requirements interview: ask the agent to design the application.';
221
+ if (interview?.status && !/closed/.test(interview.status)) return 'Finish the requirements interview (the record is not closed yet).';
222
+ const failing = f.docs.find((d) => d.written && d.check && !d.check.ok);
223
+ if (failing) return `Fix ${failing.docName}: its design-check has findings.`;
224
+ const missing = f.docs.find((d) => !d.written && !d.conditional && d.class !== 'test');
225
+ if (missing) return `Next document: ${missing.placeholder ? 'the service specs (one per service)' : missing.docName}.`;
226
+ if (!blueprint) return 'Write the blueprint (blueprint.json) from the design documents.';
227
+ if (blueprint.error) return `Fix blueprint.json: ${blueprint.error}.`;
228
+ if (v?.available && v.errors > 0) return `Fix the ${v.errors} validation error(s) of the blueprint.`;
229
+ return 'Compile the blueprint with Genesis, one service at a time.';
230
+ }
231
+
232
+ /** The whole board state of a project (or, without one, only the global keys). */
233
+ export async function boardState({ env = process.env, project }) {
234
+ const keys = listKeys(env, { project }).map(({ name, label, description, builtin, scope, status, source, masked, updatedAt }) => ({
235
+ name,
236
+ label,
237
+ description,
238
+ builtin,
239
+ scope,
240
+ status,
241
+ ...(source ? { source } : {}),
242
+ masked,
243
+ updatedAt,
244
+ }));
245
+ if (!project) return { project: null, keys };
246
+ const files = designFiles(project.root);
247
+ const pipeline = readJson(path.join(mindSetCorpusDir(env), 'procedures', 'design', 'pipeline.json'));
248
+ const bp = blueprintSummary(project.root);
249
+ const state = {
250
+ project: { id: project.id, name: project.name, root: project.root },
251
+ flow: await flow(env, project.root, pipeline, files),
252
+ interview: interviewSummary(files.has('interview-record') ? readText(files.get('interview-record').file) : null),
253
+ blueprint: bp ? { file: bp.file, name: bp.name ?? null, services: bp.services ?? [], error: bp.error ?? null } : null,
254
+ validation: await validation(env, bp),
255
+ keys,
256
+ };
257
+ state.next = nextStep(state);
258
+ return state;
259
+ }
260
+
261
+ /** One design document's text, by name; null for a name that is not a document of this project. */
262
+ export function designDoc(project, docName) {
263
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(docName)) return null;
264
+ const file = path.join(project.root, 'design', `${docName}.md`);
265
+ if (path.dirname(file) !== path.join(project.root, 'design')) return null;
266
+ return readText(file);
267
+ }
@@ -0,0 +1,329 @@
1
+ // The HTML of the project board (#9386), served by ./board.mjs. One
2
+ // self-contained document: no external script, style, font or image (the CSP
3
+ // allows only its nonce'd script and style and requests to itself). Store and
4
+ // document text reaches the page as text (textContent) or as the server's
5
+ // escaped Markdown rendering (board-md.mjs); nothing else is inserted as HTML.
6
+
7
+ const STYLE = `
8
+ :root {
9
+ --bg: #f6f7f9; --panel: #ffffff; --text: #16181d; --muted: #5c6370; --line: #e2e5ea; --soft: #f0f2f5;
10
+ --accent: #3b5bdb; --accent-text: #ffffff; --ok: #1f7a4d; --ok-bg: #e6f4ec; --warn: #8a5a00; --warn-bg: #fdf3dc;
11
+ --bad: #b42318; --bad-bg: #fdecea; --field: #ffffff; --focus: rgba(59, 91, 219, .35);
12
+ }
13
+ @media (prefers-color-scheme: dark) {
14
+ :root {
15
+ --bg: #111317; --panel: #1a1d23; --text: #e7e9ee; --muted: #9aa1ad; --line: #2b2f37; --soft: #20242b;
16
+ --accent: #7d97ff; --accent-text: #0d1020; --ok: #6fd3a0; --ok-bg: #16301f; --warn: #f0c060; --warn-bg: #33280f;
17
+ --bad: #ff8a7a; --bad-bg: #3a1714; --field: #14161a; --focus: rgba(125, 151, 255, .35);
18
+ }
19
+ }
20
+ * { box-sizing: border-box; }
21
+ body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
22
+ header { background: var(--panel); border-bottom: 1px solid var(--line); position: sticky; top: 0; z-index: 3; }
23
+ .bar { max-width: 1100px; margin: 0 auto; padding: 14px 16px 0; }
24
+ .title { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
25
+ h1 { font-size: 19px; margin: 0; }
26
+ .sub { color: var(--muted); font-size: 13px; overflow-wrap: anywhere; }
27
+ nav { display: flex; gap: 4px; margin-top: 10px; overflow-x: auto; }
28
+ nav a { padding: 8px 12px; color: var(--muted); text-decoration: none; border-bottom: 2px solid transparent; font-weight: 600; white-space: nowrap; }
29
+ nav a.on { color: var(--text); border-bottom-color: var(--accent); }
30
+ main { max-width: 1100px; margin: 0 auto; padding: 20px 16px 64px; }
31
+ .card { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px 18px; margin: 0 0 14px; }
32
+ .next { border-left: 4px solid var(--accent); }
33
+ .next b { display: block; font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; margin-bottom: 2px; }
34
+ h2 { font-size: 16px; margin: 0 0 10px; }
35
+ .muted { color: var(--muted); }
36
+ .small { font-size: 13px; }
37
+ .stage { margin: 0 0 16px; }
38
+ .stage h3 { font-size: 13px; color: var(--muted); margin: 0 0 6px; text-transform: uppercase; letter-spacing: .04em; }
39
+ .row { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; flex-wrap: wrap; }
40
+ .row + .row { border-top: 1px solid var(--line); }
41
+ .row.link { cursor: pointer; }
42
+ .row.link:hover { background: var(--soft); }
43
+ .doc { font: 13.5px ui-monospace, SFMono-Regular, Menlo, monospace; }
44
+ .chip { font-size: 12px; font-weight: 600; border-radius: 999px; padding: 1px 9px; white-space: nowrap; }
45
+ .chip.ok { color: var(--ok); background: var(--ok-bg); }
46
+ .chip.warn { color: var(--warn); background: var(--warn-bg); }
47
+ .chip.bad { color: var(--bad); background: var(--bad-bg); }
48
+ .chip.idle { color: var(--muted); background: var(--soft); }
49
+ .grow { flex: 1 1 auto; }
50
+ .split { display: grid; grid-template-columns: 260px 1fr; gap: 14px; align-items: start; }
51
+ @media (max-width: 760px) { .split { grid-template-columns: 1fr; } }
52
+ .list .row { padding: 6px 10px; }
53
+ .list .row.on { background: var(--soft); font-weight: 600; }
54
+ .md h2, .md h3, .md h4 { margin: 18px 0 8px; } .md h2 { font-size: 18px; } .md h3 { font-size: 16px; } .md h4, .md h5, .md h6 { font-size: 14px; }
55
+ .md p { margin: 8px 0; } .md ul, .md ol { padding-left: 22px; } .md li.d1 { margin-left: 18px; } .md li.d2 { margin-left: 36px; } .md li.d3, .md li.d4 { margin-left: 54px; }
56
+ .md pre { background: var(--soft); padding: 10px 12px; border-radius: 8px; overflow-x: auto; font-size: 13px; }
57
+ .md code { font: 13px ui-monospace, SFMono-Regular, Menlo, monospace; background: var(--soft); padding: 1px 4px; border-radius: 4px; }
58
+ .md pre code { background: none; padding: 0; }
59
+ .md blockquote { margin: 8px 0; padding: 4px 12px; border-left: 3px solid var(--line); color: var(--muted); }
60
+ .md a { color: var(--accent); }
61
+ .table { overflow-x: auto; }
62
+ table { border-collapse: collapse; width: 100%; font-size: 14px; }
63
+ th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; }
64
+ th { color: var(--muted); font-weight: 600; }
65
+ .kgroup h2 { margin-top: 6px; }
66
+ .kcard { border-top: 1px solid var(--line); padding: 12px 0; }
67
+ .kcard:first-of-type { border-top: none; }
68
+ .khead { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
69
+ .khead code { font-size: 12.5px; color: var(--muted); }
70
+ .khead .chip { margin-left: auto; }
71
+ .fields { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
72
+ input, textarea, select { flex: 1 1 200px; min-width: 0; font: inherit; color: var(--text); background: var(--field); border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; }
73
+ textarea { min-height: 60px; resize: vertical; }
74
+ input:focus, textarea:focus, select:focus, button:focus-visible { outline: 3px solid var(--focus); outline-offset: 1px; }
75
+ .field { position: relative; flex: 1 1 220px; min-width: 0; display: flex; }
76
+ .field input { flex: 1 1 auto; padding-right: 64px; }
77
+ .peek { position: absolute; right: 4px; top: 50%; transform: translateY(-50%); padding: 3px 9px; font-size: 13px; border: none; background: transparent; color: var(--muted); }
78
+ button { font: inherit; font-weight: 600; border-radius: 8px; padding: 8px 14px; border: 1px solid var(--line); background: var(--panel); color: var(--text); cursor: pointer; }
79
+ button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
80
+ button:disabled, input:disabled { opacity: .55; cursor: default; }
81
+ .links { display: flex; gap: 14px; margin-top: 8px; }
82
+ .links button { background: none; border: none; padding: 0; color: var(--muted); font-weight: 500; text-decoration: underline; }
83
+ .links button.danger { color: var(--bad); }
84
+ .note { font-size: 13px; color: var(--warn); margin: 6px 0 0; }
85
+ #flash { position: fixed; bottom: 16px; left: 50%; transform: translateX(-50%); display: none; padding: 10px 16px; border-radius: 8px; font-weight: 600; z-index: 5; }
86
+ #flash.ok { display: block; color: var(--ok); background: var(--ok-bg); }
87
+ #flash.err { display: block; color: var(--bad); background: var(--bad-bg); }
88
+ footer { color: var(--muted); font-size: 13px; margin-top: 24px; }
89
+ `;
90
+
91
+ const SCRIPT = `
92
+ (() => {
93
+ const main = document.getElementById('main');
94
+ const flash = document.getElementById('flash');
95
+ const TABS = ['overview', 'documents', 'interview', 'blueprint', 'keys'];
96
+ let state = null, shown = '', docCache = new Map();
97
+
98
+ function el(tag, cls, text) {
99
+ const e = document.createElement(tag);
100
+ if (cls) e.className = cls;
101
+ if (text !== undefined && text !== null) e.textContent = text;
102
+ return e;
103
+ }
104
+ function say(text, kind) {
105
+ flash.textContent = text; flash.className = kind;
106
+ clearTimeout(say.t); say.t = setTimeout(() => { flash.className = ''; }, kind === 'err' ? 8000 : 3000);
107
+ }
108
+ function when(iso) { if (!iso) return ''; const d = new Date(iso); return isNaN(d) ? '' : d.toLocaleString(); }
109
+ function route() {
110
+ const h = location.hash.replace(/^#/, '');
111
+ const [tab, ...rest] = h.split('/');
112
+ return { tab: TABS.includes(tab) ? tab : 'overview', arg: decodeURIComponent(rest.join('/')) };
113
+ }
114
+ async function api(method, url, body) {
115
+ const res = await fetch(url, { method, headers: body ? { 'Content-Type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined, cache: 'no-store' });
116
+ let data = {}; try { data = await res.json(); } catch {}
117
+ if (!res.ok) throw new Error((data.error && data.error.message) || ('the board answered ' + res.status));
118
+ return data;
119
+ }
120
+ function typing() {
121
+ const a = document.activeElement;
122
+ if (a && main.contains(a) && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA' || a.tagName === 'SELECT')) return true;
123
+ return [...main.querySelectorAll('input, textarea')].some((e) => e.value && e.defaultValue !== e.value);
124
+ }
125
+
126
+ function chipOf(d) {
127
+ if (d.written) {
128
+ if (!d.check) return el('span', 'chip ok', 'Written');
129
+ return d.check.ok ? el('span', 'chip ok', 'Checked') : el('span', 'chip bad', d.check.findings.length + ' finding' + (d.check.findings.length === 1 ? '' : 's'));
130
+ }
131
+ return d.conditional ? el('span', 'chip idle', 'If needed') : el('span', 'chip warn', 'Waiting');
132
+ }
133
+
134
+ function overview() {
135
+ const frag = document.createDocumentFragment();
136
+ const next = el('section', 'card next');
137
+ next.append(el('b', '', 'Next step'), el('div', '', state.next));
138
+ frag.append(next);
139
+ const f = state.flow;
140
+ const card = el('section', 'card');
141
+ card.append(el('h2', '', 'Design flow'));
142
+ if (!f.available) { card.append(el('p', 'muted', 'The design pipeline is not installed. Run "genesis install".')); frag.append(card); return frag; }
143
+ if (!f.checksAvailable) card.append(el('p', 'note', 'design-check is unavailable here (mind-set package not found); documents show as written, not checked.'));
144
+ const stages = [];
145
+ for (const d of f.docs) { const last = stages[stages.length - 1]; if (last && last.stage === d.stage) last.docs.push(d); else stages.push({ stage: d.stage, label: d.label, docs: [d] }); }
146
+ for (const s of stages) {
147
+ const box = el('div', 'stage');
148
+ box.append(el('h3', '', s.stage + ' · ' + s.label));
149
+ for (const d of s.docs) {
150
+ const r = el('div', 'row' + (d.written ? ' link' : ''));
151
+ r.append(el('span', 'doc grow', d.docName), el('span', 'small muted', d.written ? when(d.mtime) : ''), chipOf(d));
152
+ if (d.written) r.addEventListener('click', () => { location.hash = '#documents/' + encodeURIComponent(d.docName); });
153
+ box.append(r);
154
+ }
155
+ card.append(box);
156
+ }
157
+ if (f.other && f.other.length) {
158
+ const box = el('div', 'stage'); box.append(el('h3', '', 'Other documents'));
159
+ for (const n of f.other) { const r = el('div', 'row link'); r.append(el('span', 'doc grow', n)); r.addEventListener('click', () => { location.hash = '#documents/' + encodeURIComponent(n); }); box.append(r); }
160
+ card.append(box);
161
+ }
162
+ frag.append(card);
163
+ return frag;
164
+ }
165
+
166
+ async function documents(arg) {
167
+ const wrap = el('div', 'split');
168
+ const list = el('section', 'card list');
169
+ const names = state.flow.available ? state.flow.docs.filter((d) => d.written).map((d) => d.docName).concat(state.flow.other || []) : [];
170
+ if (!names.length) { list.append(el('p', 'muted', 'No design document yet.')); wrap.append(list); return wrap; }
171
+ const pick = names.includes(arg) ? arg : names[0];
172
+ for (const n of names) { const r = el('div', 'row link doc' + (n === pick ? ' on' : ''), n); r.addEventListener('click', () => { location.hash = '#documents/' + encodeURIComponent(n); }); list.append(r); }
173
+ const view = el('section', 'card md');
174
+ const d = state.flow.docs.find((x) => x.docName === pick);
175
+ const head = el('div', 'row'); head.append(el('h2', 'grow', pick)); if (d) head.append(chipOf(d)); view.append(head);
176
+ if (d && d.check && !d.check.ok) { const ul = el('ul', 'small'); for (const m of d.check.findings) ul.append(el('li', '', m)); view.append(ul); }
177
+ const body = el('div', '', 'Loading...'); view.append(body);
178
+ wrap.append(list, view);
179
+ const key = pick + '@' + (d ? d.mtime : '');
180
+ try {
181
+ if (!docCache.has(key)) docCache.set(key, (await api('GET', '/api/doc?name=' + encodeURIComponent(pick))).html);
182
+ body.innerHTML = docCache.get(key); // the server's escaped rendering (board-md.mjs)
183
+ } catch (e) { body.textContent = e.message; }
184
+ return wrap;
185
+ }
186
+
187
+ function interview() {
188
+ const card = el('section', 'card');
189
+ const i = state.interview;
190
+ card.append(el('h2', '', 'Requirements interview'));
191
+ if (!i) { card.append(el('p', 'muted', 'The interview has not started. Ask the agent to design the application.')); return card; }
192
+ const r = el('div', 'row'); r.append(el('span', 'grow', 'Status'), el('span', 'chip ' + (/closed/.test(i.status || '') ? 'ok' : 'warn'), i.status || 'unknown')); card.append(r);
193
+ card.append(el('h2', '', 'Open questions (' + i.open.length + ')'));
194
+ if (!i.open.length) card.append(el('p', 'muted', 'None.'));
195
+ else { const ul = el('ul'); for (const o of i.open) ul.append(el('li', '', o)); card.append(ul); }
196
+ if (i.ledger.length) {
197
+ card.append(el('h2', '', 'Coverage ledger'));
198
+ const t = el('table'); const [h, ...rows] = i.ledger;
199
+ const tr = el('tr'); for (const c of h) tr.append(el('th', '', c)); const th = el('thead'); th.append(tr); t.append(th);
200
+ const tb = el('tbody'); for (const row of rows) { const r2 = el('tr'); for (const c of row) r2.append(el('td', '', c)); tb.append(r2); } t.append(tb);
201
+ const w = el('div', 'table'); w.append(t); card.append(w);
202
+ }
203
+ return card;
204
+ }
205
+
206
+ function blueprint() {
207
+ const card = el('section', 'card');
208
+ const b = state.blueprint, v = state.validation;
209
+ card.append(el('h2', '', 'Blueprint'));
210
+ if (!b) { card.append(el('p', 'muted', 'No blueprint.json yet. It is written after the design documents.')); return card; }
211
+ if (b.error) { card.append(el('p', 'note', b.error)); return card; }
212
+ const r = el('div', 'row'); r.append(el('span', 'grow', b.name ? 'Project ' + b.name : 'blueprint.json'));
213
+ if (v && v.available) r.append(el('span', 'chip ' + (v.errors ? 'bad' : v.warnings ? 'warn' : 'ok'), v.errors ? v.errors + ' error(s)' : v.warnings ? v.warnings + ' warning(s)' : 'Valid'));
214
+ else r.append(el('span', 'chip idle', 'Not validated'));
215
+ card.append(r);
216
+ if (v && v.first && v.first.length) { const ul = el('ul', 'small'); for (const m of v.first) ul.append(el('li', 'doc', m)); card.append(ul); }
217
+ const t = el('table'); const tr = el('tr'); for (const c of ['Service', 'Data objects', 'Business APIs']) tr.append(el('th', '', c));
218
+ const th = el('thead'); th.append(tr); t.append(th); const tb = el('tbody');
219
+ for (const s of b.services) { const r2 = el('tr'); r2.append(el('td', 'doc', s.name), el('td', '', String(s.dataObjects)), el('td', '', String(s.businessApis))); tb.append(r2); }
220
+ t.append(tb); const w = el('div', 'table'); w.append(t); card.append(w);
221
+ return card;
222
+ }
223
+
224
+ function keyCard(k) {
225
+ const c = el('div', 'kcard');
226
+ const head = el('div', 'khead');
227
+ head.append(el('strong', '', k.label), el('code', '', k.name), el('span', 'chip ' + (k.status === 'set' ? 'ok' : 'warn'), k.status === 'set' ? 'Set' : 'Empty'));
228
+ c.append(head);
229
+ if (k.description) c.append(el('div', 'small muted', k.description));
230
+ const meta = []; if (k.masked) meta.push('key ' + k.masked); if (k.status === 'set' && k.updatedAt) meta.push('saved ' + when(k.updatedAt));
231
+ if (meta.length) c.append(el('div', 'small muted', meta.join(' · ')));
232
+ if (k.source) c.append(el('p', 'note', 'The environment variable ' + k.source + ' is set and wins over a value saved here.'));
233
+ const base = '/api/keys/' + k.scope + '/' + encodeURIComponent(k.name);
234
+ const fields = el('div', 'fields');
235
+ const field = el('div', 'field');
236
+ const input = el('input'); input.type = 'password'; input.autocomplete = 'off'; input.spellcheck = false;
237
+ input.placeholder = k.status === 'set' ? 'Paste a new value to replace it' : 'Paste the value'; input.setAttribute('aria-label', 'Value of ' + k.label);
238
+ const peek = el('button', 'peek', 'Show'); peek.type = 'button';
239
+ peek.addEventListener('click', () => { const s = input.type === 'password'; input.type = s ? 'text' : 'password'; peek.textContent = s ? 'Hide' : 'Show'; input.focus(); });
240
+ field.append(input, peek);
241
+ const save = el('button', 'primary', k.status === 'set' ? 'Replace' : 'Save'); save.type = 'button';
242
+ const doSave = async () => {
243
+ const v = input.value.trim(); if (!v) { say('Paste the value first.', 'err'); return; }
244
+ save.disabled = true;
245
+ try { await api('PUT', base + '/value', { value: v }); input.value = ''; input.type = 'password'; say(k.label + ' saved.', 'ok'); await load(true); }
246
+ catch (e) { say(e.message, 'err'); } finally { save.disabled = false; }
247
+ };
248
+ save.addEventListener('click', doSave); input.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') doSave(); });
249
+ fields.append(field, save);
250
+ if (!state.canWrite) { input.disabled = true; save.disabled = true; peek.disabled = true; }
251
+ c.append(fields);
252
+ if (state.canWrite) {
253
+ const links = el('div', 'links');
254
+ if (k.status === 'set' && !k.source) { const b = el('button', '', 'Clear value'); b.type = 'button'; b.addEventListener('click', async () => { if (!confirm('Clear the value of ' + k.label + '?')) return; try { await api('DELETE', base + '/value'); say(k.label + ' cleared.', 'ok'); await load(true); } catch (e) { say(e.message, 'err'); } }); links.append(b); }
255
+ if (!k.builtin) { const b = el('button', 'danger', 'Delete key'); b.type = 'button'; b.addEventListener('click', async () => { if (!confirm('Delete ' + k.label + ' and its value?')) return; try { await api('DELETE', base); say(k.label + ' deleted.', 'ok'); await load(true); } catch (e) { say(e.message, 'err'); } }); links.append(b); }
256
+ if (links.childNodes.length) c.append(links);
257
+ }
258
+ return c;
259
+ }
260
+
261
+ function keys() {
262
+ const frag = document.createDocumentFragment();
263
+ if (!state.canWrite) { const n = el('section', 'card'); n.append(el('p', 'note', 'Read-only here. To add or change keys, run "genesis board" in the project folder (it opens the board with write access).')); frag.append(n); }
264
+ for (const [scope, title, hint] of [['project', 'This project', 'Kept in your home folder under this project, never in the project folder.'], ['global', 'Global', 'Yours in every project, such as the Genesis API key.']]) {
265
+ const g = el('section', 'card kgroup');
266
+ g.append(el('h2', '', title), el('div', 'small muted', hint));
267
+ const ks = state.keys.filter((k) => k.scope === scope);
268
+ if (!ks.length) g.append(el('p', 'muted', 'No keys yet.'));
269
+ for (const k of ks) g.append(keyCard(k));
270
+ frag.append(g);
271
+ }
272
+ if (state.canWrite) {
273
+ const add = el('section', 'card');
274
+ add.append(el('h2', '', 'Add a key'), el('div', 'small muted', 'The agent usually adds the keys it needs; you can add one yourself.'));
275
+ const f1 = el('div', 'fields'), f2 = el('div', 'fields'), f3 = el('div', 'fields');
276
+ const name = el('input'); name.placeholder = 'name, e.g. stripe-secret-key';
277
+ const label = el('input'); label.placeholder = 'Label';
278
+ const scope = el('select'); for (const [v, t] of [['project', 'This project'], ['global', 'Global']]) { const o = el('option', '', t); o.value = v; scope.append(o); }
279
+ const desc = el('textarea'); desc.placeholder = 'What it is for and where to get it';
280
+ const go = el('button', 'primary', 'Add key'); go.type = 'button';
281
+ go.addEventListener('click', async () => { try { await api('POST', '/api/keys', { name: name.value.trim(), label: label.value, description: desc.value, scope: scope.value }); name.value = ''; label.value = ''; desc.value = ''; say('Key added.', 'ok'); await load(true); } catch (e) { say(e.message, 'err'); } });
282
+ f1.append(name, label, scope); f2.append(desc); f3.append(go); add.append(f1, f2, f3);
283
+ frag.append(add);
284
+ }
285
+ return frag;
286
+ }
287
+
288
+ async function render(force) {
289
+ const { tab, arg } = route();
290
+ for (const a of document.querySelectorAll('nav a')) a.classList.toggle('on', a.dataset.tab === tab);
291
+ const sig = tab + '|' + arg + '|' + JSON.stringify(state);
292
+ if (sig === shown && !force) return;
293
+ if (!force && tab === 'keys' && typing()) return;
294
+ shown = sig;
295
+ const content = tab === 'overview' ? overview() : tab === 'documents' ? await documents(arg) : tab === 'interview' ? interview() : tab === 'blueprint' ? blueprint() : keys();
296
+ main.replaceChildren(content);
297
+ }
298
+
299
+ async function load(force) {
300
+ try { state = await api('GET', '/api/state'); await render(force); }
301
+ catch (e) { say(e.message, 'err'); }
302
+ }
303
+
304
+ window.addEventListener('hashchange', () => render(true));
305
+ setInterval(() => { if (document.visibilityState === 'visible') load(false); }, 3000);
306
+ load(true);
307
+ })();
308
+ `;
309
+
310
+ /** The board page; the project name is set as text by the script's first state load. */
311
+ export function renderBoardPage({ nonce, projectName }) {
312
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
313
+ return (
314
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
315
+ '<meta name="viewport" content="width=device-width, initial-scale=1">' +
316
+ '<meta name="referrer" content="no-referrer">' +
317
+ `<title>${esc(projectName)} · Genesis board</title>` +
318
+ `<style nonce="${nonce}">${STYLE}</style></head>` +
319
+ '<body><header><div class="bar">' +
320
+ `<div class="title"><h1>${esc(projectName)}</h1><span class="sub">Genesis project board</span></div>` +
321
+ '<nav><a href="#overview" data-tab="overview">Overview</a><a href="#documents" data-tab="documents">Documents</a>' +
322
+ '<a href="#interview" data-tab="interview">Interview</a><a href="#blueprint" data-tab="blueprint">Blueprint</a>' +
323
+ '<a href="#keys" data-tab="keys">Keys</a></nav></div></header>' +
324
+ '<main id="main"></main>' +
325
+ '<div class="bar"><footer>Local board on 127.0.0.1, read from the project folder as the agent writes. Open it any time with <code>genesis board</code> in the project folder.</footer></div>' +
326
+ '<div id="flash" role="status" aria-live="polite"></div>' +
327
+ `<script nonce="${nonce}">${SCRIPT}</script></body></html>`
328
+ );
329
+ }