@bugb-technologies/bravos 1.19.0 → 1.22.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/dist/account.js +19 -2
- package/dist/cli.js +124 -14
- package/dist/context.js +126 -3
- package/dist/dashboard.js +9 -0
- package/dist/device.js +3 -1
- package/dist/doctor.js +4 -0
- package/dist/guide.js +5 -3
- package/dist/help.js +15 -8
- package/dist/instruction-blocks.js +2 -1
- package/dist/principles.js +279 -0
- package/dist/review-server.js +19 -4
- package/dist/review-wait.js +11 -0
- package/dist/review.js +342 -41
- package/dist/rules.js +82 -6
- package/docs/GUIDE.md +12 -2
- package/docs/UPGRADING.md +39 -0
- package/hooks/cards.mjs +20 -5
- package/hooks/lib/briefing.mjs +26 -2
- package/hooks/lib/context.mjs +57 -1
- package/hooks/lib/licence.mjs +2 -1
- package/hooks/lib/machine.mjs +77 -0
- package/hooks/lib/pre-pr.mjs +82 -1
- package/hooks/lib/principles.mjs +513 -0
- package/hooks/lib/refresh.mjs +11 -1
- package/hooks/lib/replay.mjs +218 -100
- package/package.json +1 -1
- package/skills/bravos/SKILL.md +1 -0
- package/skills/bravos-context/SKILL.md +4 -4
- package/skills/bravos-principles/SKILL.md +52 -0
- package/templates/dashboard/dashboard.html +75 -1
- package/templates/review/review.html +140 -11
- package/templates/workflows/bravos-nightly-claude.yml +1 -1
- package/templates/workflows/bravos-nightly-codex.yml +1 -1
- package/templates/workflows/bravos-pr-gate.yml +1 -1
package/dist/review.js
CHANGED
|
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
|
|
|
3
3
|
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { createServer } from 'node:http';
|
|
5
5
|
import { dirname, join } from 'node:path';
|
|
6
|
-
import { reviewSources } from './context.js';
|
|
6
|
+
import { contextLib, reviewSources } from './context.js';
|
|
7
7
|
import { templatesDir } from './paths.js';
|
|
8
8
|
import { BravosError } from './types.js';
|
|
9
9
|
// @comment -- "bravos review: the drafts an agent wrote (.guardlink/<kind>-draft.json) rendered as a bravos-branded page people answer in, a loopback-only server that saves each person's answers to .guardlink/<kind>-answers/<name>.json, and a plain-text summary of agreement and disagreement for the agent. Draft text comes from repo files and is untrusted: it travels as JSON and the page renders it with textContent."
|
|
@@ -13,6 +13,7 @@ const MAX_BODY = 256 * 1024;
|
|
|
13
13
|
const IDLE_MS = 30 * 60 * 1000;
|
|
14
14
|
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
15
15
|
const str = (v, max = 4000) => typeof v === 'string' && v.length <= max;
|
|
16
|
+
const isAdoption = (v) => isObject(v) && str(v.id, 20) && (v.kind === 'enforced' || v.kind === 'guidance') && str(v.statement, 600) && str(v.scope, 200) && str(v.why, 600) && Array.isArray(v.paths) && v.paths.length <= 20 && v.paths.every((g) => str(g, 200)) && typeof v.hash === 'string' && /^[0-9a-f]{16}$/.test(v.hash);
|
|
16
17
|
// @comment -- "Kind names become file names: lowercase letters and hyphens only."
|
|
17
18
|
export function checkKind(kind) {
|
|
18
19
|
if (!/^[a-z][a-z-]{0,30}$/.test(kind))
|
|
@@ -37,6 +38,8 @@ export function validateDraft(value, kind) {
|
|
|
37
38
|
throw bad('repo must be a string');
|
|
38
39
|
if (value.perspective !== undefined && value.perspective !== 'researcher' && value.perspective !== 'owner')
|
|
39
40
|
throw bad('perspective must be researcher or owner');
|
|
41
|
+
if (value.retired !== undefined && !(Array.isArray(value.retired) && value.retired.length <= 300 && value.retired.every((r) => str(r, 80) && /^[A-Za-z0-9_.-]+$/.test(r))))
|
|
42
|
+
throw bad('retired must be a list of question ids');
|
|
40
43
|
const seen = new Set();
|
|
41
44
|
const cells = new Set();
|
|
42
45
|
for (const [n, q] of value.questions.entries()) {
|
|
@@ -73,6 +76,14 @@ export function validateDraft(value, kind) {
|
|
|
73
76
|
throw bad(`${q.id}: an item needs its text`);
|
|
74
77
|
if (q.sources !== undefined && !(Array.isArray(q.sources) && q.sources.every((s) => str(s, 400))))
|
|
75
78
|
throw bad(`${q.id}: sources must be strings`);
|
|
79
|
+
if (q.replaces !== undefined && !(Array.isArray(q.replaces) && q.replaces.length <= 20 && q.replaces.every((r) => str(r, 80) && /^[A-Za-z0-9_.-]+$/.test(r))))
|
|
80
|
+
throw bad(`${q.id}: replaces must be a list of question ids`);
|
|
81
|
+
if (q.excerpts !== undefined)
|
|
82
|
+
throw bad(`${q.id}: excerpts are filled in by bravos, not written in the draft`);
|
|
83
|
+
if (kind === 'principles')
|
|
84
|
+
checkPrincipleQuestion(q, bad);
|
|
85
|
+
else if (q.principle !== undefined)
|
|
86
|
+
throw bad(`${q.id}: principle details belong in the principles draft only`);
|
|
76
87
|
if (q.permission !== undefined) {
|
|
77
88
|
const p = q.permission;
|
|
78
89
|
const label = (v) => typeof v === 'string' && v.trim().length > 0 && v.length <= 160;
|
|
@@ -92,7 +103,47 @@ export function validateDraft(value, kind) {
|
|
|
92
103
|
}
|
|
93
104
|
return value;
|
|
94
105
|
}
|
|
95
|
-
// @comment -- "
|
|
106
|
+
// @comment -- "A principles candidate's shape: an SDP-n id, an item whose text is the one-line statement, a decision a person must make (mustTouch, never adopted by accepting untouched), and principle details: enforced or guidance, where it applies, why, optional repository globs, and its origin (a document citation, confirmed intent rules, or a starter-list entry, which is never pre-selected). Whether the origin holds is checked against the files when the review is prepared."
|
|
107
|
+
// @mitigates #principles against #principle-origin-invented using #verified-principle-origin -- "A principles draft is refused unless each candidate names one of the three origins in full, needs a person's own click, and a starter entry carries no suggestion, so no principle is pre-adopted or comes from nowhere"
|
|
108
|
+
function checkPrincipleQuestion(q, bad) {
|
|
109
|
+
if (!/^SDP-[1-9][0-9]{0,3}$/.test(q.id))
|
|
110
|
+
throw bad(`${q.id}: a principle's id is SDP-n`);
|
|
111
|
+
if (q.type !== 'item' || !str(q.text, 600) || /[\r\n]/.test(q.text) || !q.text.trim())
|
|
112
|
+
throw bad(`${q.id}: a principle is an item whose text is its statement, one line of at most 600 characters`);
|
|
113
|
+
if (q.mustTouch !== true)
|
|
114
|
+
throw bad(`${q.id}: every principle needs mustTouch: a person adopts each one`);
|
|
115
|
+
if (q.suggested !== undefined && q.suggested !== 'agree')
|
|
116
|
+
throw bad(`${q.id}: a principle's suggestion can only be agree`);
|
|
117
|
+
const p = q.principle;
|
|
118
|
+
if (!isObject(p))
|
|
119
|
+
throw bad(`${q.id}: a principle needs its principle details (kind, scope, why, origin)`);
|
|
120
|
+
if (p.kind !== 'enforced' && p.kind !== 'guidance')
|
|
121
|
+
throw bad(`${q.id}: principle.kind must be enforced or guidance`);
|
|
122
|
+
if (!str(p.scope, 200) || !p.scope.trim())
|
|
123
|
+
throw bad(`${q.id}: principle.scope says where it applies, e.g. "every HTTP handler" or "all code"`);
|
|
124
|
+
if (!str(p.why, 600) || !p.why.trim())
|
|
125
|
+
throw bad(`${q.id}: principle.why says why the team holds it`);
|
|
126
|
+
const glob = (g) => typeof g === 'string' && g.length <= 200 && /^[A-Za-z0-9_.\-/*?{},]+$/.test(g) && !g.startsWith('/') && !g.split('/').includes('..');
|
|
127
|
+
if (p.paths !== undefined && !(Array.isArray(p.paths) && p.paths.length <= 20 && p.paths.every(glob)))
|
|
128
|
+
throw bad(`${q.id}: principle.paths are repository globs such as src/api/**`);
|
|
129
|
+
if (p.origin === 'document') {
|
|
130
|
+
if (!Array.isArray(q.sources) || !q.sources.some((s) => /\bSRC-[1-9][0-9]{0,4}\b/.test(String(s))))
|
|
131
|
+
throw bad(`${q.id}: a principle from a document cites it in sources, as SRC-n "<section>"`);
|
|
132
|
+
}
|
|
133
|
+
else if (p.origin === 'intent') {
|
|
134
|
+
if (!Array.isArray(p.from) || !p.from.length || p.from.length > 20 || !p.from.every((r) => str(r, 300) && /^(?:[^:]+:)?INV-\d+$/.test(r)))
|
|
135
|
+
throw bad(`${q.id}: a principle from the intent lists its rules in principle.from, as INV-n or <path to another repository>:INV-n`);
|
|
136
|
+
}
|
|
137
|
+
else if (p.origin === 'starter') {
|
|
138
|
+
if (!str(p.starter, 60) || !p.starter)
|
|
139
|
+
throw bad(`${q.id}: a starter principle names its entry in principle.starter`);
|
|
140
|
+
if (q.suggested !== undefined)
|
|
141
|
+
throw bad(`${q.id}: a starter principle is never pre-selected; leave suggested out`);
|
|
142
|
+
}
|
|
143
|
+
else
|
|
144
|
+
throw bad(`${q.id}: principle.origin must be document, intent or starter: a principle comes from the team's documents, its confirmed rules, or the starter list, never from bravos alone`);
|
|
145
|
+
}
|
|
146
|
+
// @comment -- "Validates one person's answers against the draft: the answers schema, a non-empty name, and the ids the draft has. An answer to an id a question now replaces is carried onto that question (marked `from`); an answer to an id the draft no longer asks is kept under `stale`, never dropped silently. Returns the cleaned record."
|
|
96
147
|
export function validateAnswers(value, draft) {
|
|
97
148
|
if (!isObject(value) || value.schema !== ANSWERS_SCHEMA)
|
|
98
149
|
throw new BravosError(`answers must use schema ${ANSWERS_SCHEMA}`);
|
|
@@ -101,23 +152,73 @@ export function validateAnswers(value, draft) {
|
|
|
101
152
|
if (!isObject(value.answers))
|
|
102
153
|
throw new BravosError('answers must be an object keyed by question id');
|
|
103
154
|
const ids = new Set(draft.questions.map((q) => q.id));
|
|
104
|
-
const
|
|
105
|
-
for (const
|
|
106
|
-
|
|
107
|
-
|
|
155
|
+
const replacedBy = new Map();
|
|
156
|
+
for (const q of draft.questions)
|
|
157
|
+
for (const old of q.replaces ?? [])
|
|
158
|
+
if (!ids.has(old))
|
|
159
|
+
replacedBy.set(old, q.id);
|
|
160
|
+
const clean = (a) => {
|
|
108
161
|
if (!str(a.verdict, 20))
|
|
109
|
-
|
|
162
|
+
return null;
|
|
110
163
|
const v = a.value;
|
|
111
164
|
const okValue = str(v) || (Array.isArray(v) && v.length <= 20 && v.every((x) => str(x, 40)));
|
|
112
|
-
|
|
165
|
+
const sv = a.suggested;
|
|
166
|
+
const okSuggested = str(sv) || (Array.isArray(sv) && sv.length <= 20 && sv.every((x) => str(x, 40)));
|
|
167
|
+
return {
|
|
113
168
|
verdict: a.verdict,
|
|
114
169
|
...(okValue ? { value: v } : {}),
|
|
115
170
|
...(str(a.choice, 40) ? { choice: a.choice } : {}),
|
|
116
171
|
...(str(a.text) ? { text: a.text } : {}),
|
|
117
172
|
...(str(a.comment) ? { comment: a.comment } : {}),
|
|
173
|
+
...(okSuggested ? { suggested: sv } : {}),
|
|
174
|
+
...(str(a.from, 80) ? { from: a.from } : {}),
|
|
175
|
+
...(isAdoption(a.adopted) ? { adopted: a.adopted } : {}),
|
|
118
176
|
};
|
|
177
|
+
};
|
|
178
|
+
const answers = Object.create(null);
|
|
179
|
+
const stale = Object.create(null);
|
|
180
|
+
const entries = [...Object.entries(value.answers), ...(isObject(value.stale) ? Object.entries(value.stale) : [])];
|
|
181
|
+
for (const [id, a] of entries) {
|
|
182
|
+
if (!isObject(a))
|
|
183
|
+
continue;
|
|
184
|
+
const c = clean(a);
|
|
185
|
+
if (!c)
|
|
186
|
+
continue;
|
|
187
|
+
if (ids.has(id)) {
|
|
188
|
+
if (!answers[id])
|
|
189
|
+
answers[id] = c;
|
|
190
|
+
}
|
|
191
|
+
else if (replacedBy.has(id)) {
|
|
192
|
+
const to = replacedBy.get(id);
|
|
193
|
+
if (!answers[to])
|
|
194
|
+
answers[to] = { ...c, from: id };
|
|
195
|
+
}
|
|
196
|
+
else if (Object.keys(stale).length < 300 && /^[A-Za-z0-9_.-]{1,80}$/.test(id))
|
|
197
|
+
stale[id] = c;
|
|
119
198
|
}
|
|
120
|
-
|
|
199
|
+
const status = value.status === 'in-progress' ? 'in-progress' : 'confirmed';
|
|
200
|
+
return {
|
|
201
|
+
schema: ANSWERS_SCHEMA,
|
|
202
|
+
kind: draft.kind,
|
|
203
|
+
by: value.by.trim(),
|
|
204
|
+
date: str(value.date, 40) ? value.date : new Date().toISOString().slice(0, 10),
|
|
205
|
+
answers,
|
|
206
|
+
status,
|
|
207
|
+
...(str(value.confirmedAt, 40) ? { confirmedAt: value.confirmedAt } : {}),
|
|
208
|
+
...(Object.keys(stale).length ? { stale } : {}),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
/** The answers a person has confirmed: in-progress saves never count as anybody's answer. */
|
|
212
|
+
export const confirmedOnly = (files) => files.filter((f) => f.status !== 'in-progress');
|
|
213
|
+
// @comment -- "Refuses a new draft that stops asking a question somebody confirmed an answer to, unless a question in it names the old id in `replaces`. The agent rewrites the draft each session; this is what keeps a confirmed answer from vanishing because a question was renamed."
|
|
214
|
+
export function lostAnswers(draft, files) {
|
|
215
|
+
const lost = new Map();
|
|
216
|
+
const retired = new Set(draft.retired ?? []);
|
|
217
|
+
for (const f of confirmedOnly(files))
|
|
218
|
+
for (const id of Object.keys(f.stale ?? {}))
|
|
219
|
+
if (!retired.has(id))
|
|
220
|
+
(lost.get(id) ?? lost.set(id, new Set()).get(id)).add(f.by);
|
|
221
|
+
return [...lost].map(([id, by]) => ({ id, by: [...by].sort() })).sort((a, b) => a.id.localeCompare(b.id));
|
|
121
222
|
}
|
|
122
223
|
// A must-touch decision counts only when a person acted on it; accepting untouched does not.
|
|
123
224
|
const DECIDED = new Set(['chosen', 'edited', 'no', 'choice', 'change', 'agree']);
|
|
@@ -214,15 +315,63 @@ const citedIds = (q) => (q.sources ?? []).flatMap((s) => s.match(/\bSRC-[1-9][0-
|
|
|
214
315
|
export async function prepareReview(root, draft) {
|
|
215
316
|
const sources = await reviewSources(root, new Set(draft.questions.flatMap(citedIds)));
|
|
216
317
|
const verified = new Set(sources.map((s) => s.id));
|
|
318
|
+
const textOf = new Map(sources.map((s) => [s.id, s.text]));
|
|
319
|
+
const L = await contextLib();
|
|
320
|
+
const problems = [];
|
|
217
321
|
const questions = draft.questions.map((q) => {
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
322
|
+
let out = q;
|
|
323
|
+
const flag = (why) => {
|
|
324
|
+
out = { ...out, mustTouch: true, confidence: 'low', reason: [out.reason, why].filter(Boolean).join(' ') };
|
|
325
|
+
};
|
|
326
|
+
if (q.permission) {
|
|
327
|
+
const missing = [...new Set(citedIds(q).filter((id) => !verified.has(id)))];
|
|
328
|
+
if (missing.length)
|
|
329
|
+
flag(`Check ${missing.join(', ')} before deciding. Its source text could not be included and verified for this review.`);
|
|
330
|
+
}
|
|
331
|
+
// THE CITED PASSAGE, FROM THE DOCUMENT ITSELF: shown under the question so a person checks the source,
|
|
332
|
+
// not bravos's reading of it. A section that is not in the document makes the item a decision.
|
|
333
|
+
const excerpts = [];
|
|
334
|
+
const notFound = [];
|
|
335
|
+
for (const c of (q.sources ?? []).flatMap((s) => L.citations(s))) {
|
|
336
|
+
const text = textOf.get(c.id);
|
|
337
|
+
if (text === undefined)
|
|
338
|
+
continue;
|
|
339
|
+
const passage = L.findSection(text, c.section);
|
|
340
|
+
if (passage)
|
|
341
|
+
excerpts.push({ id: c.id, section: c.section, text: passage });
|
|
342
|
+
else
|
|
343
|
+
notFound.push(`${c.id} "${c.section}"`);
|
|
344
|
+
}
|
|
345
|
+
if (excerpts.length)
|
|
346
|
+
out = { ...out, excerpts };
|
|
347
|
+
if (notFound.length)
|
|
348
|
+
flag(`The cited ${notFound.join(', ')} is not a heading or passage in that document: check the source before deciding.`);
|
|
349
|
+
if (draft.kind === 'principles' && q.principle?.origin === 'document') {
|
|
350
|
+
const cited = (q.sources ?? []).flatMap((s) => L.citations(s));
|
|
351
|
+
const unverified = [...new Set(citedIds(q).filter((id) => !verified.has(id)))];
|
|
352
|
+
if (!cited.length)
|
|
353
|
+
problems.push(`${q.id}: cites no section of a stored document (SRC-n "<section>")`);
|
|
354
|
+
else if (unverified.length || notFound.length)
|
|
355
|
+
problems.push(`${q.id}: its document citation ${[...unverified, ...notFound].join(', ')} could not be found in the stored documents`);
|
|
356
|
+
}
|
|
357
|
+
return out;
|
|
225
358
|
});
|
|
359
|
+
// A PRINCIPLE COMES FROM THE TEAM, NEVER FROM BRAVOS ALONE: every candidate's origin is checked against the files
|
|
360
|
+
// before anyone sees it, and a draft with one that does not hold is refused as a whole.
|
|
361
|
+
if (draft.kind === 'principles') {
|
|
362
|
+
const { principleOriginProblem, principlesLib } = await import('./principles.js');
|
|
363
|
+
const P = await principlesLib();
|
|
364
|
+
for (const [i, q] of questions.entries()) {
|
|
365
|
+
const problem = await principleOriginProblem(root, q);
|
|
366
|
+
if (problem)
|
|
367
|
+
problems.push(problem);
|
|
368
|
+
const starter = q.principle?.origin === 'starter' ? P.STARTER.find((s) => s.id === q.principle?.starter) : undefined;
|
|
369
|
+
if (starter)
|
|
370
|
+
questions[i] = { ...q, reason: [q.reason, `From bravos's starter list (OWASP ASVS 4.0.3 ${starter.asvs}). Optional: adopt it only if your team holds it.`].filter(Boolean).join(' ') };
|
|
371
|
+
}
|
|
372
|
+
if (problems.length)
|
|
373
|
+
throw new BravosError(`${draftPath(draft.kind)}: these candidates cannot be proposed, because a principle comes only from your documents, rules a person confirmed, or the starter list:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
|
|
374
|
+
}
|
|
226
375
|
return { draft: { ...draft, questions }, sources, repoUrl: reviewRepoUrl(root, draft.repo) };
|
|
227
376
|
}
|
|
228
377
|
// @comment -- "Embed the draft as inert JSON with escaped tag delimiters. Only a local review may add verified document bodies. Shared artifacts carry the citations and excerpts already present in the draft."
|
|
@@ -231,8 +380,10 @@ export async function renderReview(review, mode) {
|
|
|
231
380
|
const prepared = 'schema' in review ? { draft: review, sources: [], repoUrl: undefined } : review;
|
|
232
381
|
const { draft, repoUrl } = prepared;
|
|
233
382
|
const sources = mode.kind === 'artifact' ? [] : prepared.sources;
|
|
234
|
-
|
|
235
|
-
const
|
|
383
|
+
// A shared page carries citations only: the passages are document text, like the bodies.
|
|
384
|
+
const shown = mode.kind === 'artifact' ? { ...draft, questions: draft.questions.map(({ excerpts: _e, ...q }) => q) } : draft;
|
|
385
|
+
const heading = draft.kind === 'principles' ? 'Which security design principles does your team hold?' : draft.kind !== 'intent' ? `bravos asks: ${draft.kind}` : draft.perspective === 'owner' ? 'What does this product intend?' : `How should bravos judge ${draft.repo ?? 'this project'}?`;
|
|
386
|
+
const data = JSON.stringify({ draft: shown, mode, heading, sources, repoUrl }).replace(/</g, '\\u003c').replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16)}`);
|
|
236
387
|
const page = template.replace('__BRAVOS_DATA__', () => data);
|
|
237
388
|
// On claude.ai the runtime bridge supplies the shared database, so the page drops its own CSP there.
|
|
238
389
|
return mode.kind === 'artifact' ? page.replace(/<meta http-equiv="Content-Security-Policy"[^>]*>\n?/, '') : page;
|
|
@@ -249,11 +400,15 @@ function effective(q, a) {
|
|
|
249
400
|
return Array.isArray(v) ? [...v].sort().join(', ') : String(v);
|
|
250
401
|
}
|
|
251
402
|
// @comment -- "Plain-text summary for the agent, most important first: disagreements, edits and rejections, the must-touch decisions with who made them, unanswered questions, then one line per group of suggestions accepted as is, with names; no model involved."
|
|
252
|
-
export function summarize(draft,
|
|
403
|
+
export function summarize(draft, all, skipped = []) {
|
|
404
|
+
const files = confirmedOnly(all);
|
|
405
|
+
const inProgress = all.filter((f) => f.status === 'in-progress').map((f) => f.by);
|
|
253
406
|
const out = [];
|
|
254
407
|
out.push(`bravos review ${draft.kind}${draft.perspective ? ` (${draft.perspective})` : ''}: ${files.length} ${files.length === 1 ? 'person' : 'people'} answered${files.length ? ` (${files.map((f) => `${f.by}, ${f.date}`).join('; ')})` : ''}`);
|
|
255
408
|
if (skipped.length)
|
|
256
409
|
out.push(`skipped unreadable answer files: ${skipped.join(', ')}`);
|
|
410
|
+
if (inProgress.length)
|
|
411
|
+
out.push(`still answering, not confirmed (not counted below): ${inProgress.join(', ')}`);
|
|
257
412
|
const groups = { DISAGREE: [], EDITED: [], DECIDED: [], 'NO ANSWER': [] };
|
|
258
413
|
const accepted = Object.create(null);
|
|
259
414
|
let acceptedCount = 0;
|
|
@@ -262,7 +417,8 @@ export function summarize(draft, files, skipped = []) {
|
|
|
262
417
|
const values = new Set(rows.map((r) => effective(q, r.a)));
|
|
263
418
|
const head = `${q.id}${q.title ? ` — ${q.title}` : ''}`;
|
|
264
419
|
const sugg = q.suggested !== undefined ? (Array.isArray(q.suggested) ? q.suggested.join(', ') : q.suggested) : (q.text ?? q.draft ?? '—');
|
|
265
|
-
const
|
|
420
|
+
const changed = (a) => (a.from ? ` [answered as ${a.from}, before the question changed]` : a.suggested !== undefined && q.suggested !== undefined && JSON.stringify(a.suggested) !== JSON.stringify(q.suggested) ? ' [answered before bravos changed its suggestion]' : '');
|
|
421
|
+
const block = [head, ` bravos suggested: ${sugg}`, ...rows.map((r) => ` ${r.by}: ${r.a.verdict} → ${effective(q, r.a)}${r.a.comment ? ` (${r.a.comment})` : ''}${changed(r.a)}`)];
|
|
266
422
|
if (rows.length === 0)
|
|
267
423
|
groups['NO ANSWER'].push(block);
|
|
268
424
|
else if (values.size > 1)
|
|
@@ -282,12 +438,47 @@ export function summarize(draft, files, skipped = []) {
|
|
|
282
438
|
}
|
|
283
439
|
for (const [who, ids] of Object.entries(accepted))
|
|
284
440
|
out.push('', `[ACCEPTED as suggested by ${who}] ${ids.join(', ')}`);
|
|
441
|
+
// Answers to questions this draft no longer asks: never dropped without a word.
|
|
442
|
+
const stale = new Map();
|
|
443
|
+
for (const f of files)
|
|
444
|
+
for (const [id, a] of Object.entries(f.stale ?? {}))
|
|
445
|
+
(stale.get(id) ?? stale.set(id, []).get(id)).push(`${f.by}: ${a.verdict}${a.comment ? ` (${a.comment})` : ''}`);
|
|
446
|
+
for (const [id, rows] of stale)
|
|
447
|
+
out.push('', `[NO LONGER ASKED] ${id}${(draft.retired ?? []).includes(id) ? ' (retired on purpose)' : ''}`, ...rows.map((r) => ` ${r}`));
|
|
285
448
|
out.push('', `totals: ${groups.DISAGREE.length} disagreements, ${groups.EDITED.length} edited or rejected, ${groups.DECIDED.length} decisions made, ${acceptedCount} accepted as suggested, ${groups['NO ANSWER'].length} unanswered of ${draft.questions.length}`);
|
|
286
449
|
return out.join('\n');
|
|
287
450
|
}
|
|
288
|
-
|
|
289
|
-
export
|
|
451
|
+
/** Where a person's unconfirmed answers wait: a scratch folder git ignores, never the committed answers. */
|
|
452
|
+
export const progressPath = (kind, by) => `.bravos/review/progress/${checkKind(kind)}/${slug(by)}.json`;
|
|
453
|
+
// @comment -- "Keeps the review scratch folder out of git: the page it writes can hold document bodies, and in-progress answers are one person's unfinished work. The same one-line ignore file every other bravos scratch folder carries."
|
|
454
|
+
function ensureScratchIgnored(root) {
|
|
455
|
+
try {
|
|
456
|
+
const rel = '.bravos/review/.gitignore';
|
|
457
|
+
if (!existsSync(join(root, rel)))
|
|
458
|
+
writeReviewFile(root, rel, '*\n');
|
|
459
|
+
}
|
|
460
|
+
catch {
|
|
461
|
+
/* the ignore file is a courtesy; the folder is still written 0700 */
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
const MAX_DOCUMENT_BODY = 12 * 1024 * 1024;
|
|
465
|
+
// @comment -- "The loopback review server: GET / (the page), GET /answers (everyone's confirmed answers), GET /progress?by= (this person's unconfirmed answers), POST /progress (save them as they go, to a scratch file git ignores), POST /answers (Confirm: validated, must-touch decisions checked, written as .guardlink/<kind>-answers/<slug>.json with the time), POST /documents (a design document added on the page), POST /done (stop). Every request needs the token; the Host must be the loopback address it listens on; bodies over 256 KB (12 MB for a document) are refused; it stops after 30 minutes idle. With reload, each request reads the current draft, so one page can stay open across a rewritten draft."
|
|
466
|
+
export function startReviewServer(root, draft, page, token, port = 0, opts = {}) {
|
|
290
467
|
let idle;
|
|
468
|
+
let current = { draft, page };
|
|
469
|
+
const now = opts.now ?? (() => new Date());
|
|
470
|
+
ensureScratchIgnored(root);
|
|
471
|
+
const fresh = async () => {
|
|
472
|
+
if (!opts.reload)
|
|
473
|
+
return current;
|
|
474
|
+
try {
|
|
475
|
+
current = await opts.reload();
|
|
476
|
+
}
|
|
477
|
+
catch {
|
|
478
|
+
/* keep serving the last good draft; the CLI reports a broken one */
|
|
479
|
+
}
|
|
480
|
+
return current;
|
|
481
|
+
};
|
|
291
482
|
const server = createServer((req, res) => {
|
|
292
483
|
clearTimeout(idle);
|
|
293
484
|
idle = setTimeout(() => server.close(), IDLE_MS);
|
|
@@ -302,16 +493,37 @@ export function startReviewServer(root, draft, page, token, port = 0) {
|
|
|
302
493
|
const url = new URL(req.url ?? '/', `http://127.0.0.1:${p}`);
|
|
303
494
|
if (url.searchParams.get('t') !== token)
|
|
304
495
|
return send(403, 'wrong token');
|
|
305
|
-
if (req.method === 'GET' && url.pathname === '/')
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
if (req.method === '
|
|
496
|
+
if (req.method === 'GET' && url.pathname === '/') {
|
|
497
|
+
void fresh().then((c) => send(200, c.page, 'text/html; charset=utf-8'));
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (req.method === 'GET' && url.pathname === '/answers') {
|
|
501
|
+
void fresh().then((c) => send(200, JSON.stringify(confirmedOnly(readAllAnswers(root, c.draft).files)), 'application/json'));
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
if (req.method === 'GET' && url.pathname === '/progress') {
|
|
505
|
+
const by = url.searchParams.get('by') ?? '';
|
|
506
|
+
if (!slug(by))
|
|
507
|
+
return send(400, 'name needed');
|
|
508
|
+
void fresh().then((c) => {
|
|
509
|
+
try {
|
|
510
|
+
const raw = readFileSync(join(root, progressPath(c.draft.kind, by)), 'utf8');
|
|
511
|
+
send(200, JSON.stringify(validateAnswers(JSON.parse(raw), c.draft)), 'application/json');
|
|
512
|
+
}
|
|
513
|
+
catch {
|
|
514
|
+
send(404, 'none');
|
|
515
|
+
}
|
|
516
|
+
});
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
const posts = ['/answers', '/progress', '/documents', '/done'];
|
|
520
|
+
if (req.method === 'POST' && posts.includes(url.pathname)) {
|
|
521
|
+
const limit = url.pathname === '/documents' ? MAX_DOCUMENT_BODY : MAX_BODY;
|
|
310
522
|
let size = 0;
|
|
311
523
|
const chunks = [];
|
|
312
524
|
req.on('data', (c) => {
|
|
313
525
|
size += c.length;
|
|
314
|
-
if (size >
|
|
526
|
+
if (size > limit) {
|
|
315
527
|
send(413, 'too large');
|
|
316
528
|
req.destroy();
|
|
317
529
|
}
|
|
@@ -319,25 +531,69 @@ export function startReviewServer(root, draft, page, token, port = 0) {
|
|
|
319
531
|
chunks.push(c);
|
|
320
532
|
});
|
|
321
533
|
req.on('end', () => {
|
|
322
|
-
if (size >
|
|
534
|
+
if (size > limit)
|
|
323
535
|
return;
|
|
324
536
|
if (url.pathname === '/done') {
|
|
325
537
|
send(200, 'ok');
|
|
326
538
|
setTimeout(() => server.close(), 50);
|
|
327
539
|
return;
|
|
328
540
|
}
|
|
329
|
-
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
541
|
+
void (async () => {
|
|
542
|
+
const c = await fresh();
|
|
543
|
+
let body;
|
|
544
|
+
try {
|
|
545
|
+
body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
546
|
+
}
|
|
547
|
+
catch {
|
|
548
|
+
return send(400, 'not JSON');
|
|
549
|
+
}
|
|
550
|
+
if (url.pathname === '/documents') {
|
|
551
|
+
if (!opts.addDocument)
|
|
552
|
+
return send(404, 'documents are added in chat here');
|
|
553
|
+
const d = body;
|
|
554
|
+
if (!isObject(d) || !str(d.title, 200) || !str(d.kind, 20) || !str(d.by, 80) || !slug(d.by))
|
|
555
|
+
return send(400, 'a document needs a title, a kind and your name');
|
|
556
|
+
const doc = { title: d.title, kind: d.kind, by: d.by.trim() };
|
|
557
|
+
if (str(d.text, MAX_DOCUMENT_BODY)) {
|
|
558
|
+
doc.text = d.text;
|
|
559
|
+
if (str(d.name, 200))
|
|
560
|
+
doc.name = d.name;
|
|
561
|
+
}
|
|
562
|
+
else if (isObject(d.file) && str(d.file.name, 200) && typeof d.file.base64 === 'string')
|
|
563
|
+
doc.file = { name: d.file.name, base64: d.file.base64 };
|
|
564
|
+
else if (str(d.url, 2000))
|
|
565
|
+
doc.url = d.url;
|
|
566
|
+
else
|
|
567
|
+
return send(400, 'paste the text, choose a file, or give a link');
|
|
568
|
+
const out = await opts.addDocument(doc);
|
|
569
|
+
return out.ok ? send(200, JSON.stringify({ lines: out.lines }), 'application/json') : send(400, out.reason);
|
|
570
|
+
}
|
|
571
|
+
try {
|
|
572
|
+
let a = validateAnswers(body, c.draft);
|
|
573
|
+
// Only the server records what was adopted: anything the page sent under `adopted` is dropped here.
|
|
574
|
+
if (c.draft.kind === 'principles')
|
|
575
|
+
a = await (await import('./principles.js')).withAdoptions(c.draft, a);
|
|
576
|
+
else
|
|
577
|
+
for (const k of Object.keys(a.answers))
|
|
578
|
+
delete a.answers[k].adopted;
|
|
579
|
+
if (url.pathname === '/progress') {
|
|
580
|
+
writeReviewFile(root, progressPath(c.draft.kind, a.by), JSON.stringify({ ...a, status: 'in-progress' }, null, 2) + '\n');
|
|
581
|
+
return send(200, JSON.stringify({ saved: 'progress' }), 'application/json');
|
|
582
|
+
}
|
|
583
|
+
const missing = missingDecisions(c.draft, a);
|
|
584
|
+
if (missing.length)
|
|
585
|
+
return send(400, `these decisions still need your call: ${missing.join(', ')}`);
|
|
586
|
+
const rel = `${answersDir(c.draft.kind)}/${slug(a.by)}.json`;
|
|
587
|
+
const confirmedAt = now().toISOString();
|
|
588
|
+
writeReviewFile(root, rel, JSON.stringify({ ...a, status: 'confirmed', confirmedAt }, null, 2) + '\n');
|
|
589
|
+
rmSync(join(root, progressPath(c.draft.kind, a.by)), { force: true });
|
|
590
|
+
const after = opts.afterConfirm ? await opts.afterConfirm(c.draft.kind).catch((e) => [`could not update after Confirm: ${e instanceof Error ? e.message : String(e)}`]) : [];
|
|
591
|
+
send(200, JSON.stringify({ saved: rel, confirmedAt, lines: after }), 'application/json');
|
|
592
|
+
}
|
|
593
|
+
catch (e) {
|
|
594
|
+
send(400, e instanceof Error ? e.message : 'bad answers');
|
|
595
|
+
}
|
|
596
|
+
})();
|
|
341
597
|
});
|
|
342
598
|
return;
|
|
343
599
|
}
|
|
@@ -355,7 +611,52 @@ export function startReviewServer(root, draft, page, token, port = 0) {
|
|
|
355
611
|
export const newToken = () => randomBytes(16).toString('hex');
|
|
356
612
|
// @comment -- "Writes the rendered page for file mode (no server) to .bravos/review/<kind>.html and returns its path."
|
|
357
613
|
export function writePage(root, kind, page) {
|
|
614
|
+
ensureScratchIgnored(root);
|
|
358
615
|
const rel = `.bravos/review/${checkKind(kind)}.html`;
|
|
359
616
|
writeReviewFile(root, rel, page);
|
|
360
617
|
return rel;
|
|
361
618
|
}
|
|
619
|
+
// @comment -- "One sentence about the intake for the dashboard's Design rules view: who confirmed it and when, the must-touch decisions nobody has made, the design documents stored and waiting to be converted, and confirmed answers given before their question or bravos's suggestion changed. Read-only and never throws; null when there is no intake draft here. Names come from the committed answers files, which the team already shares."
|
|
620
|
+
export function intakeSummary(root) {
|
|
621
|
+
let draft;
|
|
622
|
+
try {
|
|
623
|
+
draft = readDraft(root, 'intent');
|
|
624
|
+
}
|
|
625
|
+
catch {
|
|
626
|
+
return null;
|
|
627
|
+
}
|
|
628
|
+
const files = confirmedOnly(readAllAnswers(root, draft).files);
|
|
629
|
+
const parts = [];
|
|
630
|
+
if (files.length) {
|
|
631
|
+
const latest = [...files].sort((a, b) => (b.confirmedAt ?? b.date).localeCompare(a.confirmedAt ?? a.date));
|
|
632
|
+
parts.push(`confirmed by ${latest.map((f) => `${f.by} (${(f.confirmedAt ?? f.date).slice(0, 10)})`).join(', ')}`);
|
|
633
|
+
}
|
|
634
|
+
else
|
|
635
|
+
parts.push('not confirmed yet: bravos review intent opens it');
|
|
636
|
+
const open = draft.questions.filter((q) => q.mustTouch && !files.some((f) => DECIDED.has(f.answers[q.id]?.verdict ?? '')));
|
|
637
|
+
if (open.length)
|
|
638
|
+
parts.push(`${open.length} decision${open.length === 1 ? '' : 's'} still open`);
|
|
639
|
+
const changed = draft.questions.filter((q) => files.some((f) => {
|
|
640
|
+
const a = f.answers[q.id];
|
|
641
|
+
return !!a && (!!a.from || (a.suggested !== undefined && q.suggested !== undefined && JSON.stringify(a.suggested) !== JSON.stringify(q.suggested)));
|
|
642
|
+
}));
|
|
643
|
+
if (changed.length)
|
|
644
|
+
parts.push(`${changed.length} answer${changed.length === 1 ? '' : 's'} to check: the question changed after it was confirmed`);
|
|
645
|
+
try {
|
|
646
|
+
const index = JSON.parse(readFileSync(join(root, '.bravos/context/sources.json'), 'utf8'));
|
|
647
|
+
const n = Array.isArray(index.sources) ? index.sources.length : 0;
|
|
648
|
+
let waiting = 0;
|
|
649
|
+
try {
|
|
650
|
+
waiting = readdirSync(join(root, '.bravos/context/inbox')).filter((f) => f.endsWith('.json')).length;
|
|
651
|
+
}
|
|
652
|
+
catch {
|
|
653
|
+
/* no inbox */
|
|
654
|
+
}
|
|
655
|
+
if (n || waiting)
|
|
656
|
+
parts.push(`${n} design document${n === 1 ? '' : 's'}${waiting ? ` (${waiting} more waiting to be converted)` : ''}`);
|
|
657
|
+
}
|
|
658
|
+
catch {
|
|
659
|
+
/* no documents */
|
|
660
|
+
}
|
|
661
|
+
return `Intake: ${parts.join(' · ')}.`;
|
|
662
|
+
}
|