In this section
- Classify transform · spiders / species/genome-spider/lib/classify.mjs lines 1–95
- Edges ingest · spiders / species/genome-spider/lib/edges.mjs lines 1–224
- Git other · spiders / species/genome-spider/lib/git.mjs lines 1–107
- Markers transform · spiders / species/genome-spider/lib/markers.mjs lines 1–151
- Schema transform · spiders / species/genome-spider/lib/schema.mjs lines 1–100
Classify
A JavaScript module in the genome spider folder of Spiders that strips timestamp (`stripTimestamp`).
transformspiders / species/genome-spider/lib/classify.mjs · lines 1–95 of 95
- What it does
- It calculates its inputs. Defines classifyPath, stripTimestamp, logicalGroupKey, pathIsSkipped.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "Content is only read — for imports, JSON provenance, functions and constants — from files under a curated set of directory/ filename conventions (`modules/`, `parts/`, `cartridges/`, `manifests/`, `proofs/`, `test/`, `engine/`, `src/`, `sources/`, `data/`, `scripts/`, `tools/`, `.github/workflows/`, plus `*.proof.mjs` and `index.html` wherever they live) — see `lib/classify.mjs`."
- Downstream impact
- Used directly by 2 files: Edges (spiders); Spider (spiders).
- What it achieves
- It classifies path (`classifyPath`) and is built from the strip timestamp helper (`stripTimestamp`) and the logical group key helper (`logicalGroupKey`). Turns a repo-relative path into a genome node "kind" and a "logical name" (the filename with its leading generation timestamp, if any, stripped off).
- Why it matters
- Imported by Edges and Spider.
- Application
- spiders · species/genome-spider/lib · JavaScript module
- Uses
- none found
- Used by
- imported by Edges (import), imported by Spider (import)
- Produces
- classifyPath, stripTimestamp, logicalGroupKey, COMPOSABLE_KINDS, TEXT_EXT, SKIP_SEGMENT, pathIsSkipped
- Defines here
- classifyPath, stripTimestamp, logicalGroupKey, pathIsSkipped
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 species/genome-spider/lib/classify.mjs:1-95 · blob d0ae0efe798e9d10e26143e5bf79175ce0a32681 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
// classify.mjs — turns a repo-relative path into a genome node "kind" and a
// "logical name" (the filename with its leading generation timestamp, if
// any, stripped off). This is heuristic, not certified: it reads directory
// and filename conventions actually observed across the estate (see
// genome-spider/README.md "What this deliberately does not claim").
const TIMESTAMP_PREFIX = /^(\d{8,14})-(.+)$/; // e.g. 202609011950-geodesy.js -> geodesy.js
const DIR_KIND_RULES = [
[/(^|\/)\.github\/workflows(\/|$)/i, 'workflow'],
[/(^|\/)modules(\/|$)/i, 'module'],
[/(^|\/)parts(\/|$)/i, 'part'],
[/(^|\/)cartridges(\/|$)/i, 'cartridge'],
[/(^|\/)manifests(\/|$)/i, 'manifest'],
[/(^|\/)proofs?(\/|$)/i, 'proof-suite'],
[/(^|\/)test(s)?(\/|$)/i, 'proof-suite'],
[/(^|\/)(engine|src)(\/|$)/i, 'source-unit'],
[/(^|\/)sources(\/|$)/i, 'pinned-source'],
[/(^|\/)(data|scopes)(\/|$)/i, 'data-product'],
[/(^|\/)scripts(\/|$)/i, 'tool-script'],
[/(^|\/)tools(\/|$)/i, 'tool-script'],
[/(^|\/)docs(\/|$)/i, 'doc'],
];
export function classifyPath(relPath) {
// Filename conventions are checked first and win over directory
// location: a file named *.proof.mjs is a proof suite even when it
// lives under a path that also matches /modules/ (gridatlas groups its
// proofs as tools/proofs/modules/<name>.proof.mjs — the "modules" there
// names which module the proof is *for*, not what the proof file *is*).
// An earlier version of this function checked directory rules first and
// misclassified all 18 of those proof files as kind 'module', which
// then made them look like dead code (a proof file run directly from
// the CLI is never imported by anything — that is not evidence of
// abandonment, it's how proofs are always run).
const base = relPath.split('/').pop() || relPath;
if (/\.proof\.mjs$/.test(base)) return 'proof-suite';
if (base === 'manifest.json' || /-composition\.json$/.test(base) || /-parts\.json$/.test(base)) {
return 'manifest';
}
if (base === 'index.html') return 'entry-point';
for (const [re, kind] of DIR_KIND_RULES) {
if (re.test(relPath)) return kind;
}
return 'file';
}
export function stripTimestamp(basename) {
const m = TIMESTAMP_PREFIX.exec(basename);
return m ? m[2] : basename;
}
export function logicalGroupKey(relPath) {
const dir = relPath.includes('/') ? relPath.slice(0, relPath.lastIndexOf('/')) : '';
const base = relPath.split('/').pop();
return `${dir}::${stripTimestamp(base)}`;
}
// Kinds that are expected to be *composed into* something else (an artefact
// or a manifest) rather than being terminal, load-bearing files themselves.
// Only these are eligible dead-code / uncomposed candidates — flagging a
// README or a workflow as "dead" because nothing imports it is a false
// positive class this list exists to avoid.
//
// 'pinned-source' (anything under a sources/ directory) is deliberately
// excluded even though the name suggests it should qualify: across this
// estate sources/ holds reference and provenance material — extraction
// snapshots, provenance manifests, docs about upstream data sources — not
// code a manifest is expected to pull back in. A first version of this
// detector included it and flagged 20 files this way (ventus-grid-engine's
// sources/deeplink-extracts/*, spiders/docs/sources/*.md, data-grid-gb's
// sources/*-manifest.json) that are working as designed, not abandoned.
export const COMPOSABLE_KINDS = new Set(['module', 'part']);
// Extensions genome-spider will read into memory and pattern-match. Binary
// or vendored-format files are never opened.
export const TEXT_EXT = new Set([
'.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '.py',
'.json', '.yml', '.yaml', '.html', '.htm', '.md', '.css',
]);
// Segments excluded from *content scanning* (function/constant extraction,
// import/JSON parsing). They are still counted, by filename only, for the
// RE-DOING marker — a "releases" directory full of timestamped rebuilds is
// exactly the evidence that marker exists to surface.
export const SKIP_SEGMENT = new Set([
'.git', 'node_modules', '__pycache__', 'dist', 'vendor', 'site-packages',
'coverage', 'homepage_versions', 'site_versions', 'nightly', 'releases',
'.claude-worktrees', 'pipelinenews-worktrees',
]);
export function pathIsSkipped(relPath) {
const segs = relPath.split('/');
return segs.some((s) => SKIP_SEGMENT.has(s));
}Edges
A JavaScript module in the genome spider folder of Spiders that uses SHA-256 using data from ...
ingestspiders / species/genome-spider/lib/edges.mjs · lines 1–224 of 224 · pattern lineOf (shared by 12 files)
- What it does
- It fetches data. Defines 9 functions or classes, including lineOf, snippet, resolveWithinRepo, importEdges, fetchEdges. Uses libraries node:path. Side effects: makes network requests.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: data source: ...; JSON file modules.json.
- Downstream impact
- Used directly by 1 file: Spider (spiders).
- What it achieves
- It resolves within repo (`resolveWithinRepo`) and is built from the line of helper (`lineOf`) and the snippet step (`snippet`). Evidenced, real dependency detection. Every edge this module returns carries the file and the pattern that produced it, because an unevidenced edge in a dependency map is worse than a missing one (that rule is enforced again, mechanically, by genome.proof.mjs).
- Why it matters
- Imported by Spider.
- Application
- spiders · species/genome-spider/lib · JavaScript module
- Uses
- Classify (import), node:path
- Used by
- imported by Spider (import), mentioned in Standalone (comment link)
- Produces
- importEdges, fetchEdges, workflowUsesEdges, jsonProvenanceEdges, isTextFile
- Defines here
- lineOf, snippet, resolveWithinRepo, importEdges, fetchEdges, workflowUsesEdges, jsonProvenanceEdges, walk, isTextFile
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 species/genome-spider/lib/edges.mjs:1-224 · blob 857c1d6a73420d6ba5f56601a589bf218b696a70 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: agent_infra · users: ai_agent · canonical: unknown
// edges.mjs — evidenced, real dependency detection. Every edge this module
// returns carries the file and the pattern that produced it, because an
// unevidenced edge in a dependency map is worse than a missing one (that
// rule is enforced again, mechanically, by genome.proof.mjs).
import path from 'node:path';
import { TEXT_EXT } from './classify.mjs';
const RE_IMPORT_FROM = /\bimport\s+(?:[\s\S]*?\bfrom\s+)?['"]([^'"]+)['"]/g;
const RE_REQUIRE = /\brequire\(\s*['"]([^'"]+)['"]\s*\)/g;
const RE_FETCH_URL = /\bfetch\(\s*['"]([^'"]+)['"]/g;
const RE_ACTION_USES = /^\s*(?:-\s*)?uses:\s*([\w.-]+\/[\w.-]+)@([^\s#]+)/gm;
const RE_WORKFLOW_REPOSITORY = /\brepository:\s*['"]?([\w.-]+\/[\w.-]+)['"]?/g;
const PATH_LIKE = /^(?:\.{1,2}\/)?[\w.\-/]+\.(?:js|mjs|cjs|jsx|ts|tsx|py|json|html|htm|css)$/i;
const HEX40 = /^[0-9a-f]{40}$/;
const HEX_ANY = /^[0-9a-f]{7,64}$/;
function lineOf(text, index) {
let line = 1;
for (let i = 0; i < index && i < text.length; i++) if (text[i] === '\n') line++;
return line;
}
function snippet(text, index) {
const start = Math.max(0, text.lastIndexOf('\n', index) + 1);
let end = text.indexOf('\n', index);
if (end < 0) end = text.length;
return text.slice(start, end).trim().slice(0, 160);
}
/** Resolve a relative-looking specifier against the file's own directory,
* then against the repo root, returning the repo-relative path if it
* names a file this repo actually tracks. Returns null otherwise — a
* specifier that resolves to nothing is not evidence of anything. */
function resolveWithinRepo(fromRelDir, specifier, trackedSet) {
const candidates = [];
if (specifier.startsWith('.')) {
candidates.push(path.posix.normalize(path.posix.join(fromRelDir, specifier)));
} else {
candidates.push(path.posix.normalize(specifier));
candidates.push(path.posix.normalize(path.posix.join(fromRelDir, specifier)));
}
for (const c of candidates) {
const norm = c.replace(/^(\.\.\/)+/, '').replace(/^\.\//, '');
if (trackedSet.has(norm)) return norm;
// extension-less import (common for .mjs written without the suffix)
for (const ext of ['.js', '.mjs', '.cjs']) {
if (trackedSet.has(norm + ext)) return norm + ext;
}
}
return null;
}
/** import/require edges, intra-repo only (cross-repo package imports are
* not how this estate links code — fetch, pinned SHAs and manifest path
* strings are). */
export function importEdges(relPath, text, trackedSet) {
const out = [];
const dir = relPath.includes('/') ? relPath.slice(0, relPath.lastIndexOf('/')) : '';
for (const re of [RE_IMPORT_FROM, RE_REQUIRE]) {
re.lastIndex = 0;
let m;
while ((m = re.exec(text))) {
const spec = m[1];
const resolved = resolveWithinRepo(dir, spec, trackedSet);
if (!resolved || resolved === relPath) continue;
out.push({
toPath: resolved,
type: 'imports',
evidence: { file: relPath, line: lineOf(text, m.index), pattern: re === RE_IMPORT_FROM ? 'import ... from' : 'require(...)', snippet: snippet(text, m.index) },
});
}
}
return out;
}
/** fetch('https://...') edges to other repos in the estate, matched by
* raw.githubusercontent.com/OWNER/REPO/... or OWNER.github.io/REPO/... */
export function fetchEdges(relPath, text, owner, knownRepoNames) {
const out = [];
RE_FETCH_URL.lastIndex = 0;
let m;
while ((m = RE_FETCH_URL.exec(text))) {
const url = m[1];
let target = null;
let mm;
if ((mm = new RegExp(`raw\\.githubusercontent\\.com/${owner}/([\\w.-]+)/`, 'i').exec(url))) {
target = mm[1];
} else if ((mm = new RegExp(`${owner}\\.github\\.io/([\\w.-]+)/?`, 'i').exec(url))) {
target = mm[1];
} else if ((mm = new RegExp(`api\\.github\\.com/repos/${owner}/([\\w.-]+)`, 'i').exec(url))) {
target = mm[1];
}
if (target && knownRepoNames.has(target)) {
out.push({
toRepo: target,
type: 'fetch',
evidence: { file: relPath, line: lineOf(text, m.index), pattern: 'fetch(url)', snippet: snippet(text, m.index) },
});
}
}
return out;
}
/** uses: owner/repo@<sha> in a workflow — pinned-action edges, and the
* input the pinned-actions vaccine checks (see genome.proof.mjs). */
export function workflowUsesEdges(relPath, text) {
const out = [];
RE_ACTION_USES.lastIndex = 0;
let m;
while ((m = RE_ACTION_USES.exec(text))) {
const [, ref, pin] = m;
out.push({
toRepo: ref, // may be "owner/repo" or "owner/repo/subpath"
pinned: HEX40.test(pin),
pin,
type: 'pinned-action',
evidence: { file: relPath, line: lineOf(text, m.index), pattern: 'uses: owner/repo@sha', snippet: snippet(text, m.index) },
});
}
RE_WORKFLOW_REPOSITORY.lastIndex = 0;
while ((m = RE_WORKFLOW_REPOSITORY.exec(text))) {
out.push({
toRepo: m[1],
type: 'workflow-checkout',
evidence: { file: relPath, line: lineOf(text, m.index), pattern: 'checkout repository:', snippet: snippet(text, m.index) },
});
}
return out;
}
/** Walk parsed JSON looking for (a) string values that look like a
* repo-relative source path and resolve to a tracked file — manifest
* composition evidence, carrying a sibling sha256/bytes when present —
* and (b) {repository, tree|sha|ref|commit} pairs naming a pinned
* cross-repo source. Both are how this estate actually declares
* provenance: JSON string literals, not code-level imports. */
export function jsonProvenanceEdges(relPath, jsonText, trackedSet, knownRepoNames) {
const out = [];
let data;
try {
data = JSON.parse(jsonText);
} catch {
return out; // not valid JSON; no evidence to extract
}
const dir = relPath.includes('/') ? relPath.slice(0, relPath.lastIndexOf('/')) : '';
const seen = new Set();
function walk(node, pointer) {
if (node === null || typeof node !== 'object') return;
if (Array.isArray(node)) {
node.forEach((v, i) => walk(v, `${pointer}/${i}`));
return;
}
// (a) path-like string leaves, with an optional sibling hash.
for (const [key, val] of Object.entries(node)) {
if (typeof val === 'string' && PATH_LIKE.test(val)) {
const candidates = [
path.posix.normalize(val.replace(/^\.\//, '')),
path.posix.normalize(path.posix.join(dir, val)),
];
let resolved = null;
for (const c of candidates) {
const norm = c.replace(/^(\.\.\/)+/, '');
if (trackedSet.has(norm)) { resolved = norm; break; }
}
if (resolved) {
const dedupeKey = `${resolved}@${pointer}/${key}`;
if (!seen.has(dedupeKey)) {
seen.add(dedupeKey);
const sha256 = typeof node.sha256 === 'string' ? node.sha256 : null;
out.push({
toPath: resolved,
type: 'manifest-path',
sha256,
evidence: { file: relPath, line: 0, pattern: `json:"${key}"`, snippet: `${pointer}/${key} = "${val}"` },
});
}
}
}
}
// (b) {(source_)?repo(sitory)?: "Owner/Name", (head_|source_)?(tree|sha|ref|commit): "<hex>"}
// e.g. gridatlas/atlas/modules.json's source_patterns_from, and
// ventus-grid-engine/sources/*-provenance.json's {source_repo,
// source_path, head_sha} triples.
const repoKey = Object.keys(node).find((k) => /^(source_)?repo(sitory)?$/i.test(k));
const shaKey = Object.keys(node).find((k) => /^(head_|source_)?(tree|sha|ref|commit)$/i.test(k));
if (repoKey && shaKey && typeof node[repoKey] === 'string' && typeof node[shaKey] === 'string') {
const repoVal = node[repoKey];
const shaVal = node[shaKey];
const shortName = repoVal.includes('/') ? repoVal.split('/').pop() : repoVal;
if (knownRepoNames.has(shortName) && HEX_ANY.test(shaVal)) {
out.push({
toRepo: shortName,
type: 'json-provenance',
pin: shaVal,
evidence: { file: relPath, line: 0, pattern: `json:"${repoKey}"+"${shaKey}"`, snippet: `${pointer}: ${repoKey}=${repoVal}, ${shaKey}=${shaVal}${node.source_path ? ', source_path=' + node.source_path : ''}` },
});
}
}
// (c) a map whose keys are themselves repo names to a pinned sha, e.g.
// {"globalgrid2050": "7d00781b...", "gridatlas": "64268fd0"}.
for (const [key, val] of Object.entries(node)) {
if (knownRepoNames.has(key) && typeof val === 'string' && HEX_ANY.test(val)) {
out.push({
toRepo: key,
type: 'json-provenance',
pin: val,
evidence: { file: relPath, line: 0, pattern: 'json: {<repo-name>: <sha>}', snippet: `${pointer}/${key} = "${val}"` },
});
}
}
for (const [key, val] of Object.entries(node)) {
if (val && typeof val === 'object') walk(val, `${pointer}/${key}`);
}
}
walk(data, '');
return out;
}
export function isTextFile(relPath) {
const ext = path.extname(relPath).toLowerCase();
return TEXT_EXT.has(ext);
}Git
A JavaScript module in the genome spider folder of Spiders that resolves repo root (`resolveRepoRoot`).
otherspiders / species/genome-spider/lib/git.mjs · lines 1–107 of 107
- What it does
- It lists and searches its content. Defines 8 functions or classes, including run, isGitRepo, repoStats, lsFiles, topRevisedFiles. Uses libraries node:child_process, node:path. Side effects: starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 2 files: Lineage (spiders); Spider (spiders).
- What it achieves
- It resolves repo root (`resolveRepoRoot`) and is built from the run step (`run`) and the is git repo helper (`isGitRepo`). Thin, evidenced wrapper over the git CLI.
- Why it matters
- Imported by Lineage and Spider.
- Application
- spiders · species/genome-spider/lib · JavaScript module
- Uses
- node:child_process, node:path
- Used by
- imported by Lineage (import), imported by Spider (import)
- Produces
- isGitRepo, repoStats, lsFiles, topRevisedFiles, fileLastCommit, fileHistory, resolveRepoRoot
- Defines here
- run, isGitRepo, repoStats, lsFiles, topRevisedFiles, fileLastCommit, fileHistory, resolveRepoRoot
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 species/genome-spider/lib/git.mjs:1-107 · blob 6d7043a5c683cad069d47570f9bdb0df0f935312 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unknown
// git.mjs — thin, evidenced wrapper over the git CLI. No network, no auth,
// no dependency outside Node's stdlib. Every call is against a local
// checkout already on disk; genome-spider never clones or fetches.
import { spawnSync } from 'node:child_process';
import path from 'node:path';
const MAX_BUFFER = 64 * 1024 * 1024; // 64MB — globalgrid2050's log is large but text.
function run(cwd, args) {
const r = spawnSync('git', args, {
cwd,
encoding: 'utf8',
maxBuffer: MAX_BUFFER,
windowsHide: true,
});
if (r.error) {
return { ok: false, stdout: '', stderr: String(r.error.message || r.error), status: -1 };
}
return {
ok: r.status === 0,
stdout: r.stdout || '',
stderr: r.stderr || '',
status: r.status,
};
}
export function isGitRepo(dir) {
const r = run(dir, ['rev-parse', '--is-inside-work-tree']);
return r.ok && r.stdout.trim() === 'true';
}
/** Repo-wide facts: first/last commit, commit count. One `git log`. */
export function repoStats(dir) {
const log = run(dir, ['log', '--date=iso-strict', '--pretty=format:%H|%ad']);
if (!log.ok || !log.stdout.trim()) {
return { ok: false, reason: log.stderr.trim() || 'git log returned nothing', commits: [] };
}
const commits = log.stdout.trim().split('\n').map((line) => {
const i = line.indexOf('|');
return { sha: line.slice(0, i), date: line.slice(i + 1) };
});
// git log is newest-first.
return {
ok: true,
commit_count: commits.length,
last_commit: commits[0],
first_commit: commits[commits.length - 1],
};
}
/** Every path git currently tracks (respects .gitignore already, since
* ls-files only lists what's indexed). Forward-slash separated. */
export function lsFiles(dir) {
const r = run(dir, ['ls-files', '-z']);
if (!r.ok) return { ok: false, files: [], reason: r.stderr.trim() };
const files = r.stdout.split('\0').filter(Boolean);
return { ok: true, files };
}
/** Top-N most-revised tracked files by commit count touching them. One
* `git log --name-only` walk, counted in JS (avoids a shell pipeline so
* this runs the same on Windows and in CI). */
export function topRevisedFiles(dir, limit = 8) {
const r = run(dir, ['log', '--pretty=format:', '--name-only']);
if (!r.ok) return { ok: false, files: [], reason: r.stderr.trim() };
const counts = new Map();
for (const line of r.stdout.split('\n')) {
const p = line.trim();
if (!p) continue;
counts.set(p, (counts.get(p) || 0) + 1);
}
const sorted = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit);
return { ok: true, files: sorted.map(([file, commits]) => ({ path: file, commits })) };
}
/** The last commit (sha + ISO date) that touched a specific tracked path.
* This is the clock genome-spider trusts for UNCOMPOSED — the file's own
* git history, not any timestamp encoded in its filename. */
export function fileLastCommit(dir, relPath) {
const r = run(dir, ['log', '-1', '--date=iso-strict', '--pretty=format:%H|%ad', '--', relPath]);
if (!r.ok || !r.stdout.trim()) return null;
const line = r.stdout.trim();
const i = line.indexOf('|');
if (i < 0) return null;
return { sha: line.slice(0, i), date: line.slice(i + 1) };
}
/** first_commit, last_commit and commit_count for one tracked path, in a
* single `git log` call. This is the per-unit-node equivalent of
* repoStats(). */
export function fileHistory(dir, relPath) {
const r = run(dir, ['log', '--date=iso-strict', '--pretty=format:%H|%ad', '--', relPath]);
if (!r.ok || !r.stdout.trim()) return null;
const commits = r.stdout.trim().split('\n').map((line) => {
const i = line.indexOf('|');
return { sha: line.slice(0, i), date: line.slice(i + 1) };
});
return {
commit_count: commits.length,
last_commit: commits[0],
first_commit: commits[commits.length - 1],
};
}
export function resolveRepoRoot(baseDir, relPath) {
return path.join(baseDir, ...relPath.split('/'));
}Markers
A JavaScript module in the genome spider folder of Spiders that finds next top level (`findNextTopLevel`), normalizes body (`normalizeBody`) and extracts functions (`extractFunctions`), using SHA-256 and haversine.
transformspiders / species/genome-spider/lib/markers.mjs · lines 1–151 of 151 · pattern lineOf (shared by 12 files)
- What it does
- It calculates its inputs. Defines 8 functions or classes, including balanceFrom, findNextTopLevel, normalizeBody, hashOf, lineOf. Uses libraries node:crypto.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 1 file: Spider (spiders).
- What it achieves
- It finds next top level (`findNextTopLevel`), normalizes body (`normalizeBody`) and extracts functions (`extractFunctions`). Balance-match a `brace/paren/bracket` starting at text[`startIdx`] (which must be the opening char), skipping over string/template literals and comments so braces inside a quoted string don't unbalance the scan.
- Why it matters
- Imported by Spider.
- Application
- spiders · species/genome-spider/lib · JavaScript module
- Uses
- node:crypto
- Used by
- imported by Spider (import)
- Produces
- extractFunctions, KNOWN_CONSTANT_FAMILIES, extractKnownFamilyHits, extractNamedConstants
- Defines here
- balanceFrom, findNextTopLevel, normalizeBody, hashOf, lineOf, extractFunctions, extractKnownFamilyHits, extractNamedConstants
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 species/genome-spider/lib/markers.mjs:1-151 · blob 55a8612375ec15ac49534b94cbf2b02de4739710 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
// markers.mjs — per-file extraction used to build the genome markers:
// DUPLICATION (same function/constant in >1 place), DRIFT (copies that
// disagree), DEAD CODE and RE-DOING and UNCOMPOSED (built in spider.mjs
// from these extractions plus the edge graph). This module only extracts;
// it does not decide anything is a defect on its own.
import crypto from 'node:crypto';
/** Balance-match a brace/paren/bracket starting at text[startIdx] (which
* must be the opening char), skipping over string/template literals and
* comments so braces inside a quoted string don't unbalance the scan.
* Returns the index of the matching closer, or -1. */
function balanceFrom(text, startIdx, open, close) {
let depth = 0;
let i = startIdx;
let quote = null; // ', ", ` while inside a string/template
let inLineComment = false;
let inBlockComment = false;
for (; i < text.length; i++) {
const ch = text[i];
const next = text[i + 1];
if (inLineComment) {
if (ch === '\n') inLineComment = false;
continue;
}
if (inBlockComment) {
if (ch === '*' && next === '/') { inBlockComment = false; i++; }
continue;
}
if (quote) {
if (ch === '\\') { i++; continue; }
if (ch === quote) quote = null;
continue;
}
if (ch === '/' && next === '/') { inLineComment = true; i++; continue; }
if (ch === '/' && next === '*') { inBlockComment = true; i++; continue; }
if (ch === '"' || ch === "'" || ch === '`') { quote = ch; continue; }
if (ch === open) depth++;
else if (ch === close) {
depth--;
if (depth === 0) return i;
}
}
return -1;
}
function findNextTopLevel(text, fromIdx, ch, stopChars) {
for (let i = fromIdx; i < text.length; i++) {
if (text[i] === ch) return i;
if (stopChars.has(text[i])) return -1;
}
return -1;
}
function normalizeBody(body) {
// Strip comments and collapse whitespace so formatting-only differences
// (spacing, line breaks) don't register as disagreement; genuine logic
// differences still change the hash.
const noBlockComments = body.replace(/\/\*[\s\S]*?\*\//g, ' ');
const noLineComments = noBlockComments.replace(/\/\/[^\n]*/g, ' ');
return noLineComments.replace(/\s+/g, ' ').trim();
}
function hashOf(s) {
return crypto.createHash('sha256').update(s, 'utf8').digest('hex').slice(0, 16);
}
const RE_FUNCTION_DECL = /\bfunction\s+([A-Za-z_$][\w$]*)\s*\(/g;
const RE_ARROW_ASSIGN = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\{/g;
function lineOf(text, index) {
let line = 1;
for (let i = 0; i < index && i < text.length; i++) if (text[i] === '\n') line++;
return line;
}
/** Extract named function-shaped units: classic `function name(...) {...}`
* and `const name = (...) => {...}`. Excludes anonymous/inline callbacks
* on purpose — those can't recur "by name" so they're not evidence of
* duplication in the sense this genome marker means. */
export function extractFunctions(text) {
const out = [];
for (const re of [RE_FUNCTION_DECL, RE_ARROW_ASSIGN]) {
re.lastIndex = 0;
let m;
while ((m = re.exec(text))) {
const name = m[1];
let braceStart;
if (re === RE_FUNCTION_DECL) {
const parenIdx = text.indexOf('(', m.index);
if (parenIdx < 0) continue;
const parenEnd = balanceFrom(text, parenIdx, '(', ')');
if (parenEnd < 0) continue;
braceStart = findNextTopLevel(text, parenEnd + 1, '{', new Set([';']));
} else {
braceStart = m.index + m[0].length - 1; // regex ends on the '{'
}
if (braceStart == null || braceStart < 0 || text[braceStart] !== '{') continue;
const braceEnd = balanceFrom(text, braceStart, '{', '}');
if (braceEnd < 0) continue;
const body = text.slice(braceStart, braceEnd + 1);
// Skip trivial one-line pass-throughs; too small to mean anything as
// "duplication" and they inflate the marker with noise.
if (body.length < 24) continue;
const normalized = normalizeBody(body);
out.push({
name,
line: lineOf(text, m.index),
length: body.length,
hash: hashOf(normalized),
});
}
}
return out;
}
// Curated, cited constant families: a value known, from the estate's own
// documentation, to have drifted. See grid-distance-maths/docs/EARTH-MODEL.md
// and README.md for the citation this table encodes.
export const KNOWN_CONSTANT_FAMILIES = [
{
id: 'earth-radius-km',
description: 'Earth radius (km) used in a haversine/geodesy distance calculation',
pattern: /\b(6378\.137|6371\.0088|6384\.7272|6367\.4|6366\.707)\b/g,
citation: 'Ventusltd/grid-distance-maths README.md and docs/EARTH-MODEL.md',
},
];
export function extractKnownFamilyHits(text) {
const out = [];
for (const family of KNOWN_CONSTANT_FAMILIES) {
const re = new RegExp(family.pattern.source, family.pattern.flags);
let m;
while ((m = re.exec(text))) {
out.push({ family: family.id, value: m[1], line: lineOf(text, m.index) });
}
}
return out;
}
// Generic: a SCREAMING_CASE constant assignment, by name, wherever declared.
const RE_CONST_DECL = /^[ \t]*(?:export\s+)?(?:const|let|var)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*([0-9]+(?:\.[0-9]+)?)\s*;/gm;
export function extractNamedConstants(text) {
const out = [];
RE_CONST_DECL.lastIndex = 0;
let m;
while ((m = RE_CONST_DECL.exec(text))) {
out.push({ name: m[1], value: m[2], line: lineOf(text, m.index) });
}
return out;
}Schema
A JavaScript module in the genome spider folder of Spiders that builds nodes doc (`buildNodesDoc`) and edges doc (`buildEdgesDoc`) and builds manifest doc (`buildManifestDoc`).
transformspiders / species/genome-spider/lib/schema.mjs · lines 1–100 of 100
- What it does
- It calculates its inputs. Defines coordFor, buildNodesDoc, buildEdgesDoc, buildManifestDoc.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "This shape is built in `lib/schema.mjs`, which repeats these same citations next to the code that acts on them."
- Inputs & outputs
- In: JSON file nodes.json; JSON file edges.json.
- Downstream impact
- Used directly by 1 file: Spider (spiders).
- What it achieves
- It builds nodes doc (`buildNodesDoc`), builds edges doc (`buildEdgesDoc`) and builds manifest doc (`buildManifestDoc`). Shapes genome-spider's internal node/edge arrays into the exact data files the Spider Sandbox already knows how to load.
- Why it matters
- Imported by Spider.
- Application
- spiders · species/genome-spider/lib · JavaScript module
- Uses
- none found
- Used by
- imported by Spider (import)
- Produces
- buildNodesDoc, buildEdgesDoc, buildManifestDoc
- Defines here
- coordFor, buildNodesDoc, buildEdgesDoc, buildManifestDoc
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 species/genome-spider/lib/schema.mjs:1-100 · blob 03504007c2258534776ddc90a9a305eb1c89422e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
// schema.mjs — shapes genome-spider's internal node/edge arrays into the
// exact data files the Spider Sandbox already knows how to load.
//
// The schema below is not invented here. It was read out of the running
// sandbox and its live data, with citations:
//
// Loader (which files, what shape):
// data-federation-map-for-globalgrid2050-all-repos/dashboard/sandbox/
// spider_full_po_test.html:196-200 `loadRoot()` — fetches
// "nodes.json" and "edges.json" from a sibling data/ directory.
// spider_full_po_test.html:198 `reshapeNodes(fc)` — reads
// `fc.features[].properties.{label, repo_type|scope_type,
// rag|status, status_reason, child_manifest}`. geometry/coordinates
// are present in the source data but NOT read by this function —
// included here for shape-fidelity only, not load-bearing.
// spider_full_po_test.html:200 — edges reshaped as
// `(ef.edges||[]).map(e => [e[0], e[1], e[2]])`: an index-array,
// i.e. edges reference *array position* in the nodes list, not id.
//
// Confirmed against the live data files (byte-inspected):
// data-federation-map-for-globalgrid2050-all-repos/live_sandbox/
// federation_control_ledger/data/nodes.json — a GeoJSON
// FeatureCollection matching the shape above.
// .../data/edges.json:2 — `"edge_format": "index-array-v1"`, confirming
// the index-array reading above is the declared contract, not an
// accident of one file.
// .../data/manifest.json — the cartridge manifest shape mirrored by
// buildManifestDoc() below (schema_version, scope, counts, sources).
function coordFor(i, n) {
// Cosmetic only — reshapeNodes() never reads geometry. Spread nodes on a
// circle so the file is inspectable/plottable if someone opens it in a
// GeoJSON viewer, without asserting any real geography.
const angle = (2 * Math.PI * i) / Math.max(n, 1);
const r = 60;
return [Number((Math.cos(angle) * r).toFixed(2)), Number((Math.sin(angle) * r).toFixed(2))];
}
export function buildNodesDoc(genomeNodes) {
const features = genomeNodes.map((n, i) => ({
type: 'Feature',
id: n.id,
geometry: { type: 'Point', coordinates: coordFor(i, genomeNodes.length) },
properties: {
label: n.label,
repo_type: n.kind,
scope_type: n.kind,
rag: n.rag,
status: n.rag,
status_reason: n.status_reason || '',
importance_score: n.importance_score ?? 0.5,
child_manifest: null,
},
}));
return { type: 'FeatureCollection', features };
}
export function buildEdgesDoc(genomeNodes, genomeEdges) {
const indexOf = new Map(genomeNodes.map((n, i) => [n.id, i]));
const edges = [];
const droppedUnresolved = [];
for (const e of genomeEdges) {
const f = indexOf.get(e.from);
const t = indexOf.get(e.to);
if (f === undefined || t === undefined) {
droppedUnresolved.push(e);
continue;
}
edges.push([f, t, e.type]);
}
return {
doc: {
edge_format: 'index-array-v1',
status_note: 'Emitted by spiders/species/genome-spider/spider.mjs. Every edge above is also present, with its evidence citation, in genome.json#edges.',
edges,
},
droppedUnresolved,
};
}
export function buildManifestDoc({ generatedAt, nodeCount, edgeCount }) {
return {
schema_version: 'atlas-cartridge-v0.2',
generated_utc: generatedAt,
public_title: 'Ventus estate genome',
public_strapline: 'Repositories, internal units and the dependencies genome-spider could evidence between them',
scope: {
id: 'estate-genome',
label: 'Estate genome (genome-spider)',
scope_type: 'repository_federation',
parent_manifest: null,
},
counts: { nodes: nodeCount, edges: edgeCount, sectors: 0 },
key_law_status: 'SCREENING_GRADE_NOT_CERTIFICATION',
key_note: 'Every node carries real git history (first/last commit, commit count). Every edge carries a file+line or JSON-pointer citation. Genome markers (duplication, drift, dead code, re-doing, uncomposed) are listed separately in genome.json and are not folded into this cartridge\'s rag colouring beyond a coarse amber/red flag.',
unresolved_findings: [],
tier: 'geojson',
sources: { nodes: 'nodes.json', edges: 'edges.json', layers: null, sectors: null },
};
}