In this section
- Dec render · galaxies-wafers / iterations/39-decisions-and-permission/dec.css lines 1–65
- Iterations — 39 Decisions and Permission Page render · galaxies-wafers / iterations/39-decisions-and-permission/index.html lines 1–76
- Records ingest · galaxies-wafers / iterations/39-decisions-and-permission/records.mjs lines 1–235
Dec
A style sheet in the iterations folder of Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/.
rendergalaxies-wafers / iterations/39-decisions-and-permission/dec.css · lines 1–65 of 65 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Downstream impact
- Used directly by 1 file: Iterations — 39 Decisions and Permission Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Loaded by the 39 Decisions and Permission page at https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/.
- Application
- galaxies-wafers · iterations/39-decisions-and-permission · style sheet
- Uses
- none found
- Used by
- loaded by Iterations — 39 Decisions and Permission Page (stylesheet)
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/39-decisions-and-permission/dec.css:1-65 · blob fec7e5bb675df84dd374622cb17433a3c8b85a87 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
:root{--ink:#d8dee9;--dim:#8b93a7;--ground:#0b0d12;--edge:#1b2030;--beam:#5ec8f2;--amber:#ffb000;--grey:#8b93a7}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
padding:calc(env(safe-area-inset-top,0px) + .8rem) 1rem calc(env(safe-area-inset-bottom,0px) + 2rem)}
main{max-width:60rem;margin:0 auto}
h1{font-size:14px;letter-spacing:.18em;font-weight:600;margin:0 0 .35rem;color:#fff}
h2{font-size:11px;letter-spacing:.14em;font-weight:400;color:var(--dim);margin:1.2rem 0 .4rem}
p{margin:.35rem 0}
.dim{color:var(--dim)} .small{font-size:11.5px}
a{color:var(--beam)}
code{color:var(--beam);overflow-wrap:anywhere}
.pin{color:#fff}
.summary{border-left:3px solid #fff;padding:.35rem .6rem;background:#10131b;margin:.6rem 0}
.summary b{color:#fff}
.layers{display:grid;gap:.2rem;margin:.6rem 0}
.layer{display:flex;align-items:center;gap:.55rem;min-height:40px;padding:0 .2rem;border-bottom:1px solid var(--edge);cursor:pointer}
.layer input{width:20px;height:20px;accent-color:#d8dee9;flex:none}
.layer span{overflow-wrap:anywhere}
.keyform{margin:.7rem 0}
.keyrow{display:flex;gap:.4rem;margin:.25rem 0}
.keyrow input{flex:1;min-width:0;font:inherit;font-size:16px;color:#fff;background:#05060a;border:1px solid var(--edge);border-radius:.35rem;padding:.45rem .55rem;min-height:44px}
.keyrow button,.boardnav button{font:inherit;color:var(--ink);background:#07080c;border:1px solid var(--edge);border-radius:.35rem;min-height:44px;min-width:56px}
.keyrow button:active{border-color:#fff}
.verdict{border:1px solid var(--edge);border-left-width:4px;border-radius:.4rem;background:#10131b;padding:.5rem .65rem;overflow-wrap:anywhere}
.verdict .v{font-weight:600;letter-spacing:.08em;font-size:13.5px}
.verdict.grants{border-left-color:#fff} .verdict.grants .v{color:#fff}
.verdict.refuses{border-left-color:var(--amber)} .verdict.refuses .v{color:var(--amber)}
.verdict.none{border-left-color:var(--grey)} .verdict.none .v{color:var(--grey)}
.verdict ul{margin:.3rem 0;padding-left:1.1rem}
.plane{position:relative;margin:.4rem -1rem 0;height:min(100vw,62vh);min-height:320px;max-height:760px;background:#05060a;border-top:1px solid var(--edge);border-bottom:1px solid var(--edge)}
#board{display:block;width:100%;height:100%;touch-action:none;cursor:pointer}
.fit{position:absolute;right:.6rem;top:.6rem;font:inherit;color:var(--ink);background:#0b0d12e6;border:1px solid var(--edge);border-radius:.35rem;min-width:44px;min-height:40px}
.boardnav{position:absolute;left:.6rem;top:.6rem;display:flex;align-items:center;gap:.35rem;background:#0b0d12cc;border-radius:.35rem}
.boardnav button{min-width:40px;min-height:40px}
.boardnav button:disabled{opacity:.35}
.drawn{position:absolute;left:.6rem;bottom:.35rem;font-size:10.5px;pointer-events:none}
.legend{margin:.35rem 0 0;line-height:1.9}
.sw{display:inline-block;width:12px;height:12px;border-radius:50%;vertical-align:-2px;margin:0 .3rem 0 .15rem}
.sw-decided{background:#eceff4;box-shadow:0 0 0 1.5px #000}
.sw-open{background:#14161c;box-shadow:inset 0 0 0 2px var(--amber)}
.sw-super{background:transparent;box-shadow:inset 0 0 0 2px #6b7385}
.sw-bad{background:#14161c;outline:1.5px dashed #fff;outline-offset:1px}
.sw-key{width:8px;height:8px;background:var(--beam);box-shadow:0 0 6px 2px #5ec8f288}
.card{border:1px solid var(--edge);border-radius:.45rem;background:#10131b;padding:.55rem .7rem;margin:.7rem 0;overflow-wrap:anywhere}
.card h3{margin:0 0 .35rem;font-size:14px;color:#fff;font-weight:600}
.card dl{display:grid;grid-template-columns:minmax(6.5rem,auto) 1fr;gap:.3rem .7rem;margin:.4rem 0}
.card dt{color:var(--dim)} .card dd{margin:0}
.card .q{color:#fff;font-size:13.5px}
.card ul{margin:0;padding-left:1.1rem}
.card .prob{border-left:3px dashed #fff;padding-left:.5rem}
.btns{display:flex;flex-wrap:wrap;gap:.4rem;margin:.3rem 0}
.btn{display:inline-flex;align-items:center;gap:.3rem;font:inherit;font-size:11.5px;letter-spacing:.1em;color:#fff;text-decoration:none;background:#07080c;border:1px solid #3a4258;border-radius:.35rem;padding:.3rem .55rem;min-height:36px}
.btn.off{color:var(--dim);border-style:dashed}
.btns .why{flex-basis:100%;font-size:11px;color:var(--dim)}
.rows{list-style:none;margin:0;padding:0;display:grid;gap:.4rem}
.rows li.plain{border:1px solid var(--edge);border-radius:.4rem;padding:.45rem .55rem;overflow-wrap:anywhere}
.qrows{margin:.3rem 0;padding-left:1.1rem}
.questions{border:1px solid var(--edge);border-radius:.45rem;background:#10131b;padding:0 .65rem;margin:1.2rem 0 .5rem}
.questions summary{font-size:11px;letter-spacing:.14em;text-transform:uppercase;cursor:pointer;color:var(--beam);min-height:40px;display:flex;align-items:center}
.questions dt{color:#fff;margin-top:.5rem;font-size:12px}
.questions dd{margin:.2rem 0 .6rem;font-size:11.5px;overflow-wrap:anywhere}
.machine{border-left:3px solid var(--beam);padding:.35rem .6rem;background:#07080c;overflow-wrap:anywhere}
footer{margin-top:1.2rem;overflow-wrap:anywhere}
@media (min-width:900px){.plane{margin:.4rem 0 0;border:1px solid var(--edge);border-radius:.45rem;height:62vh}}Iterations — 39 Decisions and Permission Page
A web page in Galaxies Wafers. Published at https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/.
rendergalaxies-wafers / iterations/39-decisions-and-permission/index.html · lines 1–76 of 76 · Entry point
- What it does
- It draws its content. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: JSON file graph.json; form fields (user input). Out: web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/.
- What it achieves
- No Record, No Permission.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- galaxies-wafers · iterations/39-decisions-and-permission · page
- Uses
- Dec (stylesheet), Iterations — 31 Code Card Everywhere Page (link), Galaxies Wafers — Index Page (link), Galaxies Wafers — Iterations Page (link), Iterations — 39 Decisions and Permission (script src)
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/39-decisions-and-permission/index.html:1-76 · blob 8860c2ed81a2b16cb3141fdfe1b0207e9a2005b7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>No Record, No Permission</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="dec.css">
</head>
<body>
<main>
<header>
<h1>NO RECORD, NO PERMISSION</h1>
<p class="dim">A decision record attaches a judgement to one permanent key of the estate: a block, a constant, a function family or a pair of blocks. A <b>decided</b> record is permission to do what it says. An <b>open</b> record is a question: the key is not changed. <b>No record is no permission.</b> Each record is a stone on the board, placed by its number; the keys it judges are the lit po … [line shortened here: 419 characters; full line on GitHub]
<p id="summary" class="summary">WAIT — nothing is fetched until you tick a layer or check a key.</p>
</header>
<section class="layers" aria-label="Layers">
<label class="layer"><input type="checkbox" data-layer="stones"><span id="lbl-stones" data-base-label="Stones · decision records">Stones · decision records [WAIT]</span></label>
<label class="layer"><input type="checkbox" data-layer="edges"><span id="lbl-edges" data-base-label="Cased edges · decisions/graph.json">Cased edges · decisions/graph.json [WAIT]</span></label>
</section>
<form id="keyform" class="keyform" autocomplete="off">
<label for="key" class="dim small">Type any key: may an agent act on it?</label>
<div class="keyrow">
<input id="key" name="key" type="text" inputmode="text" autocapitalize="off" spellcheck="false" placeholder="block:Ek · family:511 · line:337722">
<button type="submit" id="check">check</button>
</div>
<div id="verdict" class="verdict none" aria-live="polite"><span class="dim">WAIT — type a key and press check.</span></div>
</form>
<div class="plane">
<canvas id="board" aria-label="The decision board. Tap a stone to read its record, tap a lit point to check its key. Drag to pan, pinch or wheel to zoom."></canvas>
<button type="button" id="fit" class="fit">fit</button>
<div class="boardnav">
<button type="button" id="prev" aria-label="previous board" disabled>‹</button>
<span id="boardname" class="dim small">board —</span>
<button type="button" id="next" aria-label="next board" disabled>›</button>
</div>
<div id="drawn" class="drawn dim"></div>
</div>
<p class="legend small dim"><span class="sw sw-decided"></span>decided · <span class="sw sw-open"></span>open (amber ring, the colour the estate's Decisions map gives open records) · <span class="sw sw-super"></span>superseded · <span class="sw sw-bad"></span>does not conform · <span class="sw sw-key"></span>key judged</p>
<section id="card" class="card" aria-live="polite">
<p class="dim">Tap a stone to read its record.</p>
</section>
<h2>RECORDS THAT DO NOT CONFORM TO SCHEMA.md</h2>
<ul id="nonconf" class="rows"><li class="plain dim">WAIT — tick Stones.</li></ul>
<p id="gate" class="small dim"></p>
<details id="questions" class="questions">
<summary>Questions</summary>
<dl>
<dt>1. How does this help draw a system or a single-line diagram?</dt>
<dd>It draws no busbar, feeder, transformer, cable route, protection or earthing. It says which drawing actions on the keys that feed a drawing are permitted or refused, computed from the records now:
<ul id="q-draw" class="qrows"><li class="dim">not yet known: tick Stones.</li></ul>
The permission is read from <code>status</code> and <code>consequences.agents_may</code> of each record; the key's name from the <code>label</code> of its node in <code>decisions/graph.json</code>.</dd>
<dt>2. What is this code used for?</dt>
<dd>Found by searching the estate for the path <code>decisions/</code> at stars commit <span class="pin" id="q-pin">—</span>. <code>modular-star/decision-record.mjs</code> turns a Decision issue into <code>decisions/dNNN.json</code>; <code>modular-star/decisions.mjs</code> reads every record and writes <code>decisions/graph.json</code> (run by <code>.github/workflows/decisions.yml</code> lin … [line shortened here: 1,503 characters; full line on GitHub]
<dt>3. Where does it lead next?</dt>
<dd><span id="q-next">not yet known: tick Stones.</span></dd>
</dl>
</details>
<p id="machine" class="machine small">Machine detail · not yet known: tick Stones.</p>
<footer class="dim small">
<p id="loadingrule">Loading, as Grid Atlas does it: nothing is fetched until a layer is ticked or a key is checked.</p>
<p id="prov"></p>
<p>No colour here is a verdict: granted is white, refused is amber (the estate's own colour for an open record), no record is grey. <a href="../">every version</a></p>
</footer>
</main>
<script type="module" src="app.mjs"></script>
</body>
</html>Records
A JavaScript module in the iterations folder of Galaxies Wafers that parses schema (`parseSchema`). Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/.
ingestgalaxies-wafers / iterations/39-decisions-and-permission/records.mjs · lines 1–235 of 235 · pattern splitKey (shared by 2 files)
- What it does
- It lists and searches its content. Defines 19 functions or classes, including parseSchema, splitKey, atomProblem, keyProblem, isStr.
- Downstream impact
- Used directly by 1 file: Iterations — 39 Decisions and Permission (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/). Reached from 1 other entry point, including Iterations — 39 Decisions and Permission Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/).
- What it achieves
- It parses schema (`parseSchema`), splits key (`splitKey`) and reads key (`readKey`). No Record, No Permission — the arithmetic, with no DOM.
- Why it matters
- Imported by Iterations — 39 Decisions and Permission.
- Application
- galaxies-wafers · iterations/39-decisions-and-permission · JavaScript module
- Uses
- none found
- Used by
- imported by Iterations — 39 Decisions and Permission (import)
- Produces
- parseSchema, splitKey, atomProblem, keyProblem, validate, crossCheck, keysOf, readKey, permission, SIZE, numberOf, boardOf
- Defines here
- parseSchema, splitKey, atomProblem, keyProblem, isStr, isStrArr, REAL_DATE, validate, crossCheck, keysOf, readKey, permission, norm, numberOf, boardOf, stonePoint, RINGS, rank, layoutBoard
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/39-decisions-and-permission/records.mjs:1-235 · blob 3d500006d750f6152c1721bb4c8e2c9d85f6d0a9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
/* No Record, No Permission — the arithmetic, with no DOM.
Reads the rules out of stars decisions/SCHEMA.md, checks each decision record
against them, answers "what may be done on this key", and places records on
a 19 x 19 board by their permanent number. */
/* ── SCHEMA.md → rules ─────────────────────────────────────────────────────
The field table is parsed at run time, so the page checks the schema as it
is published, not a typed copy of it. Throws when the table cannot be read. */
export function parseSchema(md) {
const fields = new Map();
for (const line of String(md).split('\n')) {
const m = line.match(/^\|\s*`([a-z_]+)`\s*\|\s*([^|]+?)\s*\|\s*(.*)\|\s*$/);
if (m) fields.set(m[1], { name: m[1], required: m[2].trim().toLowerCase(), meaning: m[3].trim() });
}
if (!fields.size) throw new Error('SCHEMA.md has no field table this page can read');
for (const need of ['id', 'subject', 'status', 'consequences']) {
if (!fields.has(need)) throw new Error(`SCHEMA.md field table has no \`${need}\` row`);
}
const statusRow = fields.get('status').meaning;
const statuses = [...statusRow.matchAll(/`([a-z]+)`/g)].map(x => x[1]);
const subjRow = fields.get('subject').meaning;
const typeList = subjRow.match(/"type":\s*((?:"[a-z]+"\s*(?:\\\||\|)?\s*)+)/);
const subjectTypes = typeList ? [...typeList[1].matchAll(/"([a-z]+)"/g)].map(x => x[1]) : [];
const prefixes = [...new Set([...subjRow.matchAll(/`([a-z]+):[^`]*`/g)].map(x => x[1]))];
if (!statuses.length) throw new Error('SCHEMA.md status row names no statuses');
if (!subjectTypes.length) throw new Error('SCHEMA.md subject row names no subject types');
if (!prefixes.length) throw new Error('SCHEMA.md subject row names no key forms');
return { fields, statuses, subjectTypes, prefixes };
}
/* ── keys ─────────────────────────────────────────────────────────────────── */
export const splitKey = key => String(key ?? '').split('+').map(k => k.trim()).filter(Boolean);
/* One map id in the schema's form: <prefix>:<ref>. block refs are symbols,
family refs are numbers. Returns a reason when it is not. */
export function atomProblem(atom, schema) {
const m = String(atom).match(/^([a-z]+):(.+)$/);
if (!m) return `"${atom}" is not in the form prefix:ref`;
if (!schema.prefixes.includes(m[1])) return `"${m[1]}:" is not a key form SCHEMA.md names (${schema.prefixes.map(p => p + ':').join(', ')})`;
if (m[1] === 'family' && !/^\d+$/.test(m[2])) return `family ref "${m[2]}" is not a number`;
if (m[1] === 'block' && !/^[A-Za-z][A-Za-z0-9]*$/.test(m[2])) return `block ref "${m[2]}" is not a symbol`;
return null;
}
export function keyProblem(key, schema) {
const parts = splitKey(key);
if (!parts.length) return 'the key is empty';
if (parts.length > 2) return 'a key joins at most two blocks';
for (const p of parts) { const why = atomProblem(p, schema); if (why) return why; }
if (parts.length === 2 && !parts.every(p => p.startsWith('block:'))) return 'a pair joins two blocks';
return null;
}
/* ── one record against the schema ───────────────────────────────────────── */
const isStr = v => typeof v === 'string';
const isStrArr = v => Array.isArray(v) && v.every(isStr);
const REAL_DATE = s => { const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s); if (!m) return false; const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])); return d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]; };
export function validate(rec, fileName, schema) {
const problems = [], notes = [];
if (!rec || typeof rec !== 'object' || Array.isArray(rec)) return { ok: false, problems: ['the file is not a JSON object'], notes };
const status = rec.status;
for (const f of schema.fields.values()) {
const present = rec[f.name] !== undefined;
if (f.required === 'yes' && !present) problems.push(`required field \`${f.name}\` is missing`);
if (f.required.startsWith('when decided') && status === 'decided' && !(isStr(rec[f.name]) && rec[f.name].trim())) problems.push(`\`${f.name}\` must be written when the record is decided`);
}
for (const k of Object.keys(rec)) if (!schema.fields.has(k)) notes.push(`field \`${k}\` is not in SCHEMA.md`);
if (rec.id !== undefined) {
if (!isStr(rec.id) || !/^d\d{3,}$/.test(rec.id)) problems.push(`\`id\` "${rec.id}" is not dNNN`);
else if (fileName && fileName !== rec.id + '.json') problems.push(`\`id\` ${rec.id} does not match its file ${fileName}`);
}
if (rec.subject !== undefined) {
const s = rec.subject;
if (!s || typeof s !== 'object') problems.push('`subject` is not an object');
else {
if (!schema.subjectTypes.includes(s.type)) problems.push(`\`subject.type\` "${s.type}" is not one of ${schema.subjectTypes.join(', ')}`);
const why = keyProblem(s.key, schema);
if (why) problems.push(`\`subject.key\`: ${why}`);
else {
const parts = splitKey(s.key);
if (s.type === 'pair' && parts.length !== 2) problems.push('`subject.type` is pair but the key is not two blocks joined by +');
if (s.type !== 'pair' && parts.length !== 1) problems.push(`\`subject.type\` is ${s.type} but the key joins two keys`);
if ((s.type === 'block' || s.type === 'constant') && !parts[0].startsWith('block:')) problems.push(`a ${s.type} key uses block:`);
if (s.type === 'family' && !parts[0].startsWith('family:')) problems.push('a family key uses family:');
}
}
}
if (rec.also !== undefined) {
if (!isStrArr(rec.also)) problems.push('`also` is not a list of keys');
else for (const k of rec.also) { const why = keyProblem(k, schema); if (why) problems.push(`\`also\` "${k}": ${why}`); }
}
if (rec.question !== undefined && !(isStr(rec.question) && rec.question.trim())) problems.push('`question` is empty');
if (rec.decision !== undefined) {
if (!isStr(rec.decision)) problems.push('`decision` is not a string');
else if (status === 'open' && rec.decision !== '') problems.push('`decision` must be an empty string while open');
}
if (rec.rationale !== undefined && !isStr(rec.rationale)) problems.push('`rationale` is not a string');
if (rec.evidence !== undefined && !isStrArr(rec.evidence)) problems.push('`evidence` is not a list of links');
if (rec.date !== undefined && !(isStr(rec.date) && REAL_DATE(rec.date))) problems.push(`\`date\` "${rec.date}" is not a real YYYY-MM-DD date`);
if (status !== undefined && !schema.statuses.includes(status)) problems.push(`\`status\` "${status}" is not one of ${schema.statuses.join(', ')}`);
if (rec.supersedes !== undefined && rec.supersedes !== null && rec.supersedes !== '') {
if (!isStr(rec.supersedes) || !/^d\d{3,}$/.test(rec.supersedes)) problems.push(`\`supersedes\` "${rec.supersedes}" is not dNNN`);
else if (rec.supersedes === rec.id) problems.push('a record cannot supersede itself');
}
if (rec.consequences !== undefined) {
const c = rec.consequences;
if (!c || typeof c !== 'object') problems.push('`consequences` is not an object');
else {
if (!isStrArr(c.settles)) problems.push('`consequences.settles` is not a list of keys');
else {
for (const k of c.settles) { const why = keyProblem(k, schema); if (why) problems.push(`\`consequences.settles\` "${k}": ${why}`); }
if (status === 'open' && c.settles.length) problems.push('`consequences.settles` must be empty while open');
}
if (!isStrArr(c.agents_may)) problems.push('`consequences.agents_may` is not a list of sentences');
}
}
if (rec.source !== undefined) {
const s = rec.source;
if (!s || typeof s !== 'object' || !Number.isInteger(s.issue) || !isStr(s.url)) problems.push('`source` is not { issue: N, url }');
}
return { ok: problems.length === 0, problems, notes };
}
/* Cross-record rules: a superseded target must say superseded. */
export function crossCheck(records) {
const byId = new Map(records.map(r => [r.rec?.id, r]));
const out = [];
for (const r of records) {
const t = r.rec?.supersedes;
if (!t || !byId.has(t)) continue;
const target = byId.get(t);
if (target.rec.status !== 'superseded') out.push({ id: target.rec.id, problem: `${r.rec.id} supersedes it, but its \`status\` is "${target.rec.status}"` });
}
return out;
}
/* Every key a record judges, as single map ids. */
export function keysOf(rec) {
const ks = [...splitKey(rec?.subject?.key), ...(Array.isArray(rec?.also) ? rec.also.flatMap(splitKey) : []), ...(Array.isArray(rec?.consequences?.settles) ? rec.consequences.settles.flatMap(splitKey) : [])];
return [...new Set(ks)];
}
/* ── the reader's key → map id ───────────────────────────────────────────── */
export function readKey(input, schema) {
const raw = String(input ?? '').trim();
if (!raw) return { ok: false, why: 'type a key, for example block:Ek, family:511 or line:337722' };
const parts = raw.split('+').map(s => s.trim()).filter(Boolean).map(p => (/^[A-Za-z][A-Za-z0-9]*$/.test(p) ? 'block:' + p : p));
const key = parts.join('+');
const line = /^line:(\d+)$/.exec(key);
if (line) return { ok: true, key, line: Number(line[1]), parts, lineOnly: true };
if (/^\d+$/.test(raw)) return { ok: false, why: `"${raw}" is a bare number: write family:${raw} or line:${raw}` };
const why = keyProblem(key, schema);
if (why) return { ok: false, why };
return { ok: true, key, parts };
}
/* ── permission ──────────────────────────────────────────────────────────────
GRANTS — a conforming, current, decided record judges the key.
REFUSES — only open records judge it: a question, so the key is not changed.
HISTORY — only superseded records: no current permission.
NO RECORD — nothing judges it: no permission.
A record that does not conform grants nothing; it is listed, never used. */
export function permission(k, loaded) {
const supersededIds = new Set(loaded.filter(r => r.v.ok && r.rec.supersedes).map(r => r.rec.supersedes));
/* a broken record may write a bare symbol; match it too, so it is listed as not counted */
const norm = ks => ks.map(x => (/^[A-Za-z][A-Za-z0-9]*$/.test(x) ? 'block:' + x : x));
const hits = loaded.filter(r => { const ks = r.v.ok ? keysOf(r.rec) : norm(keysOf(r.rec)); return k.parts.every(p => ks.includes(p)) || r.rec?.subject?.key === k.key; });
const bad = hits.filter(r => !r.v.ok);
const good = hits.filter(r => r.v.ok);
const current = good.filter(r => r.rec.status !== 'superseded' && !supersededIds.has(r.rec.id));
const decided = current.filter(r => r.rec.status === 'decided');
const open = current.filter(r => r.rec.status === 'open');
const history = good.filter(r => !current.includes(r));
let verdict = 'NO RECORD';
if (decided.length) verdict = 'GRANTS';
else if (open.length) verdict = 'REFUSES';
else if (history.length) verdict = 'HISTORY';
const may = (decided.length ? decided : open).flatMap(r => r.rec.consequences.agents_may.map(s => ({ id: r.rec.id, s })));
return { verdict, decided, open, history, bad, may };
}
/* ── the board ─────────────────────────────────────────────────────────────
19 x 19 intersections. Stones sit on every fourth point (1, 5, 9, 13, 17),
five by five: 25 stones a board. Record dN goes to board floor((N-1)/25),
slot (N-1) mod 25, row-major from the top left. Three free lines separate
stones, so every stone owns its eight neighbours for the keys it judges. */
export const SIZE = 19, STEP = 4, OFFSET = 1, PER_ROW = 5, PER_BOARD = PER_ROW * PER_ROW;
export const numberOf = id => Number(String(id).slice(1));
export const boardOf = n => Math.floor((n - 1) / PER_BOARD);
export function stonePoint(n) { const s = (n - 1) % PER_BOARD; return [OFFSET + (s % PER_ROW) * STEP, OFFSET + Math.floor(s / PER_ROW) * STEP]; }
const RINGS = (() => {
const out = [];
for (let r = 1; r < SIZE; r++) {
const ring = [];
for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) if (Math.max(Math.abs(dx), Math.abs(dy)) === r) ring.push([dx, dy]);
/* a fixed order: below, right, above, left, then the diagonals, then outward */
const pref = ['0,1', '1,0', '0,-1', '-1,0', '1,1', '1,-1', '-1,1', '-1,-1'];
const rank = d => { const i = pref.indexOf(d.join(',')); return i < 0 ? 99 : i; };
ring.sort((a, b) => rank(a) - rank(b) || (Math.abs(a[0]) + Math.abs(a[1])) - (Math.abs(b[0]) + Math.abs(b[1])) || Math.atan2(a[0], -a[1]) - Math.atan2(b[0], -b[1]));
out.push(ring);
}
return out;
})();
/* recs: conforming-or-not records on one board, sorted by number.
Returns stones [{id,n,x,y}] and keys [{key,x,y,by:[ids]}]. A key judged by
two records sits by the lower-numbered one. */
export function layoutBoard(recs) {
const taken = new Set();
for (let y = OFFSET; y < SIZE; y += STEP) for (let x = OFFSET; x < SIZE; x += STEP) taken.add(x + ',' + y);
const stones = [], keys = new Map();
for (const r of [...recs].sort((a, b) => numberOf(a.rec.id) - numberOf(b.rec.id))) {
const n = numberOf(r.rec.id);
const [x, y] = stonePoint(n);
stones.push({ id: r.rec.id, n, x, y, r });
for (const key of keysOf(r.rec)) {
if (keys.has(key)) { keys.get(key).by.push(r.rec.id); continue; }
let spot = null;
for (const ring of RINGS) {
for (const [dx, dy] of ring) {
const X = x + dx, Y = y + dy;
if (X < 0 || Y < 0 || X >= SIZE || Y >= SIZE || taken.has(X + ',' + Y)) continue;
spot = [X, Y]; break;
}
if (spot) break;
}
if (!spot) continue;
taken.add(spot.join(','));
keys.set(key, { key, x: spot[0], y: spot[1], by: [r.rec.id] });
}
}
return { stones, keys: [...keys.values()] };
}