pi-bro 0.29.0 → 0.31.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,87 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { render, safeRelative } from './render.mjs';
5
+ import { localPath } from './inventory.mjs';
6
+
7
+ // Match the repository checker’s backtick/tilde fence handling, plus inline
8
+ // code spans. Mermaid is its own language and must not be parsed as Markdown.
9
+ export function markdownLinks(text) {
10
+ let fence = '', width = 0;
11
+ const prose = [];
12
+ for (const line of text.split(/\r?\n/)) {
13
+ const token = /^\s*(`{3,}|~{3,})/.exec(line);
14
+ if (token) {
15
+ if (!fence) { fence = token[1][0]; width = token[1].length; }
16
+ else if (token[1][0] === fence && token[1].length >= width) fence = '';
17
+ prose.push('');
18
+ } else prose.push(fence || /^( {4}|\t)/.test(line) ? '' : line);
19
+ }
20
+ const source = prose.join('\n').replace(/(`+)(?!`)[\s\S]*?\1(?!`)/g, '');
21
+ return [...source.matchAll(/!?\[[^\]]*\]\((<[^>]+>|[^\s)]+)(?:\s+["'][^"']*["'])?\)/g)]
22
+ .map(m => m[1].replace(/^<|>$/g, ''));
23
+ }
24
+
25
+ /** Validate the files that would exist after import, not just the model's view.
26
+ * Omitted assets resolve against the original repo; staging helpers never do.
27
+ * knownFiles is optional for the standalone CLI; the pipeline supplies it.
28
+ */
29
+ export function check(root, { repositoryRoot = root, knownFiles } = {}) {
30
+ root = path.resolve(root);
31
+ repositoryRoot = path.resolve(repositoryRoot);
32
+ const docs = localPath(root, 'docs/architecture'), errors = [];
33
+ const known = knownFiles ? new Set(knownFiles) : undefined;
34
+ const knownTarget = relative => !known || known.has(relative) || [...known].some(p => p.startsWith(relative + '/'));
35
+ const targetExists = relative => {
36
+ if (relative === '.bro-architecture-support' || relative.startsWith('.bro-architecture-support/')) {
37
+ throw new Error('Reference to temporary architecture support: ' + relative);
38
+ }
39
+ safeRelative(relative, 'reference');
40
+ // Only proposed documentation may resolve against the staged tree. Source
41
+ // references and untouched/omitted assets must also exist in the real repo.
42
+ if (relative.startsWith('docs/architecture/') && fs.existsSync(localPath(root, relative))) return true;
43
+ return knownTarget(relative) && fs.existsSync(localPath(repositoryRoot, relative));
44
+ };
45
+ let result;
46
+ try { result = render(root, true); } catch (error) { errors.push(error.message); }
47
+ const walk = dir => {
48
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
49
+ const name = path.join(dir, entry.name), relative = path.relative(root, name).split(path.sep).join('/');
50
+ if (entry.isSymbolicLink()) { errors.push('Symlink inside architecture docs: ' + relative); continue; }
51
+ if (entry.isDirectory()) walk(name);
52
+ else if (entry.name.endsWith('.md')) {
53
+ for (const link of markdownLinks(fs.readFileSync(name, 'utf8'))) {
54
+ if (!link || link.startsWith('#') || /^(https?:|mailto:|data:)/i.test(link)) continue;
55
+ try {
56
+ const target = decodeURIComponent(link.split('#')[0]);
57
+ if (path.isAbsolute(target) || target.includes('\\') || /^[a-z][a-z0-9+.-]*:/i.test(target)) throw new Error('Unsafe local link: ' + link);
58
+ const resolved = path.relative(root, path.resolve(path.dirname(name), target)).split(path.sep).join('/');
59
+ if (!targetExists(resolved)) throw new Error('Broken link: ' + link);
60
+ } catch (error) {
61
+ errors.push((error instanceof URIError ? 'Invalid URL: ' + link : error.message) + ' in ' + relative);
62
+ }
63
+ }
64
+ }
65
+ }
66
+ };
67
+ if (!fs.existsSync(path.join(docs, 'README.md'))) errors.push('Missing docs/architecture/README.md');
68
+ if (fs.existsSync(docs)) walk(docs); else errors.push('Missing docs/architecture/');
69
+ if (result) {
70
+ for (const node of result.graph.nodes) {
71
+ for (const src of node.sources || []) {
72
+ try { if (!targetExists(src)) errors.push('Missing graph source: ' + src); } catch (error) { errors.push(error.message); }
73
+ }
74
+ if (node.doc) {
75
+ try { if (!targetExists('docs/architecture/' + safeRelative(node.doc, 'doc'))) errors.push('Missing graph guide: ' + node.doc); }
76
+ catch (error) { errors.push(error.message); }
77
+ }
78
+ }
79
+ if (!result.html.includes('id="graph-data"') || result.html.includes('src="https://') || result.html.includes('href="https://')) errors.push('HTML viewer is not self-contained');
80
+ }
81
+ if (errors.length) throw new Error(errors.join('\n'));
82
+ return { nodes: result.graph.nodes.length, edges: result.graph.edges.length };
83
+ }
84
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
85
+ try { const out = check(path.resolve(process.argv[2] || '.')); console.log('Architecture docs OK · ' + out.nodes + ' nodes · ' + out.edges + ' edges'); }
86
+ catch (error) { console.error(error.message); process.exitCode = 1; }
87
+ }
@@ -0,0 +1,83 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { lstatSync, readdirSync, existsSync as fssExists } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const EXCLUDE = new Set(['.git', 'node_modules', '.venv', 'venv', '.next', 'dist', 'build', 'coverage', '.cache', '__pycache__', '.turbo']);
7
+ const SECRET = /(^|\/)(\.env(?:\..*)?|\.?credentials(?:\..*)?|auth\.json|id_rsa|id_ed25519|.*\.pem|.*\.key)$/i;
8
+
9
+ /** Check every existing ancestor before reading or creating anything beneath it. */
10
+ export function localPath(root, relative) {
11
+ if (!relative || path.isAbsolute(relative) || relative.includes('\\') || relative.split('/').some(p => !p || p === '.' || p === '..') || /[\x00-\x1f:]/.test(relative)) {
12
+ throw new Error('Unsafe project path: ' + relative);
13
+ }
14
+ let current = root;
15
+ for (const part of ['', ...relative.split('/')]) {
16
+ if (part) current = path.join(current, part);
17
+ try {
18
+ if (lstatSync(current).isSymbolicLink()) throw new Error('Refusing symlink: ' + relative);
19
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
20
+ }
21
+ return current;
22
+ }
23
+
24
+ export function listProjectFiles(root) {
25
+ let candidates;
26
+ try {
27
+ const data = execFileSync('git', ['-C', root, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], { encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
28
+ candidates = data.split('\0').filter(Boolean);
29
+ } catch {
30
+ candidates = [];
31
+ const visit = (dir, prefix = '') => {
32
+ for (const dirent of readdirSync(dir, { withFileTypes: true })) {
33
+ if (EXCLUDE.has(dirent.name) || (prefix === '' && dirent.name === '.git')) continue;
34
+ const rel = prefix ? prefix + '/' + dirent.name : dirent.name;
35
+ if (dirent.isDirectory()) visit(path.join(dir, dirent.name), rel);
36
+ else if (dirent.isFile()) candidates.push(rel);
37
+ }
38
+ };
39
+ visit(root);
40
+ }
41
+ // Architecture docs may be intentionally ignored by Git. Still read and preserve them.
42
+ const architecture = localPath(root, 'docs/architecture');
43
+ const docs = [];
44
+ const visitDocs = (dir, prefix) => {
45
+ if (!fssExists(dir)) return;
46
+ for (const item of readdirSync(dir, { withFileTypes: true })) {
47
+ const rel = prefix + '/' + item.name;
48
+ if (item.isDirectory()) visitDocs(path.join(dir, item.name), rel);
49
+ else if (item.isFile()) docs.push(rel);
50
+ }
51
+ };
52
+ visitDocs(architecture, 'docs/architecture');
53
+ const unique = [...new Set([...candidates, ...docs])].sort();
54
+ return unique.filter(p => {
55
+ const rel = p.replaceAll('\\', '/');
56
+ if (path.isAbsolute(rel) || rel.split('/').includes('..') || rel.split('/').some(x => EXCLUDE.has(x)) || SECRET.test(rel)) return false;
57
+ try { return lstatSync(localPath(root, rel)).isFile(); } catch { return false; }
58
+ });
59
+ }
60
+
61
+ export function inventory(root, files = listProjectFiles(root)) {
62
+ const count = {};
63
+ const top = {};
64
+ for (const file of files) {
65
+ const ext = path.extname(file).toLowerCase() || '(none)';
66
+ count[ext] = (count[ext] || 0) + 1;
67
+ const folder = file.split('/')[0];
68
+ top[folder] = (top[folder] || 0) + 1;
69
+ }
70
+ const meaningful = /(readme|package\.json|pyproject\.toml|go\.mod|cargo\.toml|dockerfile|compose|dbt_project\.yml|schema\.yml|workflow|dag|app\.py|main\.[a-z]+|src\/bro\.ts|agents\.md)/i;
71
+ return {
72
+ files: files.length,
73
+ byExtension: Object.fromEntries(Object.entries(count).sort((a,b) => b[1]-a[1]).slice(0,20)),
74
+ topLevel: Object.fromEntries(Object.entries(top).sort((a,b) => b[1]-a[1]).slice(0,25)),
75
+ landmarks: files.filter(f => meaningful.test(f)).slice(0,120),
76
+ existingArchitectureDocs: files.filter(f => f.startsWith('docs/architecture/')).slice(0,150)
77
+ };
78
+ }
79
+
80
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
81
+ const root = path.resolve(process.argv[2] || '.');
82
+ console.log(JSON.stringify(inventory(root), null, 2));
83
+ }
@@ -0,0 +1,61 @@
1
+ /** Pure layout: condense strongly connected components, then rank the DAG.
2
+ * A cycle shares a column; its downstream nodes do not get trapped there.
3
+ */
4
+ export function layoutGraph(nodes, edges) {
5
+ const successors = new Map(nodes.map(n => [n.id, []]));
6
+ for (const e of edges) successors.get(e.from).push(e.to);
7
+ const indices = new Map(), low = new Map(), stack = [], active = new Set(), groups = [], groupOf = new Map();
8
+ let next = 0;
9
+ function visit(id) {
10
+ indices.set(id, next); low.set(id, next++); stack.push(id); active.add(id);
11
+ for (const other of successors.get(id)) {
12
+ if (!indices.has(other)) { visit(other); low.set(id, Math.min(low.get(id), low.get(other))); }
13
+ else if (active.has(other)) low.set(id, Math.min(low.get(id), indices.get(other)));
14
+ }
15
+ if (low.get(id) === indices.get(id)) {
16
+ const group = []; let member;
17
+ do { member = stack.pop(); active.delete(member); groupOf.set(member, groups.length); group.push(member); } while (member !== id);
18
+ groups.push(group);
19
+ }
20
+ }
21
+ for (const n of nodes) if (!indices.has(n.id)) visit(n.id);
22
+ const dag = groups.map(() => new Set()), degree = groups.map(() => 0), rank = groups.map(() => 0);
23
+ for (const e of edges) {
24
+ const from = groupOf.get(e.from), to = groupOf.get(e.to);
25
+ if (from !== to && !dag[from].has(to)) { dag[from].add(to); degree[to]++; }
26
+ }
27
+ const queue = groups.map((_, i) => i).filter(i => !degree[i]);
28
+ for (let i = 0; i < queue.length; i++) {
29
+ for (const to of dag[queue[i]]) {
30
+ rank[to] = Math.max(rank[to], rank[queue[i]] + 1);
31
+ if (--degree[to] === 0) queue.push(to);
32
+ }
33
+ }
34
+ const levels = [...new Set(rank)].sort((a, b) => a - b);
35
+ const column = new Map(nodes.map(n => [n.id, levels.indexOf(rank[groupOf.get(n.id)])]));
36
+ const columns = levels.map(() => []);
37
+ for (const n of nodes) columns[column.get(n.id)].push(n);
38
+ for (const list of columns) list.sort((a, b) => a.label.localeCompare(b.label));
39
+ const W = 224, H = 80, DY = 144, P = 52;
40
+ const lanes = levels.map(() => 0);
41
+ for (const e of edges) if (column.get(e.from) === column.get(e.to)) lanes[column.get(e.from)]++;
42
+ const positions = new Map(); let x = P;
43
+ columns.forEach((list, col) => {
44
+ list.forEach((n, row) => positions.set(n.id, { x, y: P + row * DY, column: col }));
45
+ x += W + Math.max(100, 60 + lanes[col] * 24);
46
+ });
47
+ const used = levels.map(() => 0);
48
+ const routes = edges.map(e => {
49
+ const a = positions.get(e.from), b = positions.get(e.to);
50
+ if (a.column === b.column) {
51
+ // Enter and leave on the right. Separate lanes keep feedback arrows and
52
+ // their rotated labels out of component boxes and out of the next column.
53
+ const right = a.x + W, lane = right + 36 + 24 * used[a.column]++;
54
+ const y = a.y + 24, y2 = b.y + 56;
55
+ return { d: `M${right} ${y} H${lane} V${y2} H${right}`, labelX: lane - 5, labelY: (y + y2) / 2, rotation: -90 };
56
+ }
57
+ const x1 = a.x + W, y1 = a.y + H / 2, x2 = b.x, y2 = b.y + H / 2, mid = Math.max(25, (x2 - x1) * .4);
58
+ return { d: `M${x1} ${y1} C${x1 + mid} ${y1},${x2 - mid} ${y2},${x2} ${y2}`, labelX: (x1 + x2) / 2, labelY: (y1 + y2) / 2 - 8, rotation: 0 };
59
+ });
60
+ return { nodeWidth: W, nodeHeight: H, width: x + P, height: P * 2 + Math.max(1, ...columns.map(c => c.length)) * DY, positions: Object.fromEntries(positions), routes };
61
+ }
@@ -0,0 +1,228 @@
1
+ import fs from 'node:fs/promises';
2
+ import { createReadStream } from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import crypto from 'node:crypto';
6
+ import { execFile } from 'node:child_process';
7
+ import { promisify } from 'node:util';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { listProjectFiles, inventory, localPath } from './inventory.mjs';
10
+ import { validateGraph, safeRelative, render } from './render.mjs';
11
+ import { check } from './check.mjs';
12
+
13
+ const exec=promisify(execFile);
14
+ const CURRENT=path.dirname(fileURLToPath(import.meta.url));
15
+ const RESOURCES=path.resolve(CURRENT,'..');
16
+ const MAX_FILE=1024*1024,MAX_TOTAL=80*1024*1024,MAX_FILES=25000;
17
+ const digest=b=>crypto.createHash('sha256').update(b).digest('hex');
18
+ const inside=(root,name)=>name===root||name.startsWith(root+path.sep);
19
+ const skip=/((^|\/)\.env($|\.)|(^|\/)auth\.json$|(^|\/)credentials(?:\.[^/]*)?$|\.pem$|\.key$|id_rsa$|id_ed25519$)/i;
20
+
21
+ async function projectRoot(cwd){
22
+ const current=await fs.realpath(path.resolve(cwd));
23
+ try{
24
+ const {stdout}=await exec('git',['-C',current,'rev-parse','--show-toplevel'],{timeout:5000});
25
+ const resolved=await fs.realpath(path.resolve(stdout.trim()));
26
+ if(inside(resolved,current))return resolved;
27
+ }catch{}
28
+ return current;
29
+ }
30
+ async function describeRevision(root){
31
+ try{const {stdout}=await exec('git',['-C',root,'rev-parse','--short=12','HEAD'],{timeout:5000});
32
+ return 'Commit '+stdout.trim()+' (with working files when present)';}
33
+ catch{return 'Local project snapshot';}
34
+ }
35
+ function cancelled(signal) { signal?.throwIfAborted(); }
36
+ async function hashFile(file, signal) {
37
+ const hash = crypto.createHash('sha256');
38
+ for await (const bytes of createReadStream(file)) { cancelled(signal); hash.update(bytes); }
39
+ return hash.digest('hex');
40
+ }
41
+ async function stage(cwd, { signal, maxFileBytes = MAX_FILE, maxTotalBytes = MAX_TOTAL } = {}) {
42
+ cancelled(signal);
43
+ const root = await projectRoot(cwd), paths = listProjectFiles(root);
44
+ if (!paths.length) throw new Error('No non-ignored project files were found in ' + root);
45
+ if (paths.length > MAX_FILES) throw new Error('Too many input files (' + paths.length + '); narrow the workspace first');
46
+ // Existing docs get first use of the model budget. Their baseline is independent
47
+ // of that budget, including large generated HTML and binary assets left in place.
48
+ paths.sort((a, b) => Number(b.startsWith('docs/architecture/')) - Number(a.startsWith('docs/architecture/')) || a.localeCompare(b));
49
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-bro-architecture-'));
50
+ const workspace = path.join(dir, 'project'), files = [], omitted = [], documents = [];
51
+ let used = 0;
52
+ try {
53
+ await fs.mkdir(workspace, { recursive: true });
54
+ for (const relative of paths) {
55
+ cancelled(signal);
56
+ if (skip.test(relative) || relative.startsWith('.bro-architecture-support/')) continue;
57
+ const source = localPath(root, relative);
58
+ const stat = await fs.lstat(source);
59
+ if (!stat.isFile()) continue;
60
+ const isDoc = relative.startsWith('docs/architecture/');
61
+ if (isDoc) documents.push({ path: relative, sha: await hashFile(source, signal), mode: stat.mode & 0o777 });
62
+ if (stat.size > maxFileBytes || used + stat.size > maxTotalBytes) { omitted.push(relative + ' (size or snapshot budget)'); continue; }
63
+ const bytes = await fs.readFile(source);
64
+ if (bytes.includes(0)) { omitted.push(relative + ' (binary)'); continue; }
65
+ used += bytes.length;
66
+ const dest = path.join(workspace, relative);
67
+ await fs.mkdir(path.dirname(dest), { recursive: true });
68
+ await fs.writeFile(dest, bytes, { mode: 0o600 });
69
+ files.push({ path: relative, sha: digest(bytes) });
70
+ }
71
+ if (!files.length) throw new Error('No readable source files were found');
72
+ const support = path.join(workspace, '.bro-architecture-support');
73
+ await fs.mkdir(support, { recursive: true });
74
+ await fs.cp(path.join(RESOURCES, 'references'), path.join(support, 'references'), { recursive: true });
75
+ const information = { root, dir, workspace, files, documents, knownFiles: paths, omitted, revision: await describeRevision(root), inventory: inventory(root, files.map(f => f.path)) };
76
+ cancelled(signal);
77
+ await fs.writeFile(path.join(dir, 'state.json'), JSON.stringify(information), { mode: 0o600 });
78
+ cancelled(signal);
79
+ return { root, dir, workspace, inventory: information.inventory, omitted: omitted.slice(0, 40), included: files.length };
80
+ } catch (error) { await fs.rm(dir, { recursive: true, force: true }); throw error; }
81
+ }
82
+ function parseProposal(text){
83
+ if(typeof text!=='string'||Buffer.byteLength(text,'utf8')>2*1024*1024)throw new Error('Model output is missing or too large');
84
+ let source=text.trim();
85
+ if(source.startsWith('```'))source=source.replace(/^```(?:json)?\s*\n?/i,'').replace(/\n?```\s*$/,'');
86
+ let value;try{value=JSON.parse(source);}catch{throw new Error('Architecture model did not return a single valid JSON proposal; re-run to try again');}
87
+ if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Architecture proposal must be an object');
88
+ if(!value.files||typeof value.files!=='object'||Array.isArray(value.files)||!Object.hasOwn(value.files,'README.md'))throw new Error('Proposal needs files.README.md');
89
+ if(typeof value.summary!=='string'||!value.summary.trim()||value.summary.length>10000)throw new Error('Proposal needs a short summary');
90
+ if(!Array.isArray(value.unknowns)||value.unknowns.length>100||value.unknowns.some(x=>typeof x!=='string'||x.length>1000))throw new Error('Invalid unknowns');
91
+ validateGraph(value.graph);
92
+ if(Object.keys(value.files).length>80)throw new Error('Too many generated files');
93
+ let bytes=0;
94
+ for(const [relative,content] of Object.entries(value.files)){
95
+ safeRelative(relative,'output');
96
+ if(!(/\.md$|\.mmd$/i.test(relative))||relative.startsWith('diagrams/')&& !relative.endsWith('.mmd')||['architecture.graph.json','architecture.html'].includes(relative))throw new Error('Output must be Markdown or Mermaid: '+relative);
97
+ if(typeof content!=='string'||!content.trim())throw new Error('Empty documentation file: '+relative);
98
+ bytes+=Buffer.byteLength(content);
99
+ if(bytes>1024*1024)throw new Error('Generated documentation exceeds 1 MiB');
100
+ }
101
+ if(!value.files['README.md'].includes('architecture.html'))value.files['README.md']+='\n\n[Explore the architecture map](architecture.html)\n';
102
+ return value;
103
+ }
104
+ async function stagedInputsAgree(state, signal) {
105
+ for (const original of state.files) {
106
+ cancelled(signal);
107
+ const file = localPath(state.workspace, original.path);
108
+ let hash; try { hash = await hashFile(file, signal); } catch (error) { cancelled(signal); throw new Error('Staged source was removed: ' + original.path); }
109
+ if (hash !== original.sha) throw new Error('Staged source was modified during inspection: ' + original.path);
110
+ }
111
+ }
112
+ async function originalsAgree(state, signal) {
113
+ const originals = new Map([...state.files, ...(state.documents || [])].map(f => [f.path, f]));
114
+ for (const original of originals.values()) {
115
+ cancelled(signal);
116
+ const file = localPath(state.root, original.path);
117
+ let hash; try { hash = await hashFile(file, signal); } catch (error) { cancelled(signal); throw new Error('Source changed during documentation: ' + original.path); }
118
+ if (hash !== original.sha) throw new Error('Source changed during documentation: ' + original.path + '. Re-run to document the new revision.');
119
+ }
120
+ }
121
+ async function prepareChanges(state, proposal, signal) {
122
+ const docs = localPath(state.workspace, 'docs/architecture');
123
+ await fs.mkdir(docs, { recursive: true });
124
+ const files = { ...proposal.files };
125
+ const graph = { ...proposal.graph, project: { ...proposal.graph.project, revision: state.revision || 'Local project snapshot' } };
126
+ files['architecture.graph.json'] = JSON.stringify(graph, null, 2) + '\n';
127
+ for (const [relative, text] of Object.entries(files)) {
128
+ cancelled(signal);
129
+ const target = localPath(state.workspace, 'docs/architecture/' + relative);
130
+ await fs.mkdir(path.dirname(target), { recursive: true });
131
+ await fs.writeFile(target, text, { mode: 0o600 });
132
+ }
133
+ localPath(state.workspace, 'docs/architecture/architecture.html');
134
+ render(state.workspace);
135
+ files['architecture.html'] = await fs.readFile(path.join(docs, 'architecture.html'), 'utf8');
136
+ check(state.workspace, { repositoryRoot: state.root, knownFiles: state.knownFiles });
137
+ cancelled(signal);
138
+ return files;
139
+ }
140
+ async function install(state, files, signal) {
141
+ const root = state.root, docs = localPath(root, 'docs/architecture');
142
+ await originalsAgree(state, signal);
143
+ const originals = new Map((state.documents || state.files).map(f => [f.path, f]));
144
+ const previous = new Map(), pending = [];
145
+ for (const [relative, text] of Object.entries(files)) {
146
+ cancelled(signal);
147
+ safeRelative(relative, 'output');
148
+ const target = localPath(root, 'docs/architecture/' + relative);
149
+ let old = null, mode;
150
+ try { old = await fs.readFile(target); mode = (await fs.stat(target)).mode & 0o777; }
151
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
152
+ const original = originals.get('docs/architecture/' + relative);
153
+ if (original) {
154
+ if (!old || digest(old) !== original.sha) throw new Error('Architecture document changed during generation: ' + relative);
155
+ } else if (old) throw new Error('New architecture document appeared during generation: ' + relative);
156
+ previous.set(relative, { bytes: old, mode });
157
+ if (!old || old.toString('utf8') !== text) pending.push({ relative, text, target });
158
+ }
159
+ const completed = [], temporaries = [];
160
+ try {
161
+ for (const item of pending) {
162
+ cancelled(signal);
163
+ localPath(root, 'docs/architecture/' + item.relative);
164
+ await fs.mkdir(path.dirname(item.target), { recursive: true });
165
+ const tmp = item.target + '.bro-' + crypto.randomUUID() + '.tmp';
166
+ temporaries.push(tmp);
167
+ // New public docs use the normal umask; refresh keeps the existing mode.
168
+ await fs.writeFile(tmp, item.text, { flag: 'wx' });
169
+ const before = previous.get(item.relative);
170
+ if (before.mode !== undefined) await fs.chmod(tmp, before.mode);
171
+ }
172
+ for (let i = 0; i < pending.length; i++) {
173
+ cancelled(signal);
174
+ const item = pending[i], before = previous.get(item.relative).bytes;
175
+ localPath(root, 'docs/architecture/' + item.relative);
176
+ let live = null; try { live = await fs.readFile(item.target); } catch (error) { if (error.code !== 'ENOENT') throw error; }
177
+ if ((before === null) !== (live === null) || (before && live && !before.equals(live))) throw new Error('Architecture docs changed during import: ' + item.relative);
178
+ await fs.rename(temporaries[i], item.target);
179
+ completed.push(item);
180
+ // In-process cancellation throws here, then waits for rollback. It never
181
+ // kills the importer between a rename and recording what must be restored.
182
+ cancelled(signal);
183
+ }
184
+ cancelled(signal);
185
+ return completed.map(item => 'docs/architecture/' + item.relative);
186
+ } catch (error) {
187
+ const failures = [];
188
+ for (const item of completed.reverse()) {
189
+ try {
190
+ localPath(root, 'docs/architecture/' + item.relative);
191
+ const live = await fs.readFile(item.target);
192
+ if (!live.equals(Buffer.from(item.text))) throw new Error('Another writer changed this document');
193
+ const before = previous.get(item.relative);
194
+ if (before.bytes === null) await fs.rm(item.target);
195
+ else {
196
+ const tmp = item.target + '.bro-' + crypto.randomUUID() + '.tmp';
197
+ temporaries.push(tmp);
198
+ await fs.writeFile(tmp, before.bytes, { flag: 'wx' });
199
+ await fs.chmod(tmp, before.mode);
200
+ await fs.rename(tmp, item.target);
201
+ }
202
+ } catch { failures.push(item.relative); }
203
+ }
204
+ if (failures.length) throw new Error(error.message + '; rollback was incomplete for ' + failures.join(', '));
205
+ throw error;
206
+ } finally {
207
+ for (const tmp of temporaries) await fs.rm(tmp, { force: true }).catch(() => {});
208
+ }
209
+ }
210
+ async function apply(dir, proposalPath, { signal } = {}) {
211
+ cancelled(signal);
212
+ const state = JSON.parse(await fs.readFile(path.join(dir, 'state.json'), 'utf8'));
213
+ if (state.dir !== path.resolve(dir)) throw new Error('Snapshot identity mismatch');
214
+ const proposal = parseProposal(await fs.readFile(proposalPath, 'utf8'));
215
+ await stagedInputsAgree(state, signal);
216
+ const files = await prepareChanges(state, proposal, signal);
217
+ const updated = await install(state, files, signal);
218
+ return { root: state.root, updated, summary: proposal.summary, unknowns: proposal.unknowns, nodes: proposal.graph.nodes.length };
219
+ }
220
+ export {stage,parseProposal,apply};
221
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
222
+ const command=process.argv[2];
223
+ try{
224
+ if(command==='prepare')console.log(JSON.stringify(await stage(process.argv[3]||'.')));
225
+ else if(command==='apply')console.log(JSON.stringify(await apply(path.resolve(process.argv[3]),path.resolve(process.argv[4]))));
226
+ else throw new Error('Use prepare <repo> or apply <snapshot-dir> <proposal.json>');
227
+ }catch(e){console.error(e.message);process.exitCode=1;}
228
+ }
@@ -0,0 +1,66 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { layoutGraph } from './layout.mjs';
6
+
7
+ const HERE=path.dirname(fileURLToPath(import.meta.url));
8
+ const TEMPLATE=path.resolve(HERE,'../assets/architecture-viewer.html');
9
+ export const sha=(text)=>crypto.createHash('sha256').update(text).digest('hex');
10
+
11
+ function nonempty(value,name,max=5000){if(typeof value!=='string'||!value.trim()||value.length>max)throw new Error(name+' must be non-empty text');return value;}
12
+ export function safeRelative(value,name){
13
+ if(typeof value!=='string'||!value||value.includes('\\')||path.posix.isAbsolute(value)||value.startsWith('/')||value.split('/').some(x=>x===''||x==='.'||x==='..')||/[\x00-\x1f?#]/.test(value)||/^[A-Za-z]:/.test(value)) throw new Error('Unsafe '+name+': '+String(value));
14
+ return value;
15
+ }
16
+ export function validateGraph(g){
17
+ if(!g||typeof g!=='object'||Array.isArray(g))throw new Error('Graph must be an object');
18
+ if(!g.project||typeof g.project!=='object')throw new Error('Graph needs project');
19
+ nonempty(g.project.name,'project.name',200);nonempty(g.project.summary,'project.summary',2000);
20
+ if(g.project.revision!==undefined)nonempty(g.project.revision,'project.revision',500);
21
+ if(!Array.isArray(g.nodes)||!g.nodes.length||g.nodes.length>250)throw new Error('Graph needs 1–250 nodes');
22
+ if(!Array.isArray(g.edges)||g.edges.length>1500)throw new Error('Invalid graph edges');
23
+ if(g.flows!==undefined&&!Array.isArray(g.flows))throw new Error('Invalid flows');
24
+ const ids=new Set();
25
+ for(const n of g.nodes){
26
+ if(!n||typeof n!=='object'||typeof n.id!=='string'||!/^[a-zA-Z0-9_-]{1,80}$/.test(n.id)||ids.has(n.id))throw new Error('Invalid/duplicate node id');
27
+ ids.add(n.id);nonempty(n.label,'node.label',120);nonempty(n.description,'node.description',2000);
28
+ if(n.kind!==undefined)nonempty(n.kind,'node.kind',80);
29
+ if(n.sources!==undefined){if(!Array.isArray(n.sources)||n.sources.length>30)throw new Error('Invalid node sources');for(const p of n.sources)safeRelative(p,'source');}
30
+ if(n.doc!==undefined)safeRelative(n.doc,'doc');
31
+ }
32
+ for(const e of g.edges){if(!e||!ids.has(e.from)||!ids.has(e.to))throw new Error('Edge references a missing node');nonempty(e.label,'edge.label',250);}
33
+ const flowIDs=new Set();for(const f of g.flows||[]){if(!f||typeof f.id!=='string'||!/^[a-zA-Z0-9_-]{1,80}$/.test(f.id)||flowIDs.has(f.id))throw new Error('Invalid/duplicate flow id');flowIDs.add(f.id);nonempty(f.label,'flow.label',150);if(!Array.isArray(f.steps)||!f.steps.length||f.steps.some(id=>!ids.has(id)))throw new Error('Flow references a missing node');}
34
+ return g;
35
+ }
36
+ const escapeHTML=(s)=>String(s).replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;');
37
+ export function renderGraph(raw,graph){
38
+ validateGraph(graph);
39
+ const template=fs.readFileSync(TEMPLATE,'utf8');
40
+ const fallback='<ul>'+graph.nodes.map(n=>'<li><strong>'+escapeHTML(n.label)+'</strong> — '+escapeHTML(n.description)+'</li>').join('')+'</ul>';
41
+ const json=JSON.stringify({ ...graph, layout: layoutGraph(graph.nodes, graph.edges) }).replaceAll('<','\\u003c').replaceAll('>','\\u003e').replaceAll('&','\\u0026');
42
+ const values={
43
+ '__TITLE__':escapeHTML(graph.project.name),
44
+ '__SUMMARY__':escapeHTML(graph.project.summary),
45
+ '__REVISION__':escapeHTML(graph.project.revision||'repository snapshot'),
46
+ '__SHA__':sha(raw),
47
+ '__DATA__':json,
48
+ '__NOSCRIPT__':fallback
49
+ };
50
+ return template.replace(/__TITLE__|__SUMMARY__|__REVISION__|__SHA__|__DATA__|__NOSCRIPT__/g,m=>values[m]);
51
+ }
52
+ export function render(root,checkOnly=false){
53
+ const docs=path.join(root,'docs','architecture');
54
+ const raw=fs.readFileSync(path.join(docs,'architecture.graph.json'),'utf8');
55
+ const graph=validateGraph(JSON.parse(raw));
56
+ const html=renderGraph(raw,graph);
57
+ const file=path.join(docs,'architecture.html');
58
+ if(checkOnly){
59
+ if(!fs.existsSync(file)||fs.readFileSync(file,'utf8')!==html)throw new Error('architecture.html is missing or stale; re-render the graph');
60
+ } else fs.writeFileSync(file,html);
61
+ return {graph,html,file};
62
+ }
63
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
64
+ try{const root=path.resolve(process.argv[2]||'.');const result=render(root,process.argv.includes('--check'));console.log((process.argv.includes('--check')?'Checked ':'Rendered ')+path.relative(root,result.file));}
65
+ catch(e){console.error(e.message);process.exitCode=1;}
66
+ }