Repository Public
1/**2 * Pure models behind the interactive diagrams. Each function computes what the diagram shows, so the3 * accuracy of a figure can be unit-tested independently of its drawing.4 */56/* ---- 1. Tokenisation (three illustrative splitters) ---- */78export type Splitter = "mots" | "sous-mots" | "caracteres";910/** A small, fixed vocabulary of frequent French fragments. Illustrative: it belongs to no real model. */11export const PIECES = [12 "tion", "ment", "ique", "eur", "eux", "ent", "ant", "ais", "ait", "ons", "ez", "er", "ir", "re", "es", "le", "la", "les", "de", "des", "du", "un", "une", "et", "en", "est", "que", "qui", "qu",13 "mod", "èle", "èles", "lang", "age", "dé", "coup", "texte", "jet", "on", "con", "com", "pré", "pro", "sur", "sous", "dans", "pour", "par", "pas", "plus", "tout", "très", "bien", "in", "im", "an", "au", "aux",14 "ch", "ou", "oi", "ai", "ei", "eau", "ien", "gn", "ph", "th", "tr", "pr", "br", "cr", "gr", "pl", "bl", "cl", "st", "sp", "agent", "outil", "mot", "nombre", "chat", "dort",15].sort((a, b) => b.length - a.length);1617const WORD_RE = /[\p{L}\p{N}]+|[^\s\p{L}\p{N}]/gu;1819/** Splits text with one of three teaching rules. « ▁ » marks a token that starts a new word. */20export function tokenize(text: string, method: Splitter): string[] {21 const words = text.match(WORD_RE) ?? [];22 if (method === "mots") return words;23 if (method === "caracteres") return [...text].filter((c) => !/\s/.test(c));24 const out: string[] = [];25 for (const word of words) {26 let rest = word.toLowerCase(), first = true;27 while (rest) {28 const piece = PIECES.find((p) => rest.startsWith(p)) ?? [...rest][0]!;29 out.push(`${first ? "▁" : ""}${piece}`);30 rest = rest.slice(piece.length);31 first = false;32 }33 }34 return out;35}3637/* ---- 2. Attention (single head, scaled dot product, optional causal mask) ---- */3839export type Vec = [number, number];40export const dot = (a: Vec, b: Vec) => a[0] * b[0] + a[1] * b[1];4142export function softmax(scores: number[]): number[] {43 const finite = scores.filter((s) => s !== -Infinity);44 if (!finite.length) return scores.map(() => 0);45 const max = Math.max(...finite), exps = scores.map((s) => (s === -Infinity ? 0 : Math.exp(s - max))), sum = exps.reduce((a, b) => a + b, 0);46 return exps.map((e) => e / sum);47}4849export interface AttentionRow { scores: number[]; masked: boolean[]; weights: number[]; output: Vec }5051/** Attention of token `i` over all tokens: score_j = (q_i · k_j) / √d, masked if j > i when causal, then softmax. */52export function attend(queries: Vec[], keys: Vec[], values: Vec[], i: number, causal: boolean): AttentionRow {53 const d = 2;54 const masked = keys.map((_, j) => causal && j > i);55 const scores = keys.map((k, j) => (masked[j] ? -Infinity : dot(queries[i]!, k) / Math.sqrt(d)));56 const weights = softmax(scores);57 const output: Vec = [0, 0];58 weights.forEach((w, j) => { output[0] += w * values[j]![0]; output[1] += w * values[j]![1]; });59 return { scores, masked, weights, output };60}6162/* ---- 3. Context-window budget ---- */6364export interface Budget { instructions: number; documents: number; history: number; reserve: number }65export type Truncation = "historique" | "documents" | "aucune";66export interface Allocation {67 window: number; requested: number; overflow: number; fits: boolean;68 kept: Budget; dropped: { documents: number; history: number };69 /** True when even after truncation the request cannot fit (instructions + reserve exceed the window). */70 impossible: boolean;71}7273/** What is actually sent when the request exceeds the window, under a given truncation strategy. */74export function allocate(window: number, b: Budget, strategy: Truncation): Allocation {75 const requested = b.instructions + b.documents + b.history + b.reserve, overflow = Math.max(0, requested - window);76 const kept = { ...b }, dropped = { documents: 0, history: 0 };77 let left = overflow;78 if (left > 0 && strategy !== "aucune") {79 const order: ("history" | "documents")[] = strategy === "historique" ? ["history", "documents"] : ["documents", "history"];80 for (const key of order) { const cut = Math.min(kept[key], left); kept[key] -= cut; dropped[key] += cut; left -= cut; }81 }82 return { window, requested, overflow, fits: overflow === 0, kept, dropped, impossible: left > 0 };83}8485/* ---- 8. Shell simulator ---- */8687export type FsNode = { type: "dir"; children: Record<string, FsNode> } | { type: "file"; content: string };88export interface ShellState { cwd: string[]; root: FsNode; pid: number }89export interface ShellResult { state: ShellState; stdout: string; stderr: string; code: number; argv: string[]; program: string | null; pid: number | null; builtin: boolean; changed: string | null }9091export const initialShell = (): ShellState => ({92 cwd: ["projet"], pid: 4200,93 root: { type: "dir", children: { projet: { type: "dir", children: {94 "LISEZMOI.md": { type: "file", content: "Projet d’exemple pour le shell simulé.\nAucune commande ne touche votre ordinateur." },95 "notes.txt": { type: "file", content: "jetons\ncontexte\nagent\nagent de code" },96 src: { type: "dir", children: { "calcul.py": { type: "file", content: "def somme(a, b):\n return a + b" } } },97 } } } },98});99100const clone = (n: FsNode): FsNode => (n.type === "file" ? { ...n } : { type: "dir", children: Object.fromEntries(Object.entries(n.children).map(([k, v]) => [k, clone(v)])) });101function resolvePath(cwd: string[], path: string): string[] {102 const parts = path.startsWith("/") ? [] : [...cwd];103 for (const seg of path.split("/")) { if (!seg || seg === ".") continue; if (seg === "..") parts.pop(); else parts.push(seg); }104 return parts;105}106function lookup(root: FsNode, parts: string[]): FsNode | null {107 let node: FsNode = root;108 for (const p of parts) { if (node.type !== "dir" || !node.children[p]) return null; node = node.children[p]!; }109 return node;110}111export const pathString = (parts: string[]) => `/${parts.join("/")}`;112113/** Splits a command line into words, honouring double quotes, and separates a trailing « > fichier ». */114export function parseCommand(line: string): { argv: string[]; redirect: string | null } {115 const tokens = line.match(/"[^"]*"|\S+/g)?.map((t) => (t.startsWith('"') && t.endsWith('"') && t.length > 1 ? t.slice(1, -1) : t)) ?? [];116 const at = tokens.indexOf(">");117 return at >= 0 ? { argv: tokens.slice(0, at), redirect: tokens[at + 1] ?? null } : { argv: tokens, redirect: null };118}119120export const SHELL_COMMANDS = ["pwd", "ls", "cd", "cat", "mkdir", "touch", "echo", "grep"] as const;121const BUILTINS = new Set(["cd", "pwd", "echo"]);122123/** Runs one command against the in-memory filesystem. Exit codes follow the usual conventions (0, 1, 2, 127). */124export function runCommand(state: ShellState, line: string): ShellResult {125 const { argv, redirect } = parseCommand(line.trim());126 const program = argv[0] ?? null, builtin = program !== null && BUILTINS.has(program);127 const base = { argv, program, builtin, pid: null as number | null, changed: null as string | null };128 if (!program) return { ...base, state, stdout: "", stderr: "", code: 0 };129 if (!(SHELL_COMMANDS as readonly string[]).includes(program)) return { ...base, state, stdout: "", stderr: `${program} : commande introuvable`, code: 127 };130 const root = clone(state.root);131 let next: ShellState = { ...state, root };132 let pid: number | null = null;133 if (!builtin) { pid = state.pid + 1; next = { ...next, pid }; } // an external program runs in a new process134 const fail = (stderr: string, code = 1): ShellResult => ({ ...base, pid, state: { ...state, pid: next.pid }, stdout: "", stderr, code });135 const args = argv.slice(1);136 let stdout = "", changed: string | null = null;137138 if (program === "pwd") stdout = pathString(state.cwd);139 else if (program === "echo") stdout = args.join(" ");140 else if (program === "cd") {141 const target = resolvePath(state.cwd, args[0] ?? "/projet"), node = lookup(root, target);142 if (!node) return fail(`cd : ${args[0]} : aucun dossier de ce nom`);143 if (node.type !== "dir") return fail(`cd : ${args[0]} : n’est pas un dossier`);144 next = { ...next, cwd: target };145 } else if (program === "ls") {146 const node = lookup(root, resolvePath(state.cwd, args[0] ?? "."));147 if (!node) return fail(`ls : ${args[0]} : aucun fichier ou dossier de ce nom`, 2);148 stdout = node.type === "file" ? args[0]! : Object.entries(node.children).map(([n, c]) => (c.type === "dir" ? `${n}/` : n)).sort().join("\n");149 } else if (program === "cat") {150 if (!args[0]) return fail("cat : nom de fichier manquant", 2);151 const node = lookup(root, resolvePath(state.cwd, args[0]));152 if (!node) return fail(`cat : ${args[0]} : aucun fichier de ce nom`);153 if (node.type === "dir") return fail(`cat : ${args[0]} : est un dossier`);154 stdout = node.content;155 } else if (program === "grep") {156 if (args.length < 2) return fail("grep : usage : grep motif fichier", 2);157 const node = lookup(root, resolvePath(state.cwd, args[1]!));158 if (!node || node.type !== "file") return fail(`grep : ${args[1]} : aucun fichier de ce nom`, 2);159 stdout = node.content.split("\n").filter((l) => l.includes(args[0]!)).join("\n");160 if (!stdout) return { ...base, pid, state: next, stdout: "", stderr: "", code: 1 }; // no match: exit 1, no error message161 } else if (program === "mkdir" || program === "touch") {162 if (!args[0]) return fail(`${program} : nom manquant`, 2);163 const target = resolvePath(state.cwd, args[0]), name = target.pop()!, parent = lookup(root, target);164 if (!parent || parent.type !== "dir") return fail(`${program} : ${args[0]} : dossier parent introuvable`);165 if (parent.children[name]) { if (program === "mkdir") return fail(`mkdir : ${args[0]} : existe déjà`); }166 else { parent.children[name] = program === "mkdir" ? { type: "dir", children: {} } : { type: "file", content: "" }; changed = pathString([...target, name]); }167 }168169 if (redirect !== null) {170 if (!redirect) return fail("erreur de syntaxe : nom de fichier attendu après >", 2);171 const target = resolvePath(state.cwd, redirect), name = target.pop()!, parent = lookup(root, target);172 if (!parent || parent.type !== "dir") return fail(`${redirect} : dossier parent introuvable`);173 if (parent.children[name]?.type === "dir") return fail(`${redirect} : est un dossier`);174 parent.children[name] = { type: "file", content: stdout };175 changed = pathString([...target, name]);176 stdout = "";177 }178 return { ...base, pid, state: next, stdout, stderr: "", code: 0, changed };179}180181/* ---- 9. Delegation: sequential vs parallel ---- */182183export interface DelegationInput { tasks: number[]; overhead: number; aggregation: number }184export interface DelegationResult { sequential: { time: number; cost: number }; parallel: { time: number; cost: number }; speedup: number; extraCost: number }185186/**187 * Sequential: one agent does every task in turn. Parallel: one sub-agent per task, each paying a188 * coordination overhead (briefing and report), all running at once; then the orchestrator aggregates.189 * Time is wall-clock; cost is the total work done by all agents.190 */191export function delegate({ tasks, overhead, aggregation }: DelegationInput): DelegationResult {192 const sum = tasks.reduce((a, b) => a + b, 0);193 const sequential = { time: sum + aggregation, cost: sum + aggregation };194 const parallel = { time: Math.max(...tasks.map((t) => t + overhead)) + aggregation, cost: sum + overhead * tasks.length + aggregation };195 return { sequential, parallel, speedup: sequential.time / parallel.time, extraCost: parallel.cost - sequential.cost };196}197198/* ---- 11. Git flow ---- */199200export interface Commit { id: string; branch: "main" | "fonction"; kind: "normal" | "defaut" | "correctif" | "fusion" | "annulation"; label: string }201export interface GitState {202 commits: Commit[]; branchOpen: boolean; branchFrom: number | null; pr: boolean; tests: "non lancés" | "réussis" | "échoués"; approved: boolean; merged: boolean; reverted: boolean; log: string;203}204export type GitAction = "branche" | "commit" | "commit-defaut" | "corriger" | "commit-main" | "pr" | "tests" | "approuver" | "fusionner" | "annuler" | "recommencer";205206export const initialGit = (): GitState => ({ commits: [{ id: "c1", branch: "main", kind: "normal", label: "Point de départ" }], branchOpen: false, branchFrom: null, pr: false, tests: "non lancés", approved: false, merged: false, reverted: false, log: "Dépôt créé avec un premier commit sur la branche principale." });207208const branchCommits = (s: GitState) => s.commits.filter((c) => c.branch === "fonction");209/** The branch is defective when its latest defect has not been followed by a fix. */210export const branchBroken = (s: GitState) => { const list = branchCommits(s); const lastDefect = list.map((c) => c.kind).lastIndexOf("defaut"), lastFix = list.map((c) => c.kind).lastIndexOf("correctif"); return lastDefect > lastFix; };211212export function gitAllowed(s: GitState, a: GitAction): boolean {213 switch (a) {214 case "branche": return !s.branchOpen && !s.merged;215 case "commit": case "commit-defaut": return s.branchOpen && !s.merged;216 case "corriger": return s.branchOpen && !s.merged && branchBroken(s);217 case "commit-main": return !s.merged;218 case "pr": return s.branchOpen && !s.pr && branchCommits(s).length > 0;219 case "tests": return s.pr && !s.merged;220 case "approuver": return s.pr && !s.approved && !s.merged;221 case "fusionner": return s.pr && s.tests === "réussis" && s.approved && !s.merged;222 case "annuler": return s.merged && !s.reverted;223 case "recommencer": return true;224 }225}226227export function gitStep(s: GitState, a: GitAction): GitState {228 if (a === "recommencer") return initialGit();229 if (!gitAllowed(s, a)) return { ...s, log: "Action impossible dans l’état actuel du dépôt." };230 const id = `c${s.commits.length + 1}`;231 // Any new commit on the branch invalidates earlier test results and approval: they applied to older code.232 const stale = { tests: "non lancés" as const, approved: false };233 switch (a) {234 case "branche": return { ...s, branchOpen: true, branchFrom: s.commits.filter((c) => c.branch === "main").length - 1, log: "Branche « fonction » créée à partir du dernier commit de la branche principale." };235 case "commit": return { ...s, ...stale, commits: [...s.commits, { id, branch: "fonction", kind: "normal", label: "Travail sur la fonction" }], log: `Commit ${id} ajouté sur la branche. Les tests et l’approbation sont à refaire.` };236 case "commit-defaut": return { ...s, ...stale, commits: [...s.commits, { id, branch: "fonction", kind: "defaut", label: "Changement qui casse un test" }], log: `Commit ${id} ajouté : il contient une erreur que les tests peuvent détecter.` };237 case "corriger": return { ...s, ...stale, commits: [...s.commits, { id, branch: "fonction", kind: "correctif", label: "Correction de l’erreur" }], log: `Commit ${id} : correction ajoutée. L’historique conserve l’erreur et sa correction.` };238 case "commit-main": return { ...s, commits: [...s.commits, { id, branch: "main", kind: "normal", label: "Travail d’une autre personne" }], log: `Commit ${id} ajouté sur la branche principale par quelqu’un d’autre.` };239 case "pr": return { ...s, pr: true, log: "Demande de fusion ouverte : la différence entre les deux branches peut être révisée." };240 case "tests": { const ok = !branchBroken(s); return { ...s, tests: ok ? "réussis" : "échoués", log: ok ? "Intégration continue : tous les tests réussissent." : "Intégration continue : un test échoue. La fusion reste bloquée." }; }241 case "approuver": return { ...s, approved: true, log: "Révision humaine : la différence a été lue et approuvée." };242 case "fusionner": return { ...s, merged: true, commits: [...s.commits, { id, branch: "main", kind: "fusion", label: "Fusion de la branche « fonction »" }], log: `Commit de fusion ${id} : le travail de la branche rejoint la branche principale.` };243 case "annuler": return { ...s, reverted: true, commits: [...s.commits, { id, branch: "main", kind: "annulation", label: "Annulation de la fusion" }], log: `Commit ${id} : la fusion est annulée par un nouveau commit. Rien n’est effacé de l’historique.` };244 }245}246247/* ---- 12. Evaluation ---- */248249export interface EvalCase { id: string; label: string; category: string }250export interface EvalSummary {251 total: number; passA: number; passB: number; rateA: number; rateB: number;252 regressions: string[]; fixes: string[]; stillFailing: string[];253 /** Categories with no test case at all. */254 uncovered: string[];255 /** A new version is acceptable only if it breaks nothing that worked. */256 shippable: boolean;257}258259export function summarizeEval(cases: EvalCase[], a: Record<string, boolean>, b: Record<string, boolean>, categories: string[]): EvalSummary {260 const passA = cases.filter((c) => a[c.id]).length, passB = cases.filter((c) => b[c.id]).length;261 const regressions = cases.filter((c) => a[c.id] && !b[c.id]).map((c) => c.id);262 return {263 total: cases.length, passA, passB, rateA: cases.length ? passA / cases.length : 0, rateB: cases.length ? passB / cases.length : 0,264 regressions, fixes: cases.filter((c) => !a[c.id] && b[c.id]).map((c) => c.id), stillFailing: cases.filter((c) => !a[c.id] && !b[c.id]).map((c) => c.id),265 uncovered: categories.filter((cat) => !cases.some((c) => c.category === cat)),266 shippable: regressions.length === 0,267 };268}269270/* ---- 13. Hosting: local vs API break-even ---- */271272export interface HostingInput { volume: number; apiPrice: number; hardware: number; months: number; fixedMonthly: number; capacity: number }273export interface HostingResult { api: number; local: number; breakEven: number | null; cheaper: "api" | "local" | "égal"; overCapacity: boolean }274275/** Monthly cost of each option. Volume and capacity in millions of tokens per month, prices in dollars. */276export function hosting(i: HostingInput): HostingResult {277 const api = i.volume * i.apiPrice, local = (i.months > 0 ? i.hardware / i.months : 0) + i.fixedMonthly;278 return { api, local, breakEven: i.apiPrice > 0 ? local / i.apiPrice : null, cheaper: Math.abs(api - local) < 1e-9 ? "égal" : api < local ? "api" : "local", overCapacity: i.volume > i.capacity };279}280