In this section
- Decision Record storage · stars / modular-star/decision-record.mjs lines 1–76
- Decisions storage · stars / modular-star/decisions.mjs lines 1–95
- Find Prior ingest · stars / modular-star/find-prior.mjs lines 1–31
- Functions other · stars / modular-star/functions.py lines 1–36
- Stars — Modular Star storage · stars / modular-star/lib.mjs lines 1–277
- Lines other · stars / modular-star/lines.mjs lines 1–27
- Pair Verdict transform · stars / modular-star/pair-verdict.mjs lines 1–8
Decision Record
A JavaScript module in the modular star folder of Stars.
storagestars / modular-star/decision-record.mjs · lines 1–76 of 76 · Entry point
- What it does
- It loads data. Defines opt, get. Uses libraries node:fs, node:path. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Decisions Workflow (stars).
- What it achieves
- Defines `opt` and `get`.
- Why it matters
- Run by Decisions Workflow.
- Application
- stars · modular-star · JavaScript module
- Uses
- node:fs, node:path
- Used by
- run by Decisions Workflow (workflow run)
- Produces
- opt, get
- Defines here
- opt, get
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/decision-record.mjs:1-76 · blob e2337c3c3b9ea92e77733cb87dc590c6624ada8f · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env node
// decision-record.mjs — turns a GitHub issue made from the Decision form into decisions/dNNN.json.
//
// Reads the issue body (the form renders as "### Field" headings followed by the answer), takes the next free
// number in decisions/ (never reused), writes the record in the shape of decisions/SCHEMA.md and prints its path.
// Run by .github/workflows/decisions.yml. Usage:
// ISSUE_BODY="..." ISSUE_NUMBER=12 ISSUE_URL=https://github.com/... node modular-star/decision-record.mjs --out .
// Or for a dry run from a file: node modular-star/decision-record.mjs --body body.md --out /tmp/x
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
const args = process.argv.slice(2);
const opt = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : null; };
const ROOT = opt('--out') || '.';
const body = opt('--body') ? readFileSync(opt('--body'), 'utf8') : process.env.ISSUE_BODY || '';
const issue = Number(process.env.ISSUE_NUMBER) || null;
const issueUrl = process.env.ISSUE_URL || null;
// ---------- parse the form ----------
const fields = {};
for (const m of body.matchAll(/^###\s+(.+?)\s*\r?\n([\s\S]*?)(?=^###\s|\s*$(?![\s\S]))/gm)) {
const v = m[2].trim();
fields[m[1].trim().toLowerCase()] = v === '_No response_' || v === 'None' ? '' : v;
}
const get = (...names) => { for (const n of names) if (fields[n] !== undefined && fields[n] !== '') return fields[n]; return ''; };
const record = get('record').toLowerCase();
const status = /open question/.test(record) ? 'open' : 'decided';
const typeWord = get('subject type').toLowerCase();
const type = /pair/.test(typeWord) ? 'pair' : /family/.test(typeWord) ? 'family' : /constant/.test(typeWord) ? 'constant' : 'block';
// The subject key dropdown shows "Ek · Earth km" or "family:511"; the free-text box wins when filled.
let key = get('subject key (if not in the list)', 'subject key (other)') || get('subject key');
key = key.split('·')[0].trim();
if (/^\d+$/.test(key)) key = `family:${key}`;
if (type === 'pair') key = key.split(/\s*[+,]\s*/).map((k) => (/^[A-Za-z]/.test(k) && !k.includes(':') ? `block:${k}` : k)).join('+');
else if (key && !key.includes(':')) key = `${type === 'family' ? 'family' : 'block'}:${key}`;
if (!key) { console.error('No subject key in the issue; nothing written.'); process.exit(1); }
const question = get('question');
const decision = status === 'open' ? '' : get('decision');
const rationale = get('rationale', 'why');
const evidence = get('evidence').split(/\r?\n/).map((s) => s.replace(/^[-*]\s*/, '').trim()).filter(Boolean);
const supersedes = (get('supersedes').match(/d\d{3,}/) || [])[0] || null;
const agentsMay = get('what agents may now do', 'consequences').split(/\r?\n/).map((s) => s.replace(/^[-*]\s*/, '').trim()).filter(Boolean);
if (!question) { console.error('No question in the issue; nothing written.'); process.exit(1); }
if (status === 'decided' && !decision) { console.error('Marked as a decision but the decision is empty; nothing written.'); process.exit(1); }
// ---------- next number, never reused ----------
const dir = join(ROOT, 'decisions');
mkdirSync(dir, { recursive: true });
const used = readdirSync(dir).map((f) => (f.match(/^d(\d{3,})\.json$/) || [])[1]).filter(Boolean).map(Number);
const id = `d${String((used.length ? Math.max(...used) : 0) + 1).padStart(3, '0')}`;
const keys = key.split('+');
const out = {
id,
subject: { type, key },
question, decision, rationale, evidence,
date: new Date().toISOString().slice(0, 10),
status,
...(supersedes ? { supersedes } : {}),
consequences: { settles: status === 'decided' ? keys : [], agents_may: agentsMay },
...(issue ? { source: { issue, url: issueUrl } } : {}),
};
const path = join(dir, `${id}.json`);
if (existsSync(path)) { console.error(`${path} already exists; refusing to overwrite.`); process.exit(1); }
writeFileSync(path, JSON.stringify(out, null, 2) + '\n');
// Mark the superseded record, if it is here.
if (supersedes && existsSync(join(dir, `${supersedes}.json`))) {
const old = JSON.parse(readFileSync(join(dir, `${supersedes}.json`), 'utf8'));
if (old.status !== 'superseded') { old.status = 'superseded'; old.superseded_by = id; old.date = out.date; writeFileSync(join(dir, `${supersedes}.json`), JSON.stringify(old, null, 2) + '\n'); }
}
console.log(`decisions/${id}.json`);
if (process.env.GITHUB_OUTPUT) writeFileSync(process.env.GITHUB_OUTPUT, `id=${id}\npath=decisions/${id}.json\nstatus=${status}\nkey=${key}\n`, { flag: 'a' });Decisions
A JavaScript module in the modular star folder of Stars that reads blocks. It reads JSON (`readJson`) and splits key (`splitKey`).
storagestars / modular-star/decisions.mjs · lines 1–95 of 95 · Entry point · pattern splitKey (shared by 2 files)
- What it does
- It loads blocks. Defines 7 functions or classes, including esc, readJson, splitKey, keyNode, add. Uses libraries node:fs, node:path. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file blocks.json; command-line arguments. Out: JSON file graph.json.
- Downstream impact
- Used directly by 2 files: Decisions Workflow (stars); Modular Star Workflow (stars).
- What it achieves
- Defines `esc`, `readJson`, `splitKey` and 4 more.
- Why it matters
- Run by Decisions Workflow and Modular Star Workflow.
- Application
- stars · modular-star · JavaScript module
- Uses
- Stars — Index Page (estate URL), node:fs, node:path
- Used by
- run by Decisions Workflow (workflow run), run by Modular Star Workflow (workflow run)
- Produces
- esc, readJson, splitKey, keyNode, add, wire, count
- Defines here
- esc, readJson, splitKey, keyNode, add, wire, count
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/decisions.mjs:1-95 · blob 051efd247325577f630fea0c1bf233645bd69037 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env node
// decisions.mjs — the Decisions map for the Spider dashboard.
//
// Reads every decision record (decisions/d*.json, see decisions/SCHEMA.md) and writes decisions/graph.json in the
// dashboard's shape: nodes {id, label, type, rag, reason, gh, ext}, edges {from, to, type}. Each record is one card
// (open = amber, decided = green, superseded = grey) wired to the key it concerns, using the same ids the other
// graphs use (block:Ss, family:511, block:Ek), so a decision sits on the same map as the fact it is about.
// Reads blocks/blocks.json when present for the keys' titles; runs without it.
//
// Usage: node modular-star/decisions.mjs --out . (node 24, no dependencies)
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
const args = process.argv.slice(2);
const outIdx = args.indexOf('--out');
const ROOT = outIdx >= 0 && args[outIdx + 1] ? args[outIdx + 1] : '.';
const STARS = 'https://ventusltd.github.io/stars/';
const REPO = 'https://github.com/Ventusltd/stars/blob/main/';
const RAG = { open: 'amber', decided: 'green', superseded: 'grey' };
const esc = (s) => String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
const readJson = (p) => JSON.parse(readFileSync(p, 'utf8').replace(/^/, ''));
// ---------- load ----------
const dir = join(ROOT, 'decisions');
const files = existsSync(dir) ? readdirSync(dir).filter((f) => /^d\d{3,}\.json$/.test(f)).sort() : [];
const records = files.map((f) => ({ ...readJson(join(dir, f)), _file: f }));
const blocks = existsSync(join(ROOT, 'blocks/blocks.json')) ? readJson(join(ROOT, 'blocks/blocks.json')).blocks || [] : [];
const bySymbol = new Map(blocks.map((b) => [b.symbol, b]));
// ---------- keys ----------
// A subject key is one map id or a pair joined by '+'. Returns the individual map ids.
const splitKey = (key) => String(key || '').split('+').map((k) => k.trim()).filter(Boolean);
function keyNode(id) {
const [kind, ref] = id.split(':');
if (kind === 'block') {
const b = bySymbol.get(ref);
return {
id, label: b ? `${b.symbol} · ${b.title}` : `${ref} · block`, type: b?.kind || 'block',
rag: b?.state === 'UNSETTLED' ? 'amber' : 'green',
reason: b ? esc(b.description) : 'A block of the periodic table.',
gh: b?.files?.[0] ? `https://github.com/${b.files[0].repo}/blob/${b.files[0].commit || 'main'}/${b.files[0].path}` : null,
ext: `${STARS}table.html?block=${encodeURIComponent(ref)}`,
};
}
if (kind === 'family') {
return { id, label: `family ${ref}`, type: 'family', rag: 'green', reason: `Function family ${ref}: every copy of one function, under its permanent number.`,
gh: null, ext: `${STARS}code.html?family=${encodeURIComponent(ref)}` };
}
return { id, label: id, type: 'key', rag: 'grey', reason: 'A key named by a decision record.', gh: null, ext: `${STARS}table.html` };
}
// ---------- graph ----------
const nodes = [], edges = [], ids = new Set();
function add(node) { if (!ids.has(node.id)) { ids.add(node.id); nodes.push(node); } return node.id; }
function wire(from, to, type) { if (ids.has(from) && ids.has(to) && from !== to) edges.push({ from, to, type }); }
const count = (s) => records.filter((r) => r.status === s).length;
add({
id: 'decisions', label: 'Decisions', type: 'whole', rag: count('open') ? 'amber' : 'green',
reason: `${records.length} decision records: ${count('open')} open, ${count('decided')} decided, ${count('superseded')} superseded. `
+ 'A decided record is permission; an open record is a question. Each record is wired to the block, constant or family it concerns.',
gh: REPO + 'decisions/README.md', ext: 'https://github.com/Ventusltd/stars/issues/new?template=decision.yml',
});
// Records first, in id order, so the FOCUS list reads like a register.
for (const r of records) {
const status = RAG[r.status] ? r.status : 'open';
const body = status === 'open'
? `<b>Question.</b> ${esc(r.question)}${r.rationale ? `<br>${esc(r.rationale)}` : ''}`
: `<b>Question.</b> ${esc(r.question)}<br><b>Decision.</b> ${esc(r.decision)}${r.rationale ? `<br><b>Why.</b> ${esc(r.rationale)}` : ''}`;
const may = r.consequences?.agents_may?.length ? `<br><small>Agents may: ${r.consequences.agents_may.map(esc).join(' ')}</small>` : '';
const sup = r.supersedes ? `<br><small>Supersedes ${esc(r.supersedes)}.</small>` : '';
const ev = (r.evidence || []).length ? `<br><small>Evidence: ${(r.evidence || []).slice(0, 4).map((e) => `<a href="${esc(e)}">${esc(e.replace(/^https?:\/\/(www\.)?/, '').slice(0, 60))}</a>`).join(' · ')}</small>` : '';
add({
id: `decision:${r.id}`, label: `${r.id} · ${r.subject?.key || '?'} · ${status}`, type: 'decision', rag: RAG[status],
reason: `${body}${sup}${may}${ev}<br><small>${esc(r.date || '')} · ${esc(r.subject?.type || '')}</small>`,
gh: REPO + 'decisions/' + r._file, ext: r.source?.url || `${STARS}decisions/${r._file}`,
});
wire('decisions', `decision:${r.id}`, 'contains');
}
// Then the keys, so the decisions join the other maps by id.
for (const r of records) {
const keys = [...splitKey(r.subject?.key), ...(r.also || []).flatMap(splitKey)];
for (const k of keys) { add(keyNode(k)); wire(`decision:${r.id}`, k, 'concerns'); }
}
for (const r of records) {
if (r.supersedes) { add({ id: `decision:${r.supersedes}`, label: `${r.supersedes} · superseded`, type: 'decision', rag: 'grey', reason: 'Superseded record not found in decisions/.', gh: null, ext: null }); wire(`decision:${r.id}`, `decision:${r.supersedes}`, 'supersedes'); }
}
mkdirSync(dir, { recursive: true });
const out = { schema: 'decisions-graph.v1', label: 'Decisions', generated_utc: new Date().toISOString(), nodes, edges };
writeFileSync(join(dir, 'graph.json'), JSON.stringify(out));
console.log(`Decisions: ${records.length} records (${count('open')} open, ${count('decided')} decided, ${count('superseded')} superseded); graph ${nodes.length} nodes, ${edges.length} edges.`);Find Prior
A JavaScript module in the modular star folder of Stars that uses SHA-256.
ingeststars / modular-star/find-prior.mjs · lines 1–31 of 31 · Entry point
- What it does
- It fetches data. Uses libraries node:fs, node:zlib. Side effects: reads or writes files; makes network requests.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (JavaScript module); no other file was found loading it.
- What it achieves
- Before writing code: does it already exist somewhere in Ventusltd?
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- stars · modular-star · JavaScript module
- Uses
- Stars — Modular Star (import), node:fs, node:zlib
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/find-prior.mjs:1-31 · blob b76530bb41773811f9c7b36595a56c14565bb6b4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: unknown · users: none · canonical: unknown
// Before writing code: does it already exist somewhere in Ventusltd?
// Usage: node modular-star/find-prior.mjs [--catalog catalog.json.gz] file [file...]
import { readFileSync } from 'node:fs';
import { gunzipSync } from 'node:zlib';
import { langOf, extractAny, splitLines, sha256 } from './lib.mjs';
const args = process.argv.slice(2);
const ci = args.indexOf('--catalog');
const catalogPath = ci >= 0 ? args.splice(ci, 2)[1] : null;
const url = 'https://github.com/Ventusltd/stars/releases/download/modular-star/catalog.json.gz';
const raw = catalogPath ? readFileSync(catalogPath) : Buffer.from(await (await fetch(url)).arrayBuffer());
const catalog = JSON.parse(gunzipSync(raw));
console.log(`Catalogue from ${catalog.generated_utc}\n`);
for (const file of args) {
const lang = langOf(file);
if (!lang) { console.log(`${file}: not JavaScript, HTML or Python — skipped`); continue; }
const bytes = readFileSync(file), lines = splitLines(bytes);
const { issue, functions } = extractAny(lang, bytes);
console.log(`${file}${issue ? ` (${issue})` : ''}`);
if (!functions.length) console.log(' no functions of three lines or more found');
for (const f of functions) {
const exact = catalog.elements[sha256(Buffer.concat(lines.slice(f.first - 1, f.last))).toString('hex')];
const famN = exact ? exact[1] : catalog.family_by_hash[Buffer.from(f.family).toString('hex')];
const fam = famN ? catalog.families[famN] : null;
const where = `${f.name} (lines ${f.first}–${f.last})`;
if (!fam) { console.log(` new ${where}`); continue; }
console.log(` ${exact ? 'SAME CODE ' : 'SAME LOGIC '} ${where} → family #${famN}, ${fam.places.length} place(s) in ${fam.repos} repositories`);
for (const p of fam.places.slice(0, 3)) console.log(` ${p.link}${p.live ? ` (published: ${p.live})` : ''}`);
}
}Functions
A Python module in the modular star folder of Stars that uses SHA-256.
otherstars / modular-star/functions.py · lines 1–36 of 36 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries ast, hashlib, json, sys. Side effects: starts processes.
- What it achieves
- Modular star helper: list Python functions and classes in source read from stdin.
- Why it matters
- No other file in the estate was found to import it.
- Application
- stars · modular-star · Python module
- Uses
- ast, hashlib, json, sys
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/functions.py:1-36 · blob 6aab4e9c740eae966b89c994b02287fcdf3b140b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unreached_review
"""Modular star helper: list Python functions and classes in source read from stdin.
The family key hashes the parsed structure, so layout and comments do not change it. Nothing is executed.
"""
import ast
import hashlib
import json
import sys
src = sys.stdin.buffer.read()
try:
tree = ast.parse(src)
except (SyntaxError, ValueError) as exc:
print(json.dumps({"issue": "Python parse failed: " + str(exc).splitlines()[0][:160], "functions": []}))
sys.exit(0)
methods = set()
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef):
for child in node.body:
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
methods.add(id(child))
out = []
for node in ast.walk(tree):
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
continue
first = min([node.lineno] + [d.lineno for d in node.decorator_list])
last = node.end_lineno
if last - first + 1 < 3:
continue
kind = "class" if isinstance(node, ast.ClassDef) else ("method" if id(node) in methods else "function")
key = hashlib.sha256(("py\0" + ast.dump(node, include_attributes=False)).encode()).hexdigest()
out.append({"first": first, "last": last, "name": node.name, "kind": kind, "family": key})
print(json.dumps({"issue": None, "functions": out}))Stars — Modular Star
A JavaScript module that opens db (`openDb`), splits lines (`splitLines`) and rebuilds tablet (`rebuildTablet`), using SHA-256. It opens db (`openDb`), splits lines (`splitLines`) and rebuilds tablet (`rebuildTablet`).
storagestars / modular-star/lib.mjs · lines 1–277 of 277 · pattern nameOf (shared by 5 files)
- What it does
- It fetches data. Defines 20 functions or classes, including sha256, gitBlobId, langOf, openDb, q. Uses libraries node:crypto, node:child_process, node:sqlite, node:path, node:url. Side effects: makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: browser IndexedDB; user-supplied file (file picker).
- Downstream impact
- Used directly by 4 files: Build (stars); Find Prior (stars); Test (stars); Wandering (stars). Reached from 1 other entry point, including Modular Star Workflow (stars).
- What it achieves
- Modular star — shared logic. Every unique line gets a permanent number.
- Why it matters
- Imported by Find Prior. Run by Build and Wandering. Checked by Test.
- Application
- stars · modular-star · JavaScript module
- Uses
- node:crypto, node:child_process, node:sqlite, node:path, node:url, acorn, acorn-loose, acorn-walk
- Used by
- run by Build (script call), imported by Find Prior (import), run by Test (script call), run by Wandering (script call)
- Produces
- MIN_LINES, MAX_ANALYSE_LINES, sha256, gitBlobId, langOf, SCHEMA, openDb, splitLines, unpack, rebuildTablet, elementSource, extractJs
- Defines here
- sha256, gitBlobId, langOf, openDb, q, splitLines, pack, unpack, lineNumber, rebuildTablet, elementSource, tokenKey, patternNames, analyse, nameOf, extractJs, extractHtml, extractPy, extractAny, ingestFile
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/lib.mjs:1-277 · blob 403c6034eb4fdf8c53cc108d2894e0fa5503b346 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: network, process, storage · domain stage: unknown · users: none · canonical: supporting_data
// Modular star — shared logic.
// Every unique line gets a permanent number. A file version is a tablet: the ordered list of its line
// numbers. Functions and classes inside tablets become numbered elements; elements with the same
// logic (ignoring layout and comments) share a numbered family. Numbers are never reused or changed.
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { DatabaseSync } from 'node:sqlite';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as acorn from 'acorn';
import * as loose from 'acorn-loose';
import * as walk from 'acorn-walk';
export const MIN_LINES = 3;
export const MAX_ANALYSE_LINES = 400;
const HERE = path.dirname(fileURLToPath(import.meta.url));
const decoder = new TextDecoder('utf-8', { ignoreBOM: true });
export const sha256 = b => createHash('sha256').update(b).digest();
export const gitBlobId = bytes => createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
export function langOf(p) {
const ext = path.extname(p).toLowerCase();
if (['.js', '.mjs', '.cjs'].includes(ext)) return 'js';
if (['.html', '.htm'].includes(ext)) return 'html';
if (ext === '.py') return 'py';
return null;
}
export const SCHEMA = `
CREATE TABLE IF NOT EXISTS line(n INTEGER PRIMARY KEY AUTOINCREMENT, sha BLOB UNIQUE NOT NULL, text BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS tablet(n INTEGER PRIMARY KEY AUTOINCREMENT, git_blob TEXT UNIQUE NOT NULL, lang TEXT, lines BLOB NOT NULL, issue TEXT);
CREATE TABLE IF NOT EXISTS family(n INTEGER PRIMARY KEY AUTOINCREMENT, sha BLOB UNIQUE NOT NULL, lang TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS element(n INTEGER PRIMARY KEY AUTOINCREMENT, sha BLOB UNIQUE NOT NULL, family INTEGER NOT NULL, kind TEXT, needs TEXT, standalone INTEGER);
CREATE TABLE IF NOT EXISTS tablet_element(tablet INTEGER NOT NULL, element INTEGER NOT NULL, first INTEGER NOT NULL, last INTEGER NOT NULL, col0 INTEGER, col1 INTEGER, name TEXT, PRIMARY KEY(tablet, element, first));
CREATE TABLE IF NOT EXISTS occurrence(repo TEXT NOT NULL, commit_sha TEXT NOT NULL, path TEXT NOT NULL, tablet INTEGER NOT NULL, seen_utc TEXT NOT NULL, PRIMARY KEY(repo, commit_sha, path));
CREATE TABLE IF NOT EXISTS scan(repo TEXT PRIMARY KEY, commit_sha TEXT, branch TEXT, scanned_utc TEXT, files INTEGER, skipped INTEGER, issue TEXT);
CREATE INDEX IF NOT EXISTS te_element ON tablet_element(element);
CREATE INDEX IF NOT EXISTS occ_tablet ON occurrence(tablet);
CREATE INDEX IF NOT EXISTS element_family ON element(family);
`;
export function openDb(file) {
const db = new DatabaseSync(file);
db.exec(SCHEMA);
const q = sql => db.prepare(sql);
return {
db,
insLine: q('INSERT OR IGNORE INTO line(sha, text) VALUES(?, ?)'),
getLine: q('SELECT n FROM line WHERE sha = ?'),
getTablet: q('SELECT n FROM tablet WHERE git_blob = ?'),
insTablet: q('INSERT INTO tablet(git_blob, lang, lines, issue) VALUES(?, ?, ?, ?)'),
insOcc: q('INSERT OR IGNORE INTO occurrence(repo, commit_sha, path, tablet, seen_utc) VALUES(?, ?, ?, ?, ?)'),
insFamily: q('INSERT OR IGNORE INTO family(sha, lang) VALUES(?, ?)'),
getFamily: q('SELECT n FROM family WHERE sha = ?'),
insElement: q('INSERT OR IGNORE INTO element(sha, family, kind, needs, standalone) VALUES(?, ?, ?, ?, ?)'),
getElement: q('SELECT n FROM element WHERE sha = ?'),
insTE: q('INSERT OR IGNORE INTO tablet_element(tablet, element, first, last, col0, col1, name) VALUES(?, ?, ?, ?, ?, ?, ?)'),
lineCache: new Map(),
};
}
// Split bytes into physical lines, each keeping its own line ending, so a tablet rebuilds exactly.
export function splitLines(bytes) {
const out = [];
let start = 0;
for (let i = 0; i < bytes.length; i++) if (bytes[i] === 0x0a) { out.push(bytes.subarray(start, i + 1)); start = i + 1; }
if (start < bytes.length) out.push(bytes.subarray(start));
return out;
}
const pack = nums => { const b = Buffer.alloc(nums.length * 4); nums.forEach((n, i) => b.writeUInt32LE(n, i * 4)); return b; };
export const unpack = blob => { const b = Buffer.from(blob); const out = []; for (let i = 0; i < b.length; i += 4) out.push(b.readUInt32LE(i)); return out; };
function lineNumber(ctx, bytes) {
const sha = sha256(bytes), key = sha.toString('hex');
let n = ctx.lineCache.get(key);
if (n === undefined) {
ctx.insLine.run(sha, bytes);
n = Number(ctx.getLine.get(sha).n);
ctx.lineCache.set(key, n);
}
return n;
}
export function rebuildTablet(ctx, tabletN) {
const row = ctx.db.prepare('SELECT lines FROM tablet WHERE n = ?').get(tabletN);
const get = ctx.db.prepare('SELECT text FROM line WHERE n = ?');
return Buffer.concat(unpack(row.lines).map(n => Buffer.from(get.get(n).text)));
}
// Exact source of an element occurrence (the node itself, not its whole lines).
export function elementSource(ctx, te) {
const row = ctx.db.prepare('SELECT lines FROM tablet WHERE n = ?').get(te.tablet);
const get = ctx.db.prepare('SELECT text FROM line WHERE n = ?');
const nums = unpack(row.lines).slice(te.first - 1, te.last);
const lines = nums.map(n => decoder.decode(Buffer.from(get.get(n).text)));
if (lines.length === 1) return lines[0].slice(te.col0, te.col1);
return lines[0].slice(te.col0) + lines.slice(1, -1).join('') + lines.at(-1).slice(0, te.col1);
}
const GLOBALS = new Set(('undefined NaN Infinity globalThis Object Function Array Number parseFloat parseInt Boolean String Symbol Date Promise RegExp ' +
'Error AggregateError EvalError RangeError ReferenceError SyntaxError TypeError URIError JSON Math Intl ArrayBuffer SharedArrayBuffer DataView ' +
'Atomics Uint8Array Int8Array Uint16Array Int16Array Uint32Array Int32Array Float32Array Float64Array Uint8ClampedArray BigInt64Array ' +
'BigUint64Array BigInt Map Set WeakMap WeakSet WeakRef FinalizationRegistry Proxy Reflect isFinite isNaN encodeURI encodeURIComponent decodeURI ' +
'decodeURIComponent structuredClone queueMicrotask setTimeout clearTimeout setInterval clearInterval console TextEncoder TextDecoder URL ' +
'URLSearchParams AbortController AbortSignal ' +
// Browser built-ins: present in every page, never something a copied file has to supply.
'Blob File FileReader FileList FormData Headers Request Response Worker Image Audio ImageCapture ImageData ImageBitmap createImageBitmap OffscreenCanvas Path2D ' +
'MutationObserver ResizeObserver IntersectionObserver PerformanceObserver CompressionStream DecompressionStream ReadableStream WritableStream TransformStream ' +
'HTMLElement HTMLCanvasElement Element Node Event CustomEvent MouseEvent KeyboardEvent PointerEvent TouchEvent DOMParser XMLSerializer XMLHttpRequest WebSocket ' +
'crypto performance requestAnimationFrame cancelAnimationFrame requestIdleCallback getComputedStyle matchMedia screen devicePixelRatio atob btoa ' +
'alert confirm prompt history sessionStorage indexedDB caches self globalThis Buffer process innerWidth innerHeight DOMException EventTarget').split(' '));
function tokenKey(text) {
try {
const toks = [];
for (const t of acorn.tokenizer(text, { ecmaVersion: 'latest', allowHashBang: true })) {
const v = t.value && typeof t.value === 'object' ? `/${t.value.pattern}/${t.value.flags}` : (t.value ?? '');
toks.push(t.type.label + ':' + v);
}
return toks.join('\u0001');
} catch {
return text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '').replace(/\s+/g, '');
}
}
function patternNames(p, into) {
if (!p) return;
switch (p.type) {
case 'Identifier': into.add(p.name); break;
case 'ObjectPattern': for (const q of p.properties) patternNames(q.type === 'RestElement' ? q.argument : q.value, into); break;
case 'ArrayPattern': for (const e of p.elements) patternNames(e, into); break;
case 'AssignmentPattern': patternNames(p.left, into); break;
case 'RestElement': patternNames(p.argument, into); break;
}
}
// What a function needs from outside itself. Empty needs + no `this` = a standalone library candidate.
function analyse(fn) {
const isClass = fn.type.startsWith('Class');
const declared = new Set(isClass || fn.type === 'ArrowFunctionExpression' ? [] : ['arguments']);
const used = new Set();
let usesThis = false, incomplete = false;
if (fn.id) declared.add(fn.id.name);
for (const p of fn.params || []) patternNames(p, declared);
walk.fullAncestor(fn, (n, _s, anc) => {
const parent = anc[anc.length - 2];
switch (n.type) {
case 'VariableDeclarator': patternNames(n.id, declared); break;
case 'FunctionDeclaration': case 'FunctionExpression': case 'ArrowFunctionExpression':
if (n.id) declared.add(n.id.name);
for (const p of n.params) patternNames(p, declared);
if (n.type !== 'ArrowFunctionExpression') declared.add('arguments');
break;
case 'ClassDeclaration': case 'ClassExpression': if (n.id) declared.add(n.id.name); break;
case 'CatchClause': patternNames(n.param, declared); break;
case 'ThisExpression': case 'Super': if (!isClass) usesThis = true; break;
case 'MetaProperty': usesThis = true; break;
case 'Identifier': {
if (n.name === '✖') { incomplete = true; break; }
if (!parent) break;
if (parent.type === 'MemberExpression' && parent.property === n && !parent.computed) break;
if (['Property', 'MethodDefinition', 'PropertyDefinition'].includes(parent.type) && parent.key === n && !parent.computed && !parent.shorthand) break;
if (['LabeledStatement', 'BreakStatement', 'ContinueStatement', 'ExportSpecifier', 'ImportSpecifier'].includes(parent.type)) break;
used.add(n.name);
}
}
});
const needs = [...used].filter(x => !declared.has(x) && !GLOBALS.has(x)).sort();
return { needs, usesThis, incomplete };
}
function nameOf(node, parent, src) {
if (node.id?.name) return node.id.name;
if (!parent) return '(anonymous)';
if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') return parent.id.name;
if (['Property', 'MethodDefinition', 'PropertyDefinition'].includes(parent.type)) return parent.key.name ?? String(parent.key.value ?? '(computed)');
if (parent.type === 'AssignmentExpression') return src.slice(parent.left.start, parent.left.end).slice(0, 60);
if (parent.type === 'ExportDefaultDeclaration') return 'default';
return '(anonymous)';
}
// lineOffset/colOffset place a script embedded in HTML back onto the file's own lines.
export function extractJs(src, lineOffset = 0, colOffset = 0) {
let ast;
const opts = { ecmaVersion: 'latest', locations: true, allowHashBang: true, allowReturnOutsideFunction: true, allowAwaitOutsideFunction: true };
try { ast = acorn.parse(src, { ...opts, sourceType: 'module' }); }
catch { try { ast = acorn.parse(src, { ...opts, sourceType: 'script' }); } catch { ast = loose.parse(src, opts); } }
const out = [];
walk.fullAncestor(ast, (node, _s, anc) => {
if (!['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression', 'ClassDeclaration', 'ClassExpression'].includes(node.type)) return;
const first = node.loc.start.line, last = node.loc.end.line;
if (last - first + 1 < MIN_LINES) return;
const parent = anc[anc.length - 2];
const isMethod = (parent?.type === 'MethodDefinition') || (parent?.type === 'Property' && (parent.method || parent.kind !== 'init')) || parent?.type === 'PropertyDefinition';
const kind = isMethod ? 'method' : node.type.startsWith('Class') ? 'class' : node.type === 'ArrowFunctionExpression' ? 'arrow' : 'function';
const text = src.slice(node.start, node.end);
let needs = null, standalone = false;
if (last - first + 1 <= MAX_ANALYSE_LINES) {
const a = analyse(node);
needs = a.needs;
standalone = !isMethod && !a.usesThis && !a.incomplete && a.needs.length === 0;
}
out.push({
first: first + lineOffset, last: last + lineOffset,
col0: node.loc.start.column + (first === 1 ? colOffset : 0),
col1: node.loc.end.column + (last === 1 ? colOffset : 0),
kind, name: nameOf(node, parent, src), family: sha256('js\0' + tokenKey(text)), needs, standalone,
});
});
return out;
}
export function extractHtml(text) {
const out = [];
const re = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
let m;
while ((m = re.exec(text))) {
const attrs = m[1];
if (/\bsrc\s*=/i.test(attrs)) continue;
const type = (attrs.match(/\btype\s*=\s*["']?([^"'\s>]+)/i) || [])[1];
if (type && !/^(module|text\/javascript|application\/javascript)$/i.test(type)) continue;
const bodyStart = m.index + m[0].indexOf('>') + 1;
let lineOffset = 0;
for (let i = 0; i < bodyStart; i++) if (text.charCodeAt(i) === 10) lineOffset++;
const colOffset = bodyStart - (text.lastIndexOf('\n', bodyStart - 1) + 1);
out.push(...extractJs(m[2], lineOffset, colOffset));
}
return out;
}
export function extractPy(bytes) {
const py = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
const r = spawnSync(py, [path.join(HERE, 'functions.py')], { input: bytes, maxBuffer: 64 * 1024 * 1024 });
if (r.status !== 0) return { issue: 'Python helper failed: ' + String(r.stderr || r.error).slice(0, 160), functions: [] };
const res = JSON.parse(r.stdout);
return { issue: res.issue ?? null, functions: (res.functions || []).map(f => ({ ...f, family: Buffer.from(f.family, 'hex'), col0: null, col1: null, needs: null, standalone: false })) };
}
// Parse any supported source into functions. Refuses (with a reason) when line counting could disagree.
export function extractAny(lang, bytes) {
const text = decoder.decode(bytes);
if (/\r(?!\n)|\u2028|\u2029/.test(text)) return { issue: 'Unusual line breaks (lone CR or U+2028/2029); functions not extracted', functions: [] };
try {
if (lang === 'js') return { issue: null, functions: extractJs(text) };
if (lang === 'html') return { issue: null, functions: extractHtml(text) };
if (lang === 'py') return extractPy(bytes);
} catch (e) {
return { issue: 'Parse failed: ' + String(e.message).slice(0, 160), functions: [] };
}
return { issue: null, functions: [] };
}
export function ingestFile(ctx, { repo, commit, path: p, bytes, oid, seen = new Date().toISOString() }) {
const lang = langOf(p);
if (!lang) return null;
oid ??= gitBlobId(bytes);
let tablet = ctx.getTablet.get(oid)?.n;
if (tablet === undefined) {
const lines = splitLines(bytes);
const nums = lines.map(l => lineNumber(ctx, l));
const { issue, functions } = extractAny(lang, bytes);
tablet = Number(ctx.insTablet.run(oid, lang, pack(nums), issue).lastInsertRowid);
for (const f of functions) {
if (f.last > lines.length) continue;
const body = Buffer.concat(lines.slice(f.first - 1, f.last));
ctx.insFamily.run(f.family, lang === 'html' ? 'js' : lang);
const family = Number(ctx.getFamily.get(f.family).n);
const esha = sha256(body);
ctx.insElement.run(esha, family, f.kind, f.needs ? JSON.stringify(f.needs) : null, f.standalone ? 1 : 0);
const element = Number(ctx.getElement.get(esha).n);
ctx.insTE.run(tablet, element, f.first, f.last, f.col0, f.col1, f.name);
}
}
ctx.insOcc.run(repo, commit, p, tablet, seen);
return tablet;
}Lines
A JavaScript module in Stars that writes `LINES.md`: every unique line of code in the numbered database, in number order, one row per line. keeps them).
otherstars / modular-star/lines.mjs · lines 1–27 of 27 · Entry point
- What it does
- Defines arg, write. Uses libraries node:fs, node:sqlite. Side effects: reads or writes files.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Modular Star Workflow (stars).
- What it achieves
- Defines `arg` and `write`.
- Why it matters
- Run by Modular Star Workflow.
- Application
- stars · modular-star · JavaScript module
- Uses
- node:fs, node:sqlite
- Used by
- run by Modular Star Workflow (workflow run)
- Produces
- arg, write
- Defines here
- arg, write
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/lines.mjs:1-27 · blob 6f8050fb3d4c063991ebb2dd5bcc57cf80d12c95 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
// Write LINES.md: every unique line of code in the numbered database, in number order, one row per line.
// Not a summary. Format per row: <number><tab><code>. Line endings are stripped for display (the database
// keeps them). Usage: node modular-star/lines.mjs --db modular.sqlite --out LINES.md
import { createWriteStream } from 'node:fs';
import { DatabaseSync } from 'node:sqlite';
const arg = (k, d) => { const i = process.argv.indexOf('--' + k); return i > 0 ? process.argv[i + 1] : d; };
const db = new DatabaseSync(arg('db', 'modular.sqlite'), { readOnly: true });
const total = Number(db.prepare('SELECT count(*) c FROM line').get().c);
const last = Number(db.prepare('SELECT max(n) m FROM line').get().m);
const decoder = new TextDecoder('utf-8', { fatal: false });
const out = createWriteStream(arg('out', 'LINES.md'));
const write = s => new Promise(r => out.write(s) ? r() : out.once('drain', r));
await write(`# Every unique line of code — Ventusltd public repositories\n\n` +
`${total.toLocaleString('en-GB')} unique lines, numbered 1 to ${last.toLocaleString('en-GB')}. Generated ${new Date().toISOString()} by the modular star from the ` +
`numbered database (modular.sqlite on the modular-star release). The number is the line's permanent key: it never changes ` +
`and is never reused. Numbers missing from the sequence were never issued. Each row is \`number<tab>code\`; the code is shown ` +
`exactly as written, with its line ending removed (the database keeps the ending). Where a line appears, and in which files: ` +
`the tablet and occurrence tables of the same database.\n\n` + '```text\n');
for (const row of db.prepare('SELECT n, text FROM line ORDER BY n').iterate()) {
const text = decoder.decode(Buffer.from(row.text)).replace(/\r?\n$/, '').replace(/\r$/, '');
await write(`${row.n}\t${text}\n`);
}
await write('```\n');
await new Promise(r => out.end(r));
console.log(`LINES.md: ${total} lines written (numbers up to ${last})`);Pair Verdict
A JavaScript module in the modular star folder of Stars. It is built from the pair verdict helper (`pairVerdict`).
transformstars / modular-star/pair-verdict.mjs · lines 1–8 of 8
- What it does
- It calculates its inputs. Defines pairVerdict.
- Downstream impact
- Used directly by 2 files: Links and Evidence Test (stars); Reactions (stars). Reached from 1 other entry point, including Modular Star Workflow (stars).
- What it achieves
- Thresholds apply to actual red observations, never to 1 minus a smoothed green probability.
- Why it matters
- Imported by Reactions. Checked by Links and Evidence Test.
- Application
- stars · modular-star · JavaScript module
- Uses
- none found
- Used by
- run by Links and Evidence Test (script call), imported by Reactions (import)
- Produces
- pairVerdict
- Defines here
- pairVerdict
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/pair-verdict.mjs:1-8 · blob 2ef0fc3f4767a2ba1e151ae433de617f4f46d2d7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
// Thresholds apply to actual red observations, never to 1 minus a smoothed green probability.
export function pairVerdict({ green, red, total }) {
if (!Number.isInteger(total) || total < 0 || !Number.isInteger(green) || green < 0 || !Number.isInteger(red) || red < 0 || green + red > total) throw new Error('Invalid composition-test counts');
if (!total) return 'untested';
if (total >= 3 && red / total >= 0.9) return 'unstable';
if (total >= 3 && green === total) return 'proven';
return 'mixed evidence';
}