iso-explainer 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -0
- package/README.md +119 -2
- package/README.pt-BR.md +89 -0
- package/bin/iso-explainer.mjs +75 -0
- package/package.json +37 -4
- package/skills/iso-explainer/SKILL.md +99 -0
- package/skills/iso-explainer/assets/figure/figure.mjs +93 -0
- package/skills/iso-explainer/assets/fonts/OFL.txt +93 -0
- package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-400-normal.woff2 +0 -0
- package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-500-normal.woff2 +0 -0
- package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-600-normal.woff2 +0 -0
- package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-700-normal.woff2 +0 -0
- package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-800-normal.woff2 +0 -0
- package/skills/iso-explainer/assets/runtime/ANATOMY-LICENSE.txt +21 -0
- package/skills/iso-explainer/assets/runtime/LUCIDE-LICENSE.txt +43 -0
- package/skills/iso-explainer/assets/runtime/app.js +727 -0
- package/skills/iso-explainer/assets/runtime/engine.js +1224 -0
- package/skills/iso-explainer/assets/runtime/icons.js +205 -0
- package/skills/iso-explainer/assets/runtime/kit.js +676 -0
- package/skills/iso-explainer/assets/runtime/looks-core.js +162 -0
- package/skills/iso-explainer/assets/runtime/looks.js +508 -0
- package/skills/iso-explainer/assets/runtime/styles.css +461 -0
- package/skills/iso-explainer/assets/runtime/template.html +29 -0
- package/skills/iso-explainer/assets/templates/starter.course.json +134 -0
- package/skills/iso-explainer/examples/arquitetura-pedidos.docs.json +1745 -0
- package/skills/iso-explainer/examples/catalogo-looks.course.json +599 -0
- package/skills/iso-explainer/examples/engenharia-na-pratica.course.json +2079 -0
- package/skills/iso-explainer/examples/figures/token-bucket.build.mjs +111 -0
- package/skills/iso-explainer/examples/figures/token-bucket.html +962 -0
- package/skills/iso-explainer/examples/historia-pedidos.story.json +1874 -0
- package/skills/iso-explainer/references/architecture-mode.md +82 -0
- package/skills/iso-explainer/references/design-system.md +58 -0
- package/skills/iso-explainer/references/engine.md +64 -0
- package/skills/iso-explainer/references/entities.md +72 -0
- package/skills/iso-explainer/references/figure-craft.md +62 -0
- package/skills/iso-explainer/references/flows.md +67 -0
- package/skills/iso-explainer/references/inside.md +74 -0
- package/skills/iso-explainer/references/layout.md +134 -0
- package/skills/iso-explainer/references/looks.md +60 -0
- package/skills/iso-explainer/references/schema.md +157 -0
- package/skills/iso-explainer/references/story-mode.md +72 -0
- package/skills/iso-explainer/references/storytelling.md +56 -0
- package/skills/iso-explainer/scripts/build.mjs +82 -0
- package/skills/iso-explainer/scripts/harvest.mjs +240 -0
- package/skills/iso-explainer/scripts/lib/layout.mjs +111 -0
- package/skills/iso-explainer/scripts/lib/resolve.mjs +269 -0
- package/skills/iso-explainer/scripts/snapshot.mjs +159 -0
- package/skills/iso-explainer/scripts/validate.mjs +58 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Collect the raw material of a project's story into one chronological, redacted dossier.
|
|
3
|
+
// node scripts/harvest.mjs <repo> [--out dossier] [--since 2025-01-01] [--until 2026-12-31]
|
|
4
|
+
// [--sessions auto|none|<dir>[,<dir>…]] [--max-chars 60000]
|
|
5
|
+
// Sources:
|
|
6
|
+
// • decision records: ADRs, RFCs, design docs (MADR / Nygard / free-form markdown), ARCHITECTURE, CHANGELOG, CLAUDE.md, AGENTS.md
|
|
7
|
+
// • git: tags, merges (PRs), commits that touch infra/deps/migrations, commits whose message signals a decision
|
|
8
|
+
// • agent sessions: Claude Code (~/.claude/projects), Codex CLI (~/.codex/sessions), or any folder of .jsonl/.json/.md exports
|
|
9
|
+
// Writes <out>.md (read this) and <out>.json (everything, structured). Secrets are masked before writing.
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { execFileSync } from 'node:child_process';
|
|
14
|
+
|
|
15
|
+
const args = process.argv.slice(2);
|
|
16
|
+
const opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
|
|
17
|
+
const repo = path.resolve(args.find((a, i) => !a.startsWith('--') && !args[i - 1]?.startsWith('--')) || '.');
|
|
18
|
+
const out = path.resolve(opt('--out', 'dossier'));
|
|
19
|
+
const since = opt('--since', null), until = opt('--until', null);
|
|
20
|
+
const maxChars = +opt('--max-chars', 60000);
|
|
21
|
+
const sessionsOpt = opt('--sessions', 'auto');
|
|
22
|
+
if (!fs.existsSync(repo)) { console.error(`repo not found: ${repo}`); process.exit(2); }
|
|
23
|
+
|
|
24
|
+
/* ── helpers ── */
|
|
25
|
+
const SECRET = [
|
|
26
|
+
[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '[chave privada removida]'],
|
|
27
|
+
[/\b(sk|pk|rk)-[A-Za-z0-9_-]{16,}\b/g, '[segredo]'], [/\bsk-ant-[A-Za-z0-9_-]{10,}\b/g, '[segredo]'],
|
|
28
|
+
[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, '[segredo]'], [/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, '[segredo]'],
|
|
29
|
+
[/\bAKIA[0-9A-Z]{16}\b/g, '[segredo]'], [/\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g, '[segredo]'], [/\bAIza[0-9A-Za-z_-]{30,}\b/g, '[segredo]'],
|
|
30
|
+
[/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, '[jwt]'],
|
|
31
|
+
[/\b(bearer)\s+[A-Za-z0-9._~+/-]{16,}=*/gi, '$1 [segredo]'],
|
|
32
|
+
[/\b([a-z][a-z0-9+.-]*:\/\/)([^:\s/@]+):([^@\s/]+)@/gi, '$1$2:[senha]@'],
|
|
33
|
+
[/\b((?:api[_-]?key|secret|token|password|passwd|senha|client[_-]?secret|access[_-]?key)\s*[:=]\s*)(["']?)[^\s"'`]{6,}\2/gi, '$1[segredo]'],
|
|
34
|
+
];
|
|
35
|
+
const redact = (s) => SECRET.reduce((acc, [re, rep]) => acc.replace(re, rep), String(s ?? ''));
|
|
36
|
+
const clip = (s, n) => { s = String(s ?? '').replace(/\s+/g, ' ').trim(); return s.length > n ? `${s.slice(0, n - 1)}…` : s; };
|
|
37
|
+
const day = (d) => { if (d == null || d === '') return null; const t = new Date(typeof d === 'number' && d < 1e12 ? d * 1000 : d); return isNaN(t) || t.getUTCFullYear() < 1995 ? null : t.toISOString().slice(0, 10); };
|
|
38
|
+
const inRange = (d) => !!d && (!since || d >= since) && (!until || d <= until);
|
|
39
|
+
const git = (...a) => { try { return execFileSync('git', ['-C', repo, ...a], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] }); } catch { return ''; } };
|
|
40
|
+
const hasGit = !!git('rev-parse', '--git-dir').trim();
|
|
41
|
+
const rel = (f) => path.relative(repo, f);
|
|
42
|
+
|
|
43
|
+
// Words that tend to mark a decision, a motivation or a turning point (pt + en).
|
|
44
|
+
const SIGNAL = /\b(decid\w*|decis[aã]o|decision|optamos|escolhemos|vamos usar|trocar|troca(mos)?|migr\w+|substitu\w+|adot\w+|adopt\w*|replace\w*|switch\w*|instead of|em vez de|ao inv[eé]s|trade-?off|porque|because|motiv\w+|raz[aã]o|reason|problema|problem|incident\w*|outage|ca[ií]u|fora do ar|lento|slow|timeout|gargalo|bottleneck|falh\w+|fail\w*|bug|alternativ\w+|considered|descart\w+|rejeit\w+|reject\w*|ADR|RFC|arquitetura|architecture|refator\w*|refactor\w*|escal\w+|scal\w+|performance|lat[eê]ncia|latency|custo|cost|seguran[cç]a|security|breaking)\b/i;
|
|
45
|
+
const INFRA = /(^|\/)(docker-compose[^/]*\.ya?ml|Dockerfile[^/]*|compose\.ya?ml|.*\.tf|.*\.tfvars|helm\/|charts\/|k8s\/|kubernetes\/|\.github\/workflows\/|\.gitlab-ci\.yml|vercel\.json|netlify\.toml|fly\.toml|render\.yaml|serverless\.ya?ml|nginx[^/]*\.conf|Procfile|package\.json|requirements\.txt|pyproject\.toml|go\.mod|Cargo\.toml|pom\.xml|build\.gradle|.*migrations?\/|prisma\/schema\.prisma|schema\.sql)/i;
|
|
46
|
+
|
|
47
|
+
/* ── 1. decision records & docs ── */
|
|
48
|
+
const SKIP = new Set(['node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', 'vendor', 'target', '.venv', 'venv', '__pycache__', 'coverage', '.turbo', '.cache']);
|
|
49
|
+
const DIR_HINT = /(^|\/)(adr|adrs|decisions?|decision-records?|architecture|arquitetura|rfcs?|design|design-docs|proposals?|postmortems?|incidents?)(\/|$)/i;
|
|
50
|
+
const FILE_HINT = /^(adr|rfc|dr)[-_ ]?\d+|^\d{3,4}[-_].+\.(md|mdx|adoc)$/i;
|
|
51
|
+
const TOP_FILES = /^(ARCHITECTURE|ARQUITETURA|CHANGELOG|HISTORY|CLAUDE|AGENTS|GEMINI|DECISIONS|README)\.(md|mdx)$/i;
|
|
52
|
+
function walk(dir, depth = 0, acc = []) {
|
|
53
|
+
if (depth > 7) return acc;
|
|
54
|
+
let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return acc; }
|
|
55
|
+
for (const e of ents) {
|
|
56
|
+
if (e.name.startsWith('.') && e.name !== '.github') continue;
|
|
57
|
+
const f = path.join(dir, e.name);
|
|
58
|
+
if (e.isDirectory()) { if (!SKIP.has(e.name)) walk(f, depth + 1, acc); }
|
|
59
|
+
else if (/\.(md|mdx|adoc|txt)$/i.test(e.name)) {
|
|
60
|
+
const r = rel(f);
|
|
61
|
+
if (DIR_HINT.test(path.dirname(r)) || FILE_HINT.test(e.name) || (depth <= 1 && TOP_FILES.test(e.name))) acc.push(f);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return acc;
|
|
65
|
+
}
|
|
66
|
+
const SECTION = [
|
|
67
|
+
['context', /^(context|contexto|context and problem statement|problem|problema|motiva\w*|background|situa[cç][aã]o|why|por ?qu[eê])/i],
|
|
68
|
+
['decision', /^(decision|decis[aã]o|decision outcome|chosen option|resolution|solu[cç][aã]o|proposal|proposta)/i],
|
|
69
|
+
['alternatives', /^(considered options|options|alternatives|alternativas|op[cç][oõ]es|rejected)/i],
|
|
70
|
+
['consequences', /^(consequences|consequ[eê]ncias|pros and cons|trade-?offs|impact|impacto|risks?|riscos?)/i],
|
|
71
|
+
['status', /^(status|estado)/i],
|
|
72
|
+
];
|
|
73
|
+
function parseRecord(file) {
|
|
74
|
+
const raw = redact(fs.readFileSync(file, 'utf8'));
|
|
75
|
+
const lines = raw.split(/\r?\n/);
|
|
76
|
+
const title = (lines.find((l) => /^#\s+/.test(l)) || path.basename(file)).replace(/^#\s+/, '').trim();
|
|
77
|
+
const rec = { file: rel(file), title, kind: /rfc/i.test(file) ? 'rfc' : /post-?mortem|incident/i.test(file) ? 'postmortem' : DIR_HINT.test(rel(file)) || FILE_HINT.test(path.basename(file)) ? 'adr' : 'doc', sections: {} };
|
|
78
|
+
let cur = null, buf = [];
|
|
79
|
+
const flush = () => { if (cur) rec.sections[cur] = clip(buf.join(' '), cur === 'status' ? 60 : 900); buf = []; };
|
|
80
|
+
for (const l of lines) {
|
|
81
|
+
const h = /^#{2,4}\s+(.+)/.exec(l) || /^\*\*(.+?)\*\*:?\s*$/.exec(l);
|
|
82
|
+
if (h) { const key = SECTION.find(([, re]) => re.test(h[1].trim()))?.[0]; flush(); cur = key || null; continue; }
|
|
83
|
+
const inline = /^(status|estado|date|data|deciders|decisores)\s*:\s*(.+)$/i.exec(l.replace(/^[-*]\s*/, '').replace(/\*\*/g, ''));
|
|
84
|
+
if (inline) { const k = inline[1].toLowerCase(); if (/status|estado/.test(k)) rec.sections.status = clip(inline[2], 60); else if (/date|data/.test(k)) rec.date = day(inline[2]) || rec.date; else rec.deciders = clip(inline[2], 120); continue; }
|
|
85
|
+
if (cur) buf.push(l);
|
|
86
|
+
}
|
|
87
|
+
flush();
|
|
88
|
+
rec.date ||= day((/\b(20\d{2}-\d{2}-\d{2})\b/.exec(raw) || [])[1]);
|
|
89
|
+
if (!rec.date && hasGit) rec.date = git('log', '--diff-filter=A', '--follow', '--format=%ad', '--date=short', '--', file).trim().split('\n').pop() || null;
|
|
90
|
+
if (!Object.keys(rec.sections).length) rec.excerpt = clip(lines.filter((l) => l.trim() && !/^#/.test(l)).join(' '), 700);
|
|
91
|
+
return rec;
|
|
92
|
+
}
|
|
93
|
+
const records = walk(repo).map(parseRecord).filter((r) => !r.date || inRange(r.date) || (!since && !until));
|
|
94
|
+
records.sort((a, b) => (a.date || '9999').localeCompare(b.date || '9999'));
|
|
95
|
+
|
|
96
|
+
/* ── 2. git history ── */
|
|
97
|
+
const gitData = { tags: [], merges: [], infra: [], signals: [], months: {} };
|
|
98
|
+
if (hasGit) {
|
|
99
|
+
const range = [...(since ? [`--since=${since}`] : []), ...(until ? [`--until=${until}`] : [])];
|
|
100
|
+
for (const l of git('for-each-ref', '--sort=creatordate', '--format=%(creatordate:short)|%(refname:short)|%(subject)', 'refs/tags').split('\n').filter(Boolean)) {
|
|
101
|
+
const [d, name, subj] = l.split('|'); if (inRange(d) || (!since && !until)) gitData.tags.push({ date: d, name, subject: redact(clip(subj, 160)) });
|
|
102
|
+
}
|
|
103
|
+
const SEP = '\u001e';
|
|
104
|
+
const log = git('log', '--no-color', '--date=short', `--format=${SEP}%h|%ad|%an|%P|%s|%b`, '--name-only', '-n', '4000', ...range);
|
|
105
|
+
for (const chunk of log.split(SEP).filter((c) => c.trim())) {
|
|
106
|
+
const [head, ...rest] = chunk.split('\n');
|
|
107
|
+
const [hash, date, author, parents, subject, ...bodyStart] = head.split('|');
|
|
108
|
+
const files = rest.filter((l) => l.trim() && !l.includes('|')).map((l) => l.trim());
|
|
109
|
+
const body = redact(clip(bodyStart.join('|') + ' ' + rest.filter((l) => !files.includes(l.trim())).join(' '), 400));
|
|
110
|
+
gitData.months[date.slice(0, 7)] = (gitData.months[date.slice(0, 7)] || 0) + 1;
|
|
111
|
+
const c = { hash, date, author, subject: redact(clip(subject, 200)) };
|
|
112
|
+
if (parents.trim().split(' ').length > 1) gitData.merges.push({ ...c, body });
|
|
113
|
+
const infra = files.filter((f) => INFRA.test(f));
|
|
114
|
+
if (infra.length) gitData.infra.push({ ...c, files: infra.slice(0, 6) });
|
|
115
|
+
else if (SIGNAL.test(subject) || /^(feat|refactor|perf)(\(.+\))?!?:/i.test(subject)) gitData.signals.push({ ...c, body });
|
|
116
|
+
}
|
|
117
|
+
for (const k of ['merges', 'infra', 'signals']) gitData[k].reverse();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/* ── 3. agent sessions ── */
|
|
121
|
+
const home = os.homedir();
|
|
122
|
+
const encodeClaude = (p) => p.replace(/[^A-Za-z0-9]/g, '-');
|
|
123
|
+
function listFiles(dir, re, depth = 0, acc = []) {
|
|
124
|
+
if (depth > 5) return acc;
|
|
125
|
+
let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return acc; }
|
|
126
|
+
for (const e of ents) { const f = path.join(dir, e.name); if (e.isDirectory()) listFiles(f, re, depth + 1, acc); else if (re.test(e.name)) acc.push(f); }
|
|
127
|
+
return acc;
|
|
128
|
+
}
|
|
129
|
+
function textOf(content) {
|
|
130
|
+
if (content == null) return '';
|
|
131
|
+
if (typeof content === 'string') return content;
|
|
132
|
+
if (Array.isArray(content)) return content.map((c) => (typeof c === 'string' ? c : c?.type === 'text' || c?.type === 'input_text' || c?.type === 'output_text' ? c.text : '')).filter(Boolean).join('\n');
|
|
133
|
+
if (typeof content === 'object') return content.text || '';
|
|
134
|
+
return '';
|
|
135
|
+
}
|
|
136
|
+
// Normalize one JSONL line from Claude Code, Codex (old + new rollout format) or anything similar.
|
|
137
|
+
function normalize(o) {
|
|
138
|
+
const ts = o.timestamp || o.ts || o.created_at || o.time || null;
|
|
139
|
+
if (o.type === 'summary' && o.summary) return { ts, role: 'summary', text: o.summary };
|
|
140
|
+
if (o.type === 'session_meta' || o.type === 'meta') return { ts, meta: o.payload || o };
|
|
141
|
+
const p = o.type === 'response_item' || o.type === 'event_msg' ? o.payload || {} : o;
|
|
142
|
+
if (p.type === 'user_message' && p.message) return { ts, role: 'user', text: p.message };
|
|
143
|
+
if (p.type === 'agent_message' && p.message) return { ts, role: 'assistant', text: p.message };
|
|
144
|
+
const m = p.message && typeof p.message === 'object' ? p.message : p;
|
|
145
|
+
const role = m.role || o.type;
|
|
146
|
+
const files = [];
|
|
147
|
+
if (Array.isArray(m.content)) for (const c of m.content) if (c?.type === 'tool_use' && c.input) { const f = c.input.file_path || c.input.path || c.input.notebook_path; if (f) files.push(f); }
|
|
148
|
+
if (role === 'user' || role === 'assistant') return { ts, role, text: textOf(m.content), files, cwd: o.cwd };
|
|
149
|
+
return { ts, cwd: o.cwd };
|
|
150
|
+
}
|
|
151
|
+
function readSession(file) {
|
|
152
|
+
let raw; try { raw = fs.readFileSync(file, 'utf8'); } catch { return null; }
|
|
153
|
+
const rows = [];
|
|
154
|
+
if (/\.jsonl$/i.test(file)) { for (const l of raw.split('\n')) { if (!l.trim()) continue; try { rows.push(normalize(JSON.parse(l))); } catch {} } }
|
|
155
|
+
else if (/\.json$/i.test(file)) { try { const j = JSON.parse(raw); const arr = Array.isArray(j) ? j : j.messages || j.history || j.items || []; for (const o of arr) rows.push(normalize(o)); } catch {} }
|
|
156
|
+
else rows.push({ role: 'user', text: raw, ts: fs.statSync(file).mtime.toISOString() });
|
|
157
|
+
const cwd = rows.find((r) => r.cwd)?.cwd || rows.find((r) => r.meta?.cwd)?.meta.cwd || null;
|
|
158
|
+
const msgs = rows.filter((r) => (r.role === 'user' || r.role === 'assistant' || r.role === 'summary') && r.text && !/^\s*<(command|local-command|system-reminder)/.test(r.text));
|
|
159
|
+
if (!msgs.length) return null;
|
|
160
|
+
const times = rows.map((r) => day(r.ts)).filter(Boolean).sort();
|
|
161
|
+
const start = times[0] || day(fs.statSync(file).mtime), end = times.at(-1) || start;
|
|
162
|
+
const firstUser = msgs.find((m) => m.role === 'user');
|
|
163
|
+
const summaries = msgs.filter((m) => m.role === 'summary').map((m) => clip(redact(m.text), 200));
|
|
164
|
+
const snippets = [];
|
|
165
|
+
for (const m of msgs) {
|
|
166
|
+
if (m.role === 'summary' || m === firstUser || snippets.length >= 10) continue;
|
|
167
|
+
for (const para of m.text.split(/\n{2,}/)) {
|
|
168
|
+
if (para.length < 40 || /^```/.test(para.trim()) || !SIGNAL.test(para)) continue;
|
|
169
|
+
snippets.push({ role: m.role, text: clip(redact(para), 360) });
|
|
170
|
+
if (snippets.length >= 10) break;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const files = [...new Set(rows.flatMap((r) => r.files || []))].map((f) => (cwd && f.startsWith(cwd) ? path.relative(cwd, f) : f));
|
|
174
|
+
return { file, cwd, start, end, messages: msgs.length, prompt: firstUser ? clip(redact(firstUser.text), 300) : '', summaries, snippets, files: files.slice(0, 12) };
|
|
175
|
+
}
|
|
176
|
+
const sessions = [];
|
|
177
|
+
const belongs = (s) => !s.cwd || s.cwd === repo || s.cwd.startsWith(repo + path.sep);
|
|
178
|
+
if (sessionsOpt !== 'none') {
|
|
179
|
+
const dirs = sessionsOpt === 'auto' ? [] : sessionsOpt.split(',').map((d) => path.resolve(d.replace(/^~/, home)));
|
|
180
|
+
if (sessionsOpt === 'auto') {
|
|
181
|
+
const cc = path.join(home, '.claude', 'projects');
|
|
182
|
+
if (fs.existsSync(cc)) for (const d of fs.readdirSync(cc)) { const full = path.join(cc, d); if (d === encodeClaude(repo) || d.startsWith(encodeClaude(repo) + '-')) dirs.push(full); else { const f = listFiles(full, /\.jsonl$/)[0]; if (f) { const s = readSession(f); if (s?.cwd && belongs(s)) dirs.push(full); } } }
|
|
183
|
+
const cx = path.join(home, '.codex', 'sessions');
|
|
184
|
+
if (fs.existsSync(cx)) dirs.push(cx);
|
|
185
|
+
}
|
|
186
|
+
const seen = new Set();
|
|
187
|
+
for (const d of dirs) for (const f of listFiles(d, /\.(jsonl|json|md)$/i)) {
|
|
188
|
+
if (seen.has(f)) continue; seen.add(f);
|
|
189
|
+
const s = readSession(f);
|
|
190
|
+
if (!s || !inRange(s.start) && (since || until)) continue;
|
|
191
|
+
if (sessionsOpt === 'auto' && f.includes(`${path.sep}.codex${path.sep}`) && !(s.cwd && belongs(s))) continue;
|
|
192
|
+
sessions.push(s);
|
|
193
|
+
}
|
|
194
|
+
sessions.sort((a, b) => a.start.localeCompare(b.start));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/* ── 4. timeline + dossier ── */
|
|
198
|
+
const timeline = [
|
|
199
|
+
...records.filter((r) => r.date).map((r) => ({ date: r.date, kind: r.kind, title: r.title, ref: r.file, status: r.sections.status })),
|
|
200
|
+
...gitData.tags.map((t) => ({ date: t.date, kind: 'tag', title: `${t.name}${t.subject ? ` — ${t.subject}` : ''}` })),
|
|
201
|
+
...gitData.merges.map((m) => ({ date: m.date, kind: 'pr', title: m.subject, ref: m.hash })),
|
|
202
|
+
...gitData.infra.map((c) => ({ date: c.date, kind: 'infra', title: c.subject, ref: `${c.hash} · ${c.files.join(', ')}` })),
|
|
203
|
+
...gitData.signals.map((c) => ({ date: c.date, kind: 'commit', title: c.subject, ref: c.hash })),
|
|
204
|
+
...sessions.map((s) => ({ date: s.start, kind: 'session', title: s.summaries[0] || s.prompt, ref: path.basename(s.file) })),
|
|
205
|
+
].sort((a, b) => a.date.localeCompare(b.date));
|
|
206
|
+
|
|
207
|
+
const name = path.basename(repo);
|
|
208
|
+
const span = timeline.length ? `${timeline[0].date} → ${timeline.at(-1).date}` : '—';
|
|
209
|
+
let md = `# Dossiê: ${name}\n\nGerado por iso-explainer/harvest em ${new Date().toISOString().slice(0, 10)} · período ${span}\n`;
|
|
210
|
+
md += `Fontes: ${records.length} documentos de decisão/arquitetura · ${hasGit ? `${Object.values(gitData.months).reduce((a, b) => a + b, 0)} commits (${gitData.tags.length} tags, ${gitData.merges.length} merges, ${gitData.infra.length} mudanças de infra, ${gitData.signals.length} commits com sinal de decisão)` : 'sem git'} · ${sessions.length} sessões de agente\n`;
|
|
211
|
+
md += `\n> Segredos foram mascarados. Trate trechos de sessão como evidência, não como fato: confirme no código/ADR antes de afirmar.\n`;
|
|
212
|
+
md += `\n## Linha do tempo\n\n${timeline.map((e) => `- ${e.date} · **${e.kind}** · ${clip(e.title, 140)}${e.status ? ` _(${e.status})_` : ''}${e.ref ? ` — \`${clip(e.ref, 90)}\`` : ''}`).join('\n') || '_vazia_'}\n`;
|
|
213
|
+
md += `\n## Registros de decisão e documentos\n`;
|
|
214
|
+
for (const r of records) {
|
|
215
|
+
md += `\n### ${r.title}\n\`${r.file}\` · ${r.kind}${r.date ? ` · ${r.date}` : ''}${r.sections.status ? ` · status: ${r.sections.status}` : ''}${r.deciders ? ` · ${r.deciders}` : ''}\n`;
|
|
216
|
+
for (const k of ['context', 'decision', 'alternatives', 'consequences']) if (r.sections[k]) md += `- **${k}**: ${r.sections[k]}\n`;
|
|
217
|
+
if (r.excerpt) md += `- ${r.excerpt}\n`;
|
|
218
|
+
}
|
|
219
|
+
if (sessions.length) {
|
|
220
|
+
md += `\n## Sessões de agente\n`;
|
|
221
|
+
for (const s of sessions) {
|
|
222
|
+
md += `\n### ${s.start}${s.end !== s.start ? ` → ${s.end}` : ''} · ${path.basename(s.file)} (${s.messages} mensagens)\n`;
|
|
223
|
+
if (s.prompt) md += `- **pedido inicial**: ${s.prompt}\n`;
|
|
224
|
+
for (const x of s.summaries.slice(0, 3)) md += `- **resumo**: ${x}\n`;
|
|
225
|
+
for (const x of s.snippets) md += `- _${x.role}_: ${x.text}\n`;
|
|
226
|
+
if (s.files.length) md += `- arquivos editados: ${s.files.map((f) => `\`${f}\``).join(', ')}\n`;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (hasGit) {
|
|
230
|
+
md += `\n## Git\n\nCommits por mês: ${Object.entries(gitData.months).sort().map(([m, n]) => `${m}: ${n}`).join(' · ')}\n`;
|
|
231
|
+
if (gitData.infra.length) md += `\n### Mudanças de infraestrutura/dependências\n${gitData.infra.map((c) => `- ${c.date} \`${c.hash}\` ${c.subject} — ${c.files.join(', ')}`).join('\n')}\n`;
|
|
232
|
+
if (gitData.merges.length) md += `\n### Merges / PRs\n${gitData.merges.map((c) => `- ${c.date} \`${c.hash}\` ${c.subject}${c.body ? ` — ${clip(c.body, 160)}` : ''}`).join('\n')}\n`;
|
|
233
|
+
if (gitData.signals.length) md += `\n### Commits com sinal de decisão\n${gitData.signals.map((c) => `- ${c.date} \`${c.hash}\` ${c.subject}`).join('\n')}\n`;
|
|
234
|
+
}
|
|
235
|
+
if (md.length > maxChars) md = md.slice(0, maxChars) + `\n\n…(cortado em ${maxChars} caracteres; use --since/--until ou leia ${path.basename(out)}.json)\n`;
|
|
236
|
+
|
|
237
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
238
|
+
fs.writeFileSync(`${out}.md`, md);
|
|
239
|
+
fs.writeFileSync(`${out}.json`, JSON.stringify({ repo, generated: new Date().toISOString(), timeline, records, git: gitData, sessions }, null, 2));
|
|
240
|
+
console.log(`✓ ${path.relative(process.cwd(), out)}.md (${(md.length / 1024).toFixed(0)} KB) · ${records.length} docs · ${timeline.length} eventos · ${sessions.length} sessões${hasGit ? '' : ' · sem git'}`);
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Automatic layout: entities written without x/y are placed by the engine, so an author (human or
|
|
2
|
+
// model) only declares what exists and what talks to what. The result is a layered flow that reads
|
|
3
|
+
// left → right on screen: one column per rank (longest path through the links), parallel entities
|
|
4
|
+
// stacked in the column, spacing sized for the object, its name plate and link labels.
|
|
5
|
+
//
|
|
6
|
+
// Isometric screen axes: +x and +y together move right on screen (Δx = Δy), +x against +y moves down
|
|
7
|
+
// (Δx = −Δy). So a rank step is (R, R) and a slot step inside a rank is (S, −S).
|
|
8
|
+
|
|
9
|
+
const PLACED = (e) => typeof e.x === 'number' || Array.isArray(e.at) || e.x0 !== undefined;
|
|
10
|
+
const SKIP = new Set(['panel', 'zone', 'crowd', 'queue']); // anchored or area entities keep their own geometry
|
|
11
|
+
const MAX_COLS = 6; // columns per band before a long flow wraps
|
|
12
|
+
const sizeOf = (e) => Math.max(e.s ?? 4, e.d ?? 0, e.w ?? 0, e.r ? e.r * 2 : 0, e.type === 'device' ? 6 : 0);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Assigns x/y to entities without a position. Mutates the given entity objects.
|
|
16
|
+
* @param {Record<string, object>} entities defs.entities (already copied for this lesson)
|
|
17
|
+
* @param {object[]} steps authored steps (inline scene entities are positioned too)
|
|
18
|
+
* @param {Record<string, object>} links defs.links
|
|
19
|
+
* @returns {string[]} ids that were placed
|
|
20
|
+
*/
|
|
21
|
+
export function autoLayout(entities, steps = [], links = {}) {
|
|
22
|
+
const nodes = new Map(); // id -> [objects that must receive the position]
|
|
23
|
+
const want = (id, obj) => {
|
|
24
|
+
if (!obj || typeof obj !== 'object' || SKIP.has(obj.type) || PLACED(obj)) return;
|
|
25
|
+
if (!nodes.has(id)) nodes.set(id, []);
|
|
26
|
+
nodes.get(id).push(obj);
|
|
27
|
+
};
|
|
28
|
+
for (const [id, e] of Object.entries(entities)) want(id, e);
|
|
29
|
+
const edges = [];
|
|
30
|
+
const addLink = (l) => { if (l && typeof l === 'object' && l.from && l.to) edges.push([l.from, l.to, l]); };
|
|
31
|
+
Object.values(links).forEach(addLink);
|
|
32
|
+
for (const s of steps) {
|
|
33
|
+
for (const [id, v] of Object.entries(s?.scene?.entities || {})) if (v && typeof v === 'object' && !v.use && v.type && !entities[id]) want(id, v);
|
|
34
|
+
Object.values(s?.scene?.links || {}).forEach(addLink);
|
|
35
|
+
}
|
|
36
|
+
if (!nodes.size) return [];
|
|
37
|
+
|
|
38
|
+
// ranks: breadth-first distance from where the flow starts. Flows are often cycles (the request
|
|
39
|
+
// goes out and the answer comes back), so the shortest distance keeps the outbound story in order and
|
|
40
|
+
// turns the way back into return links, instead of stretching one long chain.
|
|
41
|
+
const ids = [...nodes.keys()], out = new Map(ids.map((id) => [id, []]));
|
|
42
|
+
for (const [a, b] of edges) if (nodes.has(a) && nodes.has(b) && a !== b && !out.get(a).includes(b)) out.get(a).push(b);
|
|
43
|
+
const rank = new Map();
|
|
44
|
+
const bfs = (start) => {
|
|
45
|
+
const q = [start]; rank.set(start, rank.get(start) ?? 0);
|
|
46
|
+
while (q.length) { const id = q.shift(); for (const n of out.get(id)) if (!rank.has(n) && !leafOf.has(n)) { rank.set(n, rank.get(id) + 1); q.push(n); } }
|
|
47
|
+
};
|
|
48
|
+
// leaves (a database, a key service, a feeder that talks to one component only) hang beside their
|
|
49
|
+
// component, in its column, instead of taking a column of their own
|
|
50
|
+
const nbrs = new Map(ids.map((id) => [id, new Set()]));
|
|
51
|
+
for (const [a, b] of edges) if (nodes.has(a) && nodes.has(b) && a !== b) { nbrs.get(a).add(b); nbrs.get(b).add(a); }
|
|
52
|
+
const leafOf = new Map();
|
|
53
|
+
for (const id of ids) { const [p] = nbrs.get(id); if (nbrs.get(id).size === 1 && nbrs.get(p).size >= 3) leafOf.set(id, p); } // only beside a hub: chain ends stay in the chain
|
|
54
|
+
// a component with many leaves is a fan (one worker per bolt, one replica per zone): keep those as a column
|
|
55
|
+
const leafCount = new Map(); for (const p of leafOf.values()) leafCount.set(p, (leafCount.get(p) || 0) + 1);
|
|
56
|
+
for (const [leaf, p] of [...leafOf]) if (leafCount.get(p) > 2) leafOf.delete(leaf);
|
|
57
|
+
const core = ids.filter((id) => !leafOf.has(id));
|
|
58
|
+
const roots = core.filter((id) => !edges.some(([a, b]) => b === id && core.includes(a) && a !== id));
|
|
59
|
+
for (const id of roots.length ? roots : [core[0]]) bfs(id);
|
|
60
|
+
for (const id of core) if (!rank.has(id)) bfs(id);
|
|
61
|
+
for (const [leaf, p] of leafOf) rank.set(leaf, rank.get(p));
|
|
62
|
+
// ranks may have gaps once leaves are pulled in: compact them
|
|
63
|
+
const used = [...new Set(core.map((id) => rank.get(id)))].sort((a, b) => a - b), remap = new Map(used.map((r, i) => [r, i]));
|
|
64
|
+
for (const id of ids) rank.set(id, remap.get(rank.get(id)) ?? 0);
|
|
65
|
+
|
|
66
|
+
// columns, ordered by first appearance, then two barycenter sweeps to untangle the links
|
|
67
|
+
const cols = [];
|
|
68
|
+
for (const id of core) (cols[rank.get(id)] ||= []).push(id);
|
|
69
|
+
const preds = new Map(ids.map((id) => [id, []]));
|
|
70
|
+
for (const [a, b] of edges) if (preds.has(b) && nodes.has(a) && a !== b) preds.get(b).push(a);
|
|
71
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
72
|
+
for (let c = 1; c < cols.length; c++) {
|
|
73
|
+
if (!cols[c]) continue;
|
|
74
|
+
const pos = new Map(); (cols[c - 1] || []).forEach((id, i) => pos.set(id, i));
|
|
75
|
+
const bary = (id) => { const p = preds.get(id).filter((x) => pos.has(x)); return p.length ? p.reduce((s, x) => s + pos.get(x), 0) / p.length : Infinity; };
|
|
76
|
+
cols[c] = [...cols[c]].sort((a, b) => bary(a) - bary(b));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const [leaf, p] of leafOf) { const col = cols[rank.get(p)]; col.splice(col.indexOf(p) + 1, 0, leaf); }
|
|
80
|
+
|
|
81
|
+
// spacing from the largest object: column step leaves room for a link label between objects;
|
|
82
|
+
// slot step leaves room for the object height, its name plate and pills
|
|
83
|
+
const big = Math.max(...ids.map((id) => sizeOf(nodes.get(id)[0])));
|
|
84
|
+
const R = big + 3.5, S = big + 5.5; // ≈ 210 px between columns, 133 px between rows (object + name plate) for s = 4
|
|
85
|
+
// Long flows wrap into bands of ≤ MAX_COLS columns, laid out as a serpentine: the next band runs
|
|
86
|
+
// back right → left just below, so the link that crosses bands is short and vertical, and the
|
|
87
|
+
// whole picture stays close to the stage's proportions instead of one thin, tiny row.
|
|
88
|
+
// Columns per band: pick the wrap that gives the largest zoom on a 16:10 stage (screen px:
|
|
89
|
+
// a column step is 28·R wide, a row step 14·S tall).
|
|
90
|
+
const n = cols.length;
|
|
91
|
+
const slotsOf = (per) => Array.from({ length: Math.ceil(n / per) }, (_, b) => Math.max(1, ...cols.slice(b * per, b * per + per).map((c) => c?.length || 0)));
|
|
92
|
+
const zoomOf = (per) => { const sl = slotsOf(per); const w = (per - 1) * 28 * R + 180, h = (sl.reduce((a, v) => a + v, 0) + 0.6 * (sl.length - 1) - 1) * 14 * S + 200; return Math.min(1440 / w, 900 / h); };
|
|
93
|
+
let per = Math.min(n, MAX_COLS);
|
|
94
|
+
for (let p = 2; p <= Math.min(n, MAX_COLS); p++) if (zoomOf(p) > zoomOf(per) + 1e-9) per = p;
|
|
95
|
+
const bands = Math.ceil(n / per), bandSlots = slotsOf(per);
|
|
96
|
+
// columns are top-aligned in their band: the main path runs along one line, fans and leaves hang below
|
|
97
|
+
const bandTop = []; let acc = 0;
|
|
98
|
+
for (let b = 0; b < bands; b++) { bandTop.push(acc); acc += bandSlots[b] + 0.6; }
|
|
99
|
+
cols.forEach((col, c) => {
|
|
100
|
+
if (!col) return;
|
|
101
|
+
const b = Math.floor(c / per), i = c % per, column = b % 2 ? per - 1 - i : i;
|
|
102
|
+
col.forEach((id, j) => {
|
|
103
|
+
const k = bandTop[b] + j;
|
|
104
|
+
const x = Math.round((column * R + k * S) * 10) / 10, y = Math.round((column * R - k * S) * 10) / 10;
|
|
105
|
+
for (const o of nodes.get(id)) { o.x = x; o.y = y; }
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
// links between auto-placed entities read best as straight lines between the columns
|
|
109
|
+
for (const [a, b, l] of edges) if (nodes.has(a) && nodes.has(b) && !l.pts && !l.via) l.via = 'straight';
|
|
110
|
+
return ids;
|
|
111
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// Load + resolve an authored course into the fully-expanded runtime shape.
|
|
2
|
+
// Authoring conveniences handled here (see references/schema.md):
|
|
3
|
+
// • defs (course- or lesson-level) + `use` / string references for entities & links
|
|
4
|
+
// • steps inherit the previous step's scene and metrics (null removes; scene.reset starts fresh)
|
|
5
|
+
// • `at: [col,row]` screen-aligned placement, `size` for zones/crowds
|
|
6
|
+
// • links without `pts` are auto-routed along iso axes (`via: "x" | "y" | "straight"`)
|
|
7
|
+
// • string shorthands: tags ["text"], label "A\nB", route "linkId", body "single paragraph"
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
11
|
+
import { LOOKS } from '../../assets/runtime/looks.js';
|
|
12
|
+
import { autoLayout } from './layout.mjs';
|
|
13
|
+
|
|
14
|
+
// Course-level defs merged with a lesson's (or inside's) own, as copies: auto layout writes positions
|
|
15
|
+
// into them, and one lesson's layout must not leak into another's.
|
|
16
|
+
const ownDefs = (g, own = {}) => ({
|
|
17
|
+
entities: Object.fromEntries(Object.entries({ ...g.entities, ...(own.entities || {}) }).map(([k, v]) => [k, { ...v }])),
|
|
18
|
+
links: Object.fromEntries(Object.entries({ ...g.links, ...(own.links || {}) }).map(([k, v]) => [k, { ...v }])),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
export const LOOK_NAMES = ['box', ...Object.keys(LOOKS)];
|
|
22
|
+
|
|
23
|
+
export async function loadCourse(file) {
|
|
24
|
+
const abs = path.resolve(file);
|
|
25
|
+
if (/\.(mjs|js)$/.test(abs)) return (await import(pathToFileURL(abs).href)).default;
|
|
26
|
+
return JSON.parse(fs.readFileSync(abs, 'utf8'));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
|
|
30
|
+
const clone = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v)));
|
|
31
|
+
export const fromColRow = (col, row) => [col + row, col - row];
|
|
32
|
+
export const ENTITY_TYPES = ['block', 'device', 'db', 'crowd', 'queue', 'zone', 'ghost', 'panel'];
|
|
33
|
+
export const PACKET_KINDS = ['req', 'res', 'slow', 'heavy', 'mine', 'write', 'kill', 'msg', 'poison', 'push', 'empty', 'ping', 'retry', 'event'];
|
|
34
|
+
export const CHAPTERS = ['setup', 'problem', 'technique', 'solution', 'tradeoff', 'insight', 'recap', 'case',
|
|
35
|
+
'overview', 'component', 'flow', 'data', 'integration', 'failure', 'decision', 'risk', 'proposal',
|
|
36
|
+
'context', 'motivation', 'alternative', 'consequence', 'incident', 'migration', 'milestone', 'learning'];
|
|
37
|
+
export const SOURCE_KINDS = ['adr', 'rfc', 'session', 'commit', 'pr', 'issue', 'incident', 'postmortem', 'doc', 'chat', 'meeting', 'metric', 'link'];
|
|
38
|
+
export const LINK_STYLES = ['solid', 'dashed', 'off', 'beat', 'cut', 'hot'];
|
|
39
|
+
|
|
40
|
+
function centerOf(e) {
|
|
41
|
+
if (e.type === 'crowd' || e.type === 'zone') return [(e.x0 + e.x1) / 2, (e.y0 + e.y1) / 2];
|
|
42
|
+
return [e.x, e.y];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function resolveCourse(src, { baseDir = process.cwd() } = {}) {
|
|
46
|
+
const errors = [], warnings = [];
|
|
47
|
+
const err = (p, m) => errors.push(`${p}: ${m}`), warn = (p, m) => warnings.push(`${p}: ${m}`);
|
|
48
|
+
const course = clone(src);
|
|
49
|
+
course.meta ||= {};
|
|
50
|
+
course.meta.id ||= String(course.meta.title || 'course').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
|
51
|
+
const gdefs = { entities: {}, links: {}, ...(course.defs || {}) };
|
|
52
|
+
const story = course.meta.mode === 'story';
|
|
53
|
+
const docs = course.meta.mode === 'docs' || story;
|
|
54
|
+
if (course.meta.mode && !['course', 'docs', 'story'].includes(course.meta.mode)) warn('meta.mode', `unknown mode "${course.meta.mode}" (use "course", "docs" or "story")`);
|
|
55
|
+
const chapters = [...CHAPTERS, ...Object.keys(course.meta.chapters || {})];
|
|
56
|
+
|
|
57
|
+
// lessons may be an array or a map
|
|
58
|
+
const lessonList = Array.isArray(course.lessons) ? course.lessons : Object.entries(course.lessons || {}).map(([id, l]) => ({ id, ...l }));
|
|
59
|
+
const lessons = {};
|
|
60
|
+
for (const l of lessonList) { if (!l.id) err('lessons[]', 'lesson without id'); else lessons[l.id] = l; }
|
|
61
|
+
|
|
62
|
+
// modules: lessons can be ids or {id,title}
|
|
63
|
+
if (!Array.isArray(course.modules) || !course.modules.length) {
|
|
64
|
+
course.modules = [{ id: 'main', num: '01', title: course.meta.title || 'Lessons', color: 'sand', lessons: Object.keys(lessons) }];
|
|
65
|
+
}
|
|
66
|
+
course.modules.forEach((m, mi) => {
|
|
67
|
+
m.id ||= `m${mi + 1}`; m.num ??= String(mi + 1).padStart(2, '0');
|
|
68
|
+
m.lessons = (m.lessons || []).map((x) => (typeof x === 'string' ? { id: x, title: lessons[x]?.title || x } : { title: lessons[x.id]?.title || x.id, ...x }));
|
|
69
|
+
});
|
|
70
|
+
const listed = new Set(course.modules.flatMap((m) => m.lessons.map((l) => l.id)));
|
|
71
|
+
for (const id of Object.keys(lessons)) if (!listed.has(id)) warn(`lessons.${id}`, 'not listed in any module — it will not appear in the sidebar');
|
|
72
|
+
|
|
73
|
+
// Steps resolution (shared by lessons and by native `inside` drill-downs).
|
|
74
|
+
function resolveSteps(stepList, defs, metricKeys, P, depth = 0) {
|
|
75
|
+
let prevScene = { entities: {}, links: {}, flows: [] }, prevMetrics = Object.fromEntries(metricKeys.map((k) => [k, null]));
|
|
76
|
+
return stepList.map((st, si) => {
|
|
77
|
+
const SP = `${P}.steps[${si}]`;
|
|
78
|
+
const s = { ...st };
|
|
79
|
+
if (typeof s.body === 'string') s.body = [s.body];
|
|
80
|
+
s.body ||= [];
|
|
81
|
+
if (!s.title) err(SP, 'missing title');
|
|
82
|
+
if (!s.short) warn(SP, 'missing `short` (timeline label) — using title');
|
|
83
|
+
s.short ||= String(s.title || '').replace(/<[^>]+>/g, '').slice(0, 14);
|
|
84
|
+
if (s.short.length > 14) warn(SP, `short "${s.short}" is ${s.short.length} chars — keep ≤ 14 so the timeline stays readable`);
|
|
85
|
+
if (s.chapter && !chapters.includes(s.chapter)) warn(SP, `unknown chapter "${s.chapter}" (use ${chapters.join(', ')} or declare it in meta.chapters)`);
|
|
86
|
+
const words = s.body.join(' ').replace(/<[^>]+>/g, '').split(/\s+/).filter(Boolean).length;
|
|
87
|
+
if (words > 90) warn(SP, `body has ${words} words — aim for ≤ 70 (two short paragraphs)`);
|
|
88
|
+
if (s.callout && !['insight', 'tip', 'warn', 'next'].includes(s.callout.kind || 'insight')) warn(SP, `callout.kind "${s.callout.kind}" unknown`);
|
|
89
|
+
if (s.sources) s.sources = s.sources.map((x) => (typeof x === 'string' ? { label: x } : x));
|
|
90
|
+
for (const [k, x] of (s.sources || []).entries()) if (x.kind && !SOURCE_KINDS.includes(x.kind)) warn(`${SP}.sources[${k}]`, `unknown kind "${x.kind}" (use ${SOURCE_KINDS.join(', ')})`);
|
|
91
|
+
if (s.decision) {
|
|
92
|
+
if (!s.decision.decision) err(`${SP}.decision`, 'needs `decision` (what was decided)');
|
|
93
|
+
if (!s.decision.context) warn(`${SP}.decision`, 'no `context` — say what motivated it');
|
|
94
|
+
if (typeof s.decision.alternatives === 'string') s.decision.alternatives = [s.decision.alternatives];
|
|
95
|
+
}
|
|
96
|
+
if (story && depth === 0 && (s.decision || ['decision', 'motivation', 'incident'].includes(s.chapter)) && !(s.sources || []).length)
|
|
97
|
+
warn(SP, 'story step without `sources` — cite where this comes from (ADR, RFC, PR, session…) or say in the text that it is inferred');
|
|
98
|
+
if (story && depth === 0 && !s.date) warn(SP, 'story step without `date` (shown under the timeline label)');
|
|
99
|
+
|
|
100
|
+
// metrics inherit
|
|
101
|
+
const m = { ...prevMetrics, ...(s.metrics || {}) };
|
|
102
|
+
for (const k of Object.keys(s.metrics || {})) if (!metricKeys.includes(k)) warn(`${SP}.metrics.${k}`, 'not listed in lesson.metrics — it will not be shown');
|
|
103
|
+
s.metrics = m; prevMetrics = m;
|
|
104
|
+
|
|
105
|
+
// scene inherit
|
|
106
|
+
const raw = s.scene || {};
|
|
107
|
+
const base = raw.reset || si === 0 ? { entities: {}, links: {}, flows: [] } : clone(prevScene);
|
|
108
|
+
const ents = { ...base.entities };
|
|
109
|
+
for (const [id, v] of Object.entries(raw.entities || {})) {
|
|
110
|
+
const EP = `${SP}.scene.entities.${id}`;
|
|
111
|
+
if (v === null) { delete ents[id]; continue; }
|
|
112
|
+
let e;
|
|
113
|
+
if (typeof v === 'string') { if (!defs.entities[v]) { err(EP, `unknown entity def "${v}"`); continue; } e = clone(defs.entities[v]); }
|
|
114
|
+
else if (v.use) { if (!defs.entities[v.use]) { err(EP, `unknown entity def "${v.use}"`); continue; } const { use, ...rest } = v; e = { ...clone(defs.entities[use]), ...rest }; }
|
|
115
|
+
else if (ents[id] && (v.patch || !v.type)) { const { patch, ...rest } = v; e = { ...ents[id], ...rest }; } // patch: tweak the inherited entity
|
|
116
|
+
else e = clone(v);
|
|
117
|
+
if (!e.type) e.type = 'block';
|
|
118
|
+
if (!ENTITY_TYPES.includes(e.type)) { err(EP, `unknown type "${e.type}" (use ${ENTITY_TYPES.join(', ')})`); continue; }
|
|
119
|
+
if (Array.isArray(e.at)) { const [x, y] = fromColRow(e.at[0], e.at[1]); e.x = x; e.y = y; delete e.at; }
|
|
120
|
+
if ((e.type === 'zone' || e.type === 'crowd') && e.x0 === undefined) {
|
|
121
|
+
if (e.x === undefined || !e.size) { err(EP, `${e.type} needs x0,x1,y0,y1 or at/x,y + size:[d,w]`); continue; }
|
|
122
|
+
const [d, w] = e.size; e.x0 = e.x - d / 2; e.x1 = e.x + d / 2; e.y0 = e.y - w / 2; e.y1 = e.y + w / 2; delete e.size; delete e.x; delete e.y;
|
|
123
|
+
}
|
|
124
|
+
if (e.type !== 'panel' && e.type !== 'zone' && e.type !== 'crowd' && (typeof e.x !== 'number' || typeof e.y !== 'number')) { err(EP, 'needs numeric x,y (or at:[col,row])'); continue; }
|
|
125
|
+
if (e.look != null) {
|
|
126
|
+
if (e.type !== 'block' && e.type !== 'db') { warn(EP, `look is only used on block and db (ignored on ${e.type})`); delete e.look; }
|
|
127
|
+
else if (!LOOK_NAMES.includes(e.look)) { err(EP, `unknown look "${e.look}" (use ${LOOK_NAMES.join(', ')})`); continue; }
|
|
128
|
+
}
|
|
129
|
+
if (e.type === 'block' && typeof e.label === 'string') e.label = e.label.split('\n');
|
|
130
|
+
if (e.type === 'block') { // text is drawn on the block face: keep it inside
|
|
131
|
+
const size = Math.min(e.s ?? 4, e.d ?? e.s ?? 4, e.w ?? e.s ?? 4), maxL = Math.floor(size * 3.3), maxS = Math.floor(size * 4.2);
|
|
132
|
+
for (const line of e.label || []) if (String(line).length > maxL) warn(EP, `label line "${line}" is ${String(line).length} chars; a block of size ${size} fits ~${maxL} — shorten, split in 2 lines, or raise s`);
|
|
133
|
+
if (e.sub && String(e.sub).length > maxS) warn(EP, `sub "${e.sub}" is ${String(e.sub).length} chars; fits ~${maxS} on this block`);
|
|
134
|
+
}
|
|
135
|
+
if (e.tags) e.tags = e.tags.map((t) => (typeof t === 'string' ? { text: t } : t));
|
|
136
|
+
if (e.type === 'panel') { e.lines ||= []; e.bars ||= []; if (!e.title) warn(EP, 'panel without title'); }
|
|
137
|
+
if (e.inside != null) {
|
|
138
|
+
if (e.type === 'panel' || e.type === 'zone' || e.type === 'queue') { warn(EP, `inside is ignored on ${e.type}`); delete e.inside; }
|
|
139
|
+
else if (typeof e.inside === 'string') { if (!useInside(e.inside, `${EP}.inside`, depth)) delete e.inside; }
|
|
140
|
+
else e.inside = registerInside(e.inside, `${EP}.inside`, depth, e);
|
|
141
|
+
}
|
|
142
|
+
ents[id] = e;
|
|
143
|
+
}
|
|
144
|
+
const panels = Object.entries(ents).filter(([, e]) => e.type === 'panel');
|
|
145
|
+
if (panels.length > 1) warn(SP, `${panels.length} panels in one scene — only one card is docked; keep one`);
|
|
146
|
+
|
|
147
|
+
const links = { ...base.links };
|
|
148
|
+
for (const [id, v] of Object.entries(raw.links || {})) {
|
|
149
|
+
const LP = `${SP}.scene.links.${id}`;
|
|
150
|
+
if (v === null) { delete links[id]; continue; }
|
|
151
|
+
let l;
|
|
152
|
+
if (typeof v === 'string') { if (!defs.links[v]) { err(LP, `unknown link def "${v}"`); continue; } l = clone(defs.links[v]); }
|
|
153
|
+
else if (v.use) { if (!defs.links[v.use]) { err(LP, `unknown link def "${v.use}"`); continue; } const { use, ...rest } = v; l = { ...clone(defs.links[use]), ...rest }; }
|
|
154
|
+
else if (links[id] && (v.patch || !v.from)) { const { patch, ...rest } = v; l = { ...links[id], ...rest }; if (rest.to || rest.via) delete l.pts; }
|
|
155
|
+
else l = clone(v);
|
|
156
|
+
links[id] = l;
|
|
157
|
+
}
|
|
158
|
+
// validate & auto-route links against the final entity set
|
|
159
|
+
for (const [id, l] of Object.entries(links)) {
|
|
160
|
+
const LP = `${SP}.scene.links.${id}`;
|
|
161
|
+
if (!l.from || !ents[l.from]) { err(LP, `from "${l.from}" is not an entity in this step`); delete links[id]; continue; }
|
|
162
|
+
if (l.to && !ents[l.to]) { err(LP, `to "${l.to}" is not an entity in this step`); delete links[id]; continue; }
|
|
163
|
+
if (ents[l.from].type === 'panel' || (l.to && ents[l.to].type === 'panel')) { err(LP, 'links cannot attach to a panel'); delete links[id]; continue; }
|
|
164
|
+
l.heads ||= 'end';
|
|
165
|
+
if (l.style && !LINK_STYLES.includes(l.style)) warn(LP, `unknown style "${l.style}"`);
|
|
166
|
+
if (!l.pts) {
|
|
167
|
+
if (!l.to) { err(LP, 'needs `to` or explicit `pts`'); delete links[id]; continue; }
|
|
168
|
+
const a = centerOf(ents[l.from]), b = centerOf(ents[l.to]), via = l.via || 'x';
|
|
169
|
+
const aligned = Math.abs(a[0] - b[0]) < 1e-6 || Math.abs(a[1] - b[1]) < 1e-6;
|
|
170
|
+
l.pts = via === 'straight' || aligned ? [l.from, l.to] : via === 'y' ? [l.from, [l.from, l.to], l.to] : [l.from, [l.to, l.from], l.to];
|
|
171
|
+
}
|
|
172
|
+
delete l.via;
|
|
173
|
+
if (l.label && String(l.label).length > 30) warn(LP, `label is ${String(l.label).length} chars — keep ≤ 28 or use "\\n"`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
let flows = raw.flows !== undefined ? clone(raw.flows) : base.flows;
|
|
177
|
+
flows = (flows || []).map((f, fi) => {
|
|
178
|
+
const FP = `${SP}.scene.flows[${fi}]`;
|
|
179
|
+
if (typeof f.route === 'string') f.route = [f.route];
|
|
180
|
+
const paths = f.routes ? f.routes.map((r) => (typeof r.path === 'string' ? (r.path = [r.path]) : r.path)) : [f.route || []];
|
|
181
|
+
for (const p of paths) for (const seg of p) for (const lid2 of [].concat(seg)) if (!links[lid2]) err(FP, `route uses link "${lid2}" which does not exist in this step`);
|
|
182
|
+
if (f.kind && !PACKET_KINDS.includes(f.kind)) warn(FP, `unknown packet kind "${f.kind}"`);
|
|
183
|
+
return f;
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
const scene = { entities: ents, links, flows };
|
|
187
|
+
s.scene = scene; prevScene = scene;
|
|
188
|
+
return s;
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// `inside`: what you see when clicking an entity. Native sub-diagram (steps/scene) or an embedded figure (html/svg file,
|
|
193
|
+
// e.g. built with the anatomy skill). Registered once in course.insides; entities keep only the key.
|
|
194
|
+
const authoredInsides = course.insides || {};
|
|
195
|
+
const insides = {}, insideByContent = new Map();
|
|
196
|
+
function resolveInside(obj, IP, depth) {
|
|
197
|
+
if (depth > 2) { err(IP, 'inside nested more than 2 levels'); return null; }
|
|
198
|
+
const out = { title: obj.title || '', summary: obj.summary || '' };
|
|
199
|
+
const read = (f, key) => {
|
|
200
|
+
const abs = path.resolve(baseDir, f);
|
|
201
|
+
if (!fs.existsSync(abs)) { err(`${IP}.${key}`, `file not found: ${f} (paths are relative to the course file)`); return null; }
|
|
202
|
+
return fs.readFileSync(abs, 'utf8');
|
|
203
|
+
};
|
|
204
|
+
if ([obj.html, obj.svg, obj.steps || obj.scene].filter(Boolean).length > 1) warn(IP, 'use only one of html, svg, steps/scene (html wins, then svg)');
|
|
205
|
+
if (obj.html) { out.kind = 'html'; out.html = read(obj.html, 'html'); if (obj.htmlDark) out.htmlDark = read(obj.htmlDark, 'htmlDark'); out.height = obj.height || null; if (out.html == null) return null; }
|
|
206
|
+
else if (obj.svg) { out.kind = 'svg'; out.svg = read(obj.svg, 'svg'); if (out.svg == null) return null; }
|
|
207
|
+
else if (obj.steps || obj.scene) {
|
|
208
|
+
out.kind = 'scene';
|
|
209
|
+
const idefs = ownDefs(gdefs, obj.defs);
|
|
210
|
+
const raw = obj.steps || [{ title: obj.title || '', short: '1', scene: obj.scene, body: obj.body || [] }];
|
|
211
|
+
autoLayout(idefs.entities, raw, idefs.links);
|
|
212
|
+
out.metrics = obj.metrics || [];
|
|
213
|
+
out.legend = obj.legend || null;
|
|
214
|
+
out.steps = resolveSteps(raw, idefs, out.metrics, IP, depth + 1);
|
|
215
|
+
if (raw.length > 8) warn(IP, `${raw.length} steps inside — keep a drill-down short (≤ 6)`);
|
|
216
|
+
} else { err(IP, 'needs one of: steps, scene, html, svg'); return null; }
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
function useInside(key, IP, depth) {
|
|
220
|
+
if (insides[key]) return true;
|
|
221
|
+
if (!authoredInsides[key]) { err(IP, `unknown inside "${key}" (define it in course.insides)`); return false; }
|
|
222
|
+
const r = resolveInside(authoredInsides[key], `insides.${key}`, depth);
|
|
223
|
+
if (r) insides[key] = r;
|
|
224
|
+
return !!r;
|
|
225
|
+
}
|
|
226
|
+
function registerInside(obj, IP, depth, e) {
|
|
227
|
+
const sig = JSON.stringify(obj);
|
|
228
|
+
if (insideByContent.has(sig)) return insideByContent.get(sig);
|
|
229
|
+
const base = String(obj.id || (Array.isArray(e.label) ? e.label.join('-') : e.label) || 'inside').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'inside';
|
|
230
|
+
let key = base, n = 2; while (insides[key] || authoredInsides[key]) key = `${base}-${n++}`;
|
|
231
|
+
insideByContent.set(sig, key);
|
|
232
|
+
const r = resolveInside(obj, IP, depth);
|
|
233
|
+
if (r) insides[key] = r;
|
|
234
|
+
return r ? key : undefined;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const out = {};
|
|
238
|
+
for (const [lid, L] of Object.entries(lessons)) {
|
|
239
|
+
const P = `lessons.${lid}`;
|
|
240
|
+
const defs = ownDefs(gdefs, L.defs);
|
|
241
|
+
if (!L.title) err(P, 'missing title');
|
|
242
|
+
if (!Array.isArray(L.steps) || !L.steps.length) { err(P, 'needs at least one step'); continue; }
|
|
243
|
+
autoLayout(defs.entities, L.steps, defs.links); // entities without x/y are placed from the links
|
|
244
|
+
if (L.steps.length < 4 && !docs) warn(P, `only ${L.steps.length} steps — lessons read best with 6–12`);
|
|
245
|
+
if (L.steps.length > 14) warn(P, `${L.steps.length} steps — consider splitting the lesson (max ~12)`);
|
|
246
|
+
const metricKeys = L.metrics || [];
|
|
247
|
+
const steps = resolveSteps(L.steps, defs, metricKeys, P);
|
|
248
|
+
(L.goals || []).forEach((g, gi) => { if (g.step >= steps.length || g.step < 0) err(`${P}.goals[${gi}]`, `step ${g.step} out of range (0-based, < ${steps.length})`); });
|
|
249
|
+
if (story) { /* chronological: any opening works */ }
|
|
250
|
+
else if (docs) {
|
|
251
|
+
if (steps[0].chapter && steps[0].chapter !== 'overview') warn(`${P}.steps[0]`, 'architecture tours read best when step 1 is an "overview" of the whole view');
|
|
252
|
+
} else {
|
|
253
|
+
if (steps[0].chapter && !['problem', 'setup', 'case'].includes(steps[0].chapter)) warn(`${P}.steps[0]`, 'lessons land best when step 1 states a problem (chapter "problem" or "setup")');
|
|
254
|
+
if (steps.at(-1).chapter && steps.at(-1).chapter !== 'recap') warn(`${P}.steps[${steps.length - 1}]`, 'consider ending with a "recap" step');
|
|
255
|
+
}
|
|
256
|
+
if (docs) { // architecture tours & stories: readers click every box, so every main component should open
|
|
257
|
+
const bare = new Set();
|
|
258
|
+
for (const st of steps) for (const [id, e] of Object.entries(st.scene.entities)) if (['block', 'db', 'device'].includes(e.type) && !e.inside && !e.dead) bare.add(id);
|
|
259
|
+
if (bare.size) warn(P, `components without \`inside\`: ${[...bare].join(', ')} — in docs/story mode give every main component a drill-down (references/inside.md)`);
|
|
260
|
+
}
|
|
261
|
+
const { defs: _d, ...rest } = L;
|
|
262
|
+
out[lid] = { ...rest, metrics: metricKeys, steps };
|
|
263
|
+
}
|
|
264
|
+
course.lessons = out;
|
|
265
|
+
course.insides = insides;
|
|
266
|
+
delete course.defs;
|
|
267
|
+
if (!Object.keys(out).length) err('lessons', 'no playable lessons');
|
|
268
|
+
return { course, errors, warnings };
|
|
269
|
+
}
|