diff --git a/.gitignore b/.gitignore index f43039c..a03b591 100644 --- a/.gitignore +++ b/.gitignore @@ -219,3 +219,7 @@ __marimo__/ # belt-and-suspenders: such records must never be committed or reach CI logs. ai-benchmark-*.json ai-records/ + +# codegraph output: derived from git history, regenerate with +# python3 tools/codegraph/codegraph.py (see tools/codegraph/README.md) +codegraph-vault/ diff --git a/docs/journal/DECISIONS.md b/docs/journal/DECISIONS.md index 9934a50..0d82d24 100644 --- a/docs/journal/DECISIONS.md +++ b/docs/journal/DECISIONS.md @@ -302,3 +302,7 @@ ## 2026-10-29 — PR #40 final review repair - 2026-10-29 · Preserve existing exact-owned `Default`/`DEFAULT` namespaces before rejecting creation of new variants of the built-in default. Greptile identified that the early validation guard made legacy saved state inaccessible. Move the reservation to the new-directory branch and test existing ownership/session preservation plus rejection before writes. Reverse: revert this focused validation adjustment only if a replacement preserves existing owners. + +## 2026-11-27 — codegraph tool and review + +- 2026-11-27 · Keep the generated Obsidian vault (`codegraph-vault/`) out of git and commit only the generator, its config and the review notes. A committed projection can never include the commit that adds it, it is fully derivable from history in seconds, and it is about 850 files of churn per regeneration. Reverse: remove the `.gitignore` entry and commit a vault snapshot if a static copy is needed for readers without Python. diff --git a/docs/review/codegraph-review_v1.0.0_2026-11-27.md b/docs/review/codegraph-review_v1.0.0_2026-11-27.md new file mode 100644 index 0000000..320e72f --- /dev/null +++ b/docs/review/codegraph-review_v1.0.0_2026-11-27.md @@ -0,0 +1,83 @@ +--- +title: "Code review grounded in the codegraph fold" +version: 1.0.0 +date: 2026-11-27 +provenance: "Generated by Claude (Claude Code thread) from tools/codegraph run at bb02bf263ea4 (main tip 91d8b89 + codegraph commit). Supersedes nothing; corrects circuit-review_v1.0.0_2026-11-27 where marked." +graph_digest: 4e56f250938e0fc7e7f867456b4137aec3471009645308fbe98419c96ba8ec92 +tags: [review, codegraph, circuit, determinism] +--- + +# Code review grounded in the codegraph fold + +**Run:** `python3 tools/codegraph/codegraph.py --repo . --out codegraph-vault` at `bb02bf263ea4`. +643 nodes, 2,983 edges, 130 commits. Fold law holds for 130/130 commits, and folding +the 112 first-parent deltas from empty reproduces HEAD. Call-site resolution: 2,973 exact, +410 unique, 112 ambiguous (ambiguous edges are kept in the vault, left out of the matrices). + +Every claim below says how it was checked: **graph** (a query over `_data/graph.json`), +**code** (read at the cited line), **numeric** (a Python replica of the Swift arithmetic), +or **general knowledge** (not observed in this repo). + +## Correction to the earlier circuit review + +The earlier review (finding 1) said the `hashValue` schema hash means "the T5 stale-prior +protocol fires every time". **That overstated it, and I'm withdrawing that part.** The +graph shows `CircuitSnapshot` is built only by `SynapticCircuit.snapshot()`, and the only +non-test caller of `snapshot()` is `FaultInjectionSuite.runFullSuite()`. No code decodes a +snapshot or compares `schemaHash`, so nothing fires today. The bug is real but latent (see 1). + +## Findings + +### 1. Schema hash is process-seeded (latent) +- **code** `SynapticCircuit.swift:424-428` hashes with `String((nodeKeys + edgeKeys).hashValue)`. +- **general knowledge** Swift seeds `Hasher` per process unless `SWIFT_DETERMINISTIC_HASHING` is set, so the value differs between launches. +- **graph** no reader of `schemaHash` outside tests; `testSnapshotSchemaHashIsStableWithNoChanges` compares two hashes in one process, so it cannot catch this. +- **Fix before snapshots are persisted:** SHA-256 over the sorted, joined keys. + +### 2. `widenUncertainty` lowers the mean, and often lowers the variance too +- **code** `CircuitTypes.swift:153-156` does `beta += amount`. The doc comment on `propagateUncertainty` says "never shifts target mean". +- **numeric** widening by 0.1: the mean always falls, and the variance *falls* for many priors, the default included: + + | prior | mean before → after | variance before → after | + |---|---|---| + | Beta(1,1) uninformed | 0.500 → 0.476 | 0.0833 → 0.0805 | + | Beta(2,2) | 0.500 → 0.488 | 0.0500 → 0.0490 | + | Beta(1,3) | 0.250 → 0.244 | 0.0375 → 0.0362 | + | Beta(8,2) lighthouse | 0.800 → 0.792 | 0.0145 → 0.0148 | + | Beta(1,0.5) | 0.667 → 0.625 | 0.0889 → 0.0901 | + + So on an uninformed neighbour, "widening" makes it *more* confident and less useful. +- **code** the test named `testWidenUncertaintyDoesNotChangeMean` (`Tests/SynapticCircuitTests.swift:230`) says in its own comment that the mean changes, and asserts only that alpha is unchanged. The name is false. +- **Fix:** scale both counts by k < 1 (mean kept, evidence weight down, variance up), keep `minimumAlpha`, and rename or rewrite the test to assert mean-preservation and variance increase. + +### 3. The 0.15 uncertainty threshold cannot be reached +- **code** `init` and `update` floor alpha at 1.0; `init` floors beta at 0.01. +- **numeric** over alpha ≥ 1 the Beta variance peaks at 0.0902 (alpha 1, beta 0.618); a 25M-point grid agrees. `instabilityUncertaintyThreshold` is 0.15, so `isEpistemicallyUnstable` is driven only by prediction error. +- **graph** that flag is persisted: `SynapseManager.observe` stores backward-pass `epistemicallyUnstable` in `EpochSnapshot`. +- Caveat: `SynapticPrior` uses synthesized `Codable`, which bypasses `init`, so a decoded prior could have alpha < 1. No decode path exists today. +- **Fix:** pick a threshold the state space can reach (for example 0.06), or normalise uncertainty by its maximum. + +### 4. Fault "collapse" by mean is unreachable; collapse by depth is reachable +- **code** `isPathological` is `depth >= 5 || (pre > 0.6 && post < 0.2)`. `injectFault` applies one update with eta = 0.1 × 2.5 = 0.25 at pass 0 (lower later). +- **numeric** the mean branch needs eta > 4α − β > 3.33 for any prior with pre > 0.6; the maximum eta is 0.25. A brute-force sweep (alpha, beta, lastPrediction, severity) found 0 hits; the lowest post-mean among pre > 0.6 priors was 0.524. Beta(8,2) moves 0.800 → 0.780 at most (the earlier review said about 0.017; the worst case is 0.0195). +- **code** the depth branch is reachable: a 5-hop chain where `severity × weight × 0.3 > 0.05` qualifies. +- **code** the collapse tests (`SynapticCircuitTests.swift:553-585`) use hand-built reports, so they never exercise the arithmetic. +- **Knock-on:** `recommendedAmplifier` caps at 1.5, which is the current static value. Worst-case drift gives 1.03 (lighthouse), 1.09 (uninformed), 1.33 (Beta(1,0.01)). It can only ever recommend lowering the amplifier. Its doc comment says the range is [1.0, 1.67]; the formula's range is [1.0, 1.5]. + +### 5. Amplifier naming conflict +- **code** ADR-003-004 says the error amplifier "does not replace" ROT_LAMBDA_AMPLIFIER. `CircuitTypes.swift:69-73` says it "Replaces static ROT_LAMBDA_AMPLIFIER". `INTEGRATION.md:98` says to update `errorDecayAmplifier` with `recommendedRotLambdaAmplifier`. Three sources, two meanings. Pick one and fix the other two. + +### 6. New: the circuit is computed but not wired into the weights +- **graph** `lighthouseFloor(for:isLighthouse:)`, `predictionError(for:)` and `connectivityFactor(for:)` have test callers only. `errorDecayAmplifier` has no reader. The whole `FaultInjectionSuite` (`runFullSuite`, `runTargetedSuite`, `auditLighthouses`) has no non-test caller. +- **code** `SynapseManager` holds `private let circuit = SynapticCircuit()`, registers nodes as `.uninformed`, and discards the forward pass (`_ = await circuit.forwardPass()`, line 167). Priors live only in memory. +- **Meaning:** the INTEGRATION.md recipe is not implemented, the ADR-004 bootstrapping discount has nothing to apply to yet, and findings 2-4 only reach users through the persisted instability flag. This is the main structural gap; it also lowers the urgency of 1. + +### 7. Smaller graph leads +- **graph** `EventLedger` (the append-only event path) has no test that constructs it (`grep EventLedger Tests/` finds nothing). 64 of 195 non-test functions have no test reach; that count undercounts reach through protocols and closures. +- **graph** file cycles: `AppMain ↔ ContentView`, `LighthouseStore ↔ SynapseManager`, `SynapseCore ↔ UserStorage`. No type-level cycles. +- **graph** churn: `SynapseCore` changed in 18 commits and has the highest fan-in (14 types, 19 files). It is the place a split would pay off. +- **graph** `SynapseCore.maybeInjectFaults(into:)` calls `random()` 7 times; fine for a feature, but runs that use it are not reproducible without a seeded generator. + +## Tool limits found during this review (failing loudly) +- `EventLedger.csvEscape(_:)` is listed as an uncalled private function. It is used as a function reference, `.map(EventLedger.csvEscape)` (`EventLedger.swift:199`). The resolver only sees calls with parentheses. Treat the "uncalled private" list as leads, and fix by emitting `references` edges for qualified member names. +- Resolution is by name, without type inference. Protocol dispatch and closures are undercounted. diff --git a/tools/codegraph/README.md b/tools/codegraph/README.md new file mode 100644 index 0000000..849f5a4 --- /dev/null +++ b/tools/codegraph/README.md @@ -0,0 +1,133 @@ +--- +title: codegraph +version: 0.1.0 +date: 2026-11-27 +provenance: built for mazze93/context-synapse on branch feat/codegraph-review +tags: [codegraph, code-review, obsidian, determinism, fold] +--- + +# codegraph + +Folds a repo's git history into a code graph, dependency matrices and an +Obsidian vault. Code change replays as a projection of a fold over the log: +each commit's graph is projected from its tree, diffed against its first +parent, and folding those deltas from the empty graph reproduces HEAD. + +Python 3.9+ standard library only. No network. Reads git objects, never the +working tree, so output is a pure function of +`(git objects reachable from --rev, config, generator version)`. + +## Run it + +From the repo root (on Mazze's Mac: `~/Projects/cognitive/context-synapse`): + +```zsh +python3 tools/codegraph/codegraph.py # HEAD -> ./codegraph-vault/ +python3 tools/codegraph/verify_determinism.py # prove it (seeds, rerun, clean copy, fold law) +python3 -m unittest discover -s tools/codegraph/tests -v # unit + end-to-end tests +``` + +Open `codegraph-vault/` as an Obsidian vault, or copy it into an existing +vault. Start at `00 Index.md`. Nothing to commit afterwards: the vault is +gitignored (see below). + +Options: `--rev ` folds up to any commit or tag; `--out ` writes +elsewhere; `--json-only` prints the graph digest and fold-law result and +writes nothing; `--config ` points at another config. + +## What it writes + +| Path | What | +|---|---| +| `00 Index.md` | counts, fold-law result, links to everything | +| `Timeline.md` | every commit in fold order with node/edge deltas | +| `Commits/Commit .md` | one note per commit: added, removed, changed nodes and edges, against the first parent | +| `Types/`, `Functions/`, `Files/`, `Modules/`, `Products/`, `Package/`, `Frameworks/`, `Dependencies/`, `External/`, `API/` | one note per node at HEAD, YAML frontmatter (`kind`, `path`, `lines`, `first_commit`, `last_commit`, `semantic_changes`, tags) and `[[wikilinks]]` for every edge in and out | +| `Removed/` | nodes that existed in history but not at HEAD, from their last known projection | +| `Matrix - modules/files/types.md` | full dependency matrices with a legend | +| `Review - Graph Findings.md` | graph queries: API probe sites, uncalled private functions, code no test reaches, cycles, fan-in, churn, resolution quality | +| `_data/graph.json` | the HEAD graph, canonical JSON | +| `_data/fold.json` | fold-law result and every commit with its delta digest | +| `_data/matrix-*.csv` | dense and sparse (edge list) matrices | +| `_data/sbom.cdx.json` | CycloneDX 1.5 SBOM of external package dependencies | +| `.codegraph-manifest.json` | sha256 of every generated file, generator and adapter versions, HEAD, config digest; no timestamp | +| `.archive/` | earlier copies of any file a later run replaced or dropped | + +## Guarantees and how they are checked + +- **Deterministic.** Everything is sorted; no timestamps, no `hash()`, no + set iteration order reaches output; git is called with a pinned locale + and plumbing formats. `verify_determinism.py` runs under three + `PYTHONHASHSEED` values and compares bytes. It was also run under + Python 3.9.25 and 3.13 with byte-identical output. +- **Idempotent.** A rerun writes nothing and leaves mtimes alone + (`written 0`). Verified by `verify_determinism.py`. +- **Clean-checkout equivalent.** `verify_determinism.py` exports the + committed generator with `git archive` and checks it produces the same + bytes, so uncommitted edits cannot leak into a result. +- **Fold law.** Every run checks `apply(parent, delta) == projection` for + every commit and that the mainline fold equals HEAD; the CLI exits 1 if + either fails. +- **Never destroys output.** The writer refuses a non-empty folder it did + not create, and moves any file it would overwrite or drop into + `.archive/-/` first. +- **Commit notes are immutable.** A commit note depends only on that commit + and its first parent (it records `generation`, not a list position), so + new history never rewrites an existing commit note. + +## Why the vault is gitignored + +A committed vault can never contain the commit that adds it: committing +the projection changes the log it is a projection of, so it would always +be one commit stale. It is also fully derivable (the determinism check is +the proof) and roughly 850 files. The repo keeps the generator, the +config and the tests; `.codegraph-manifest.json` and the graph digest in +`00 Index.md` let anyone confirm a vault matches a commit. + +## Resolution and its limits + +There is no type inference. Every edge records how it was resolved: +`exact` (a receiver, scope or type name pins it), `unique` (one visible +function fits the call's argument labels), or `ambiguous` (several fit; an +edge goes to each). Matrices leave ambiguous edges out and say how many. +Calls through a variable to a name in the adapter's ambient list (Swift +`append`, `write`, `update`, ...) are never classed `unique`. Local +functions and closures fold into their enclosing declaration; properties +count toward their type. These limits show up as missing or ambiguous +edges, never as crashes. + +A function used as a value without parentheses, such as +`.map(EventLedger.csvEscape)`, gets no edge yet, so it can appear in the +review's "private functions with no caller" list. Treat that list as leads. + +## Layout (adapter boundary) + +``` +codegraph.py CLI: fold -> render -> write +verify_determinism.py proof script +codegraph.config.json everything repo-specific +cgcore/ + adapters/ the only language-aware code + swift_lexer.py Swift tokens + swift_facts.py Swift file -> neutral facts (contract in its docstring) + swiftpm.py Package.swift / Package.resolved -> neutral manifest facts + __init__.py registry: LANGUAGES, MANIFESTS, ADAPTER_VERSION + build.py, resolve.py neutral facts -> graph for one snapshot + model.py canonical JSON, delta, apply (the fold algebra) + gitio.py read-only git plumbing + fold.py walk history, deltas, node history, fold-law check + matrix.py, sbom.py matrices and CycloneDX + vault_*.py, review.py Markdown rendering + writer.py the only module that writes files +tests/test_codegraph.py 14 tests incl. an end-to-end fold over a repo with a merge +``` + +To support another language, add an adapter that emits the same fact +shape and register it; nothing in `cgcore` outside `adapters/` changes. + +## Why sys.path + +The CLI prepends its own folder to `sys.path` so `import cgcore` finds this +package without installing anything. It never adds the current directory +or the repo being analysed, so a file in the analysed repo cannot shadow a +module. diff --git a/tools/codegraph/cgcore/__init__.py b/tools/codegraph/cgcore/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tools/codegraph/cgcore/adapters/__init__.py b/tools/codegraph/cgcore/adapters/__init__.py new file mode 100644 index 0000000..fd19019 --- /dev/null +++ b/tools/codegraph/cgcore/adapters/__init__.py @@ -0,0 +1,26 @@ +"""Adapter registry. + +A language adapter turns one source file into neutral facts; a manifest +adapter turns a package manifest (and lockfile) into neutral dependency +facts. To add a language, add a module here and register it; nothing in +cgcore outside this package knows any language. +""" +from __future__ import annotations + +from typing import Callable, Dict, List, Tuple + +from . import swift_facts, swiftpm + +# Bump when an adapter's output for the same input could change; it keys +# the parse cache and is recorded in every output manifest. +ADAPTER_VERSION = "swift-1.0.0" + +# name -> (file suffixes, extract(src, api_probes), ambient method names) +LANGUAGES: Dict[str, Tuple[Tuple[str, ...], Callable[..., dict], Tuple[str, ...]]] = { + "swift": ((".swift",), swift_facts.extract, swift_facts.AMBIENT_METHODS), +} + +# name -> (manifest file names, lockfile names, parse_manifest, parse_lock) +MANIFESTS: Dict[str, Tuple[List[str], List[str], Callable[[str], dict], Callable[[str], list]]] = { + "swiftpm": (["Package.swift"], ["Package.resolved"], swiftpm.parse_manifest, swiftpm.parse_resolved), +} diff --git a/tools/codegraph/cgcore/adapters/swift_facts.py b/tools/codegraph/cgcore/adapters/swift_facts.py new file mode 100644 index 0000000..6f6fc9c --- /dev/null +++ b/tools/codegraph/cgcore/adapters/swift_facts.py @@ -0,0 +1,367 @@ +"""Swift adapter: turn one Swift source file into language-neutral facts. + +Pure function `extract(src) -> dict`. The dict shape is the adapter +contract every language adapter must produce (see cgcore/build.py): + + imports: [{module, line, testable}] + decls: [{key, kind, subkind, name, container, selector, params, + extension, inherits, access, static, requirement, + line, end_line, digest}] + uses: [{kind: call|ref|api, owner, name, labels, receiver, + trailing, line}] + +`key` is "type:" or "func:." (container "" for +top-level). `owner` on a use is the key of the innermost enclosing decl, +or "" for file-level code. Name resolution across files happens later, +in the language-neutral build step. + +Known limits (by design, recorded rather than hidden): + - No type inference: a call through a variable (`x.foo()`) is resolved + by selector only and may come back ambiguous. + - Local functions and closures are folded into their enclosing decl. + - Property declarations are not nodes; their bodies count toward the + enclosing type. +""" +from __future__ import annotations + +import hashlib +from typing import Dict, List, Optional, Tuple + +from .swift_lexer import Token, tokenize + +TYPE_KEYWORDS = {"struct", "enum", "class", "actor", "protocol", "extension"} +FUNC_KEYWORDS = {"func", "init", "deinit", "subscript"} +MODIFIERS = { + "public", "private", "fileprivate", "internal", "open", "static", "class", + "final", "override", "mutating", "nonmutating", "nonisolated", "convenience", + "required", "lazy", "weak", "unowned", "dynamic", "indirect", "optional", + "isolated", "distributed", "consuming", "borrowing", +} +DECL_STARTERS = MODIFIERS | FUNC_KEYWORDS | TYPE_KEYWORDS | { + "var", "let", "case", "typealias", "associatedtype", "import", +} +ACCESS = {"public", "private", "fileprivate", "internal", "open"} +NOT_CALLS = { + "if", "guard", "while", "for", "switch", "return", "catch", "in", "where", + "try", "await", "throw", "repeat", "case", "else", "as", "is", "let", "var", + "func", "init", "self", "Self", "super", "some", "any", "defer", "do", +} +# Swift standard-library / Foundation method names. A call through a +# variable receiver to one of these is never classed `unique`, because the +# variable is far more likely an Array, Set, Dictionary or FileHandle than +# a repo type that happens to declare the same selector. +AMBIENT_METHODS = ( + "append", "insert", "remove", "removeAll", "removeValue", "contains", "write", + "map", "filter", "reduce", "first", "last", "sorted", "sort", "joined", "update", + "index", "firstIndex", "forEach", "compactMap", "flatMap", "min", "max", "count", + "encode", "decode", "read", "close", "load", "save", "set", "get", "add", "merge", +) + +# A probe ending in "()" matches only a call site; a bare name matches any +# use; "try!" / "as!" match the forced forms. +API_PROBES_DEFAULT = ( + "hashValue", "Date()", "UUID()", "random()", "print()", "fatalError()", + "precondition()", "try!", "as!", "ProcessInfo", "FileManager", "URLSession", +) + + +def _match(tokens: List[Token], i: int, open_ch: str, close_ch: str) -> int: + """Index of the token closing the bracket opened at tokens[i].""" + depth = 0 + for j in range(i, len(tokens)): + text = tokens[j][1] + if tokens[j][0] in ("punct", "op") and text == open_ch: + depth += 1 + elif tokens[j][0] in ("punct", "op") and text == close_ch: + depth -= 1 + if depth == 0: + return j + return len(tokens) - 1 + + +def _skip_generics(tokens: List[Token], i: int) -> int: + if i < len(tokens) and tokens[i][1] == "<": + return _match(tokens, i, "<", ">") + 1 + return i + + +def _split_top(tokens: List[Token], lo: int, hi: int) -> List[Tuple[int, int]]: + """Split tokens[lo:hi] on commas at bracket depth 0.""" + parts, depth, start = [], 0, lo + for j in range(lo, hi): + text = tokens[j][1] + if text in "([{" and tokens[j][0] == "punct": + depth += 1 + elif text in ")]}" and tokens[j][0] == "punct": + depth -= 1 + elif text == "," and depth == 0: + parts.append((start, j)) + start = j + 1 + if start < hi: + parts.append((start, hi)) + return parts + + +def _params(tokens: List[Token], open_i: int) -> Tuple[List[dict], int]: + """Parse a declaration parameter list starting at '('.""" + close_i = _match(tokens, open_i, "(", ")") + params = [] + for lo, hi in _split_top(tokens, open_i + 1, close_i): + seg = [t for t in tokens[lo:hi] if t[0] != "attr"] + colon = next((k for k, t in enumerate(seg) if t[1] == ":"), None) + if colon is None or colon == 0: + continue + names = [t[1] for t in seg[:colon] if t[0] == "id"] + rest = seg[colon + 1:] + params.append({ + "label": names[0] if names else "_", + "default": any(t[1] == "=" for t in rest), + "closure": any(t[1] == "->" for t in rest), + }) + return params, close_i + + +def _call_labels(tokens: List[Token], open_i: int) -> Tuple[List[str], int]: + close_i = _match(tokens, open_i, "(", ")") + labels = [] + for lo, hi in _split_top(tokens, open_i + 1, close_i): + if hi - lo >= 2 and tokens[lo][0] == "id" and tokens[lo + 1][1] == ":": + labels.append(tokens[lo][1]) + else: + labels.append("_") + return labels, close_i + + +def _selector(name: str, labels: List[str]) -> str: + return name + "(" + "".join(lbl + ":" for lbl in labels) + ")" + + +def _digest(tokens: List[Token], lo: int, hi: int) -> str: + text = "\x1f".join(t[1] for t in tokens[lo:hi + 1]) + return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16] + + +def _modifiers(tokens: List[Token], i: int) -> Tuple[str, bool, int]: + """Walk back from a decl keyword over modifiers and attributes.""" + access, static, j = "", False, i - 1 + while j >= 0: + kind, text, _ = tokens[j] + if kind == "attr": + j -= 1 + elif kind == "punct" and text == ")" and j > 0: + k = j # attribute or modifier argument, e.g. private(set) + depth = 0 + while k >= 0: + if tokens[k][1] == ")": + depth += 1 + elif tokens[k][1] == "(": + depth -= 1 + if depth == 0: + break + k -= 1 + j = k - 1 + elif kind == "id" and text in MODIFIERS: + access = text if text in ACCESS and not access else access + static = static or text in ("static", "class") + j -= 1 + else: + break + return access or "internal", static, j + 1 + + +class _Extractor: + def __init__(self, src: str, api_probes: Tuple[str, ...]) -> None: + self.t = tokenize(src) + self.api_bare = {p for p in api_probes if not p.endswith(("()", "!"))} + self.api_call = {p[:-2] for p in api_probes if p.endswith("()")} + self.api_forced = {p[:-1] for p in api_probes if p.endswith("!")} + self.imports: List[dict] = [] + self.decls: List[dict] = [] + self.uses: List[dict] = [] + self.stack: List[Tuple[str, Optional[dict]]] = [] + self.pending: Dict[int, dict] = {} + + # ── scope helpers ───────────────────────────────────────────────────── + def _owner(self) -> str: + for kind, decl in reversed(self.stack): + if decl is not None: + return decl["key"] + return "" + + def _type_container(self) -> Tuple[str, bool]: + """Qualified name of the innermost type scope, and whether a function + scope sits between us and it (i.e. we are inside a function).""" + for kind, decl in reversed(self.stack): + if decl is None: + continue + if decl["kind"] == "func": + return "", True + return decl["name_qual"], False + return "", False + + # ── declarations ────────────────────────────────────────────────────── + def _type_decl(self, i: int) -> int: + kw = self.t[i][1] + prev = self.t[i - 1][1] if i else "" + nxt = self.t[i + 1] if i + 1 < len(self.t) else ("", "", 0) + if prev in (".", ":", ",") or nxt[0] != "id" or \ + (kw == "class" and nxt[1] in DECL_STARTERS): + return i + 1 + access, static, start = _modifiers(self.t, i) + j = i + 1 + name_parts = [self.t[j][1]] + j += 1 + while kw == "extension" and j + 1 < len(self.t) and self.t[j][1] == "." \ + and self.t[j + 1][0] == "id": + name_parts.append(self.t[j + 1][1]) + j += 2 + j = _skip_generics(self.t, j) + inherits: List[str] = [] + if j < len(self.t) and self.t[j][1] == ":": + j += 1 + while j < len(self.t) and self.t[j][1] not in ("{", "where"): + if self.t[j][0] == "id" and self.t[j - 1][1] in (":", ","): + inherits.append(self.t[j][1]) + j = _skip_generics(self.t, j + 1) + while j < len(self.t) and self.t[j][1] != "{": + j += 1 + container, in_func = self._type_container() + name = ".".join(name_parts) + qual = name if kw == "extension" or not container else container + "." + name + decl = { + "key": "type:" + qual, "kind": "type", + "subkind": "extension" if kw == "extension" else kw, + "name": name_parts[-1], "name_qual": qual, "container": container, + "selector": "", "params": [], "extension": kw == "extension", + "inherits": inherits, "access": access, "static": False, + "requirement": False, "local": in_func, + "line": self.t[i][2], "end_line": self.t[i][2], "_start": start, + } + self.decls.append(decl) + self.pending[j] = decl + return j + + def _func_decl(self, i: int) -> int: + kw = self.t[i][1] + prev = self.t[i - 1][1] if i else "" + if prev == "." or (kw == "init" and prev in ("self", "super")): + return i + 1 + access, static, start = _modifiers(self.t, i) + j = i + 1 + name = kw + if kw == "func" and j < len(self.t): + name = self.t[j][1] + j += 1 + while j < len(self.t) and self.t[j][1] in ("?", "!"): + j += 1 + j = _skip_generics(self.t, j) + params: List[dict] = [] + if j < len(self.t) and self.t[j][1] == "(": + params, j = _params(self.t, j) + j += 1 + while j < len(self.t): + kind, text, _ = self.t[j] + if text in ("{", "}") and kind == "punct": + break + if kind in ("id", "attr") and text in DECL_STARTERS and text not in ("throws",): + break + if kind == "attr" and self.t[j - 1][1] not in ("->", ":", ","): + break + j += 1 + container, in_func = self._type_container() + if in_func: + return j # local function: folded into the enclosing decl + has_body = j < len(self.t) and self.t[j][1] == "{" + selector = name + "()" if kw == "deinit" else _selector(name, [p["label"] for p in params]) + decl = { + "key": "func:" + (container + "." if container else "") + selector, + "kind": "func", "subkind": kw if kw != "func" else "func", + "name": name, "name_qual": "", "container": container, + "selector": selector, "params": params, "extension": False, + "inherits": [], "access": access, "static": static, + "requirement": not has_body, "local": False, + "line": self.t[i][2], "end_line": self.t[max(j - 1, i)][2], "_start": start, + } + decl["digest"] = _digest(self.t, start, max(j - 1, i)) + self.decls.append(decl) + if has_body: + self.pending[j] = decl + return j + + # ── uses ────────────────────────────────────────────────────────────── + def _use_at(self, i: int) -> None: + kind, text, line = self.t[i] + prev = self.t[i - 1][1] if i else "" + nxt = self.t[i + 1][1] if i + 1 < len(self.t) else "" + owner = self._owner() + probe = None + if text in self.api_bare: + probe = text + elif text in self.api_call and nxt == "(": + probe = text + "()" + if probe: + self.uses.append({"kind": "api", "owner": owner, "name": probe, "labels": [], + "receiver": None, "trailing": False, "line": line}) + if text in self.api_forced and nxt == "!": + self.uses.append({"kind": "api", "owner": owner, "name": text + "!", "labels": [], + "receiver": None, "trailing": False, "line": line}) + if nxt == "(" and text not in NOT_CALLS and prev != "func": + labels, close_i = _call_labels(self.t, i + 1) + receiver = None + if prev == "." and i >= 2 and self.t[i - 2][0] == "id" \ + and self.t[i - 2][1] not in NOT_CALLS - {"self", "Self", "super"}: + receiver = self.t[i - 2][1] + trailing = close_i + 1 < len(self.t) and self.t[close_i + 1][1] == "{" + self.uses.append({"kind": "call", "owner": owner, "name": text, "labels": labels, + "receiver": receiver, "trailing": trailing, "line": line}) + elif text == "init" and prev == "." and nxt == "(" and i >= 2: + labels, _ = _call_labels(self.t, i + 1) + self.uses.append({"kind": "call", "owner": owner, "name": "init", "labels": labels, + "receiver": self.t[i - 2][1], "trailing": False, "line": line}) + if text[:1].isupper(): + self.uses.append({"kind": "ref", "owner": owner, "name": text, "labels": [], + "receiver": None, "trailing": False, "line": line}) + + # ── main loop ───────────────────────────────────────────────────────── + def run(self) -> dict: + i = 0 + while i < len(self.t): + kind, text, line = self.t[i] + if kind == "id" and text == "import" and i + 1 < len(self.t): + testable = i > 0 and self.t[i - 1][1] == "@testable" + j = i + 1 + if self.t[j][1] in ("struct", "class", "enum", "func", "protocol", "typealias"): + j += 1 + self.imports.append({"module": self.t[j][1], "line": line, "testable": testable}) + i = j + 1 + continue + if kind == "id" and text in TYPE_KEYWORDS: + i = self._type_decl(i) + continue + if kind == "id" and text in FUNC_KEYWORDS: + new_i = self._func_decl(i) + if new_i != i + 1: + i = new_i + continue + if kind == "punct" and text == "{": + decl = self.pending.pop(i, None) + self.stack.append(("decl" if decl else "block", decl)) + elif kind == "punct" and text == "}": + if self.stack: + _, decl = self.stack.pop() + if decl is not None: + decl["end_line"] = line + decl["digest"] = _digest(self.t, decl["_start"], i) + elif kind == "id": + self._use_at(i) + i += 1 + for decl in self.decls: + decl.pop("_start", None) + decl.pop("name_qual", None) + decl.setdefault("digest", "") + return {"imports": self.imports, "decls": self.decls, "uses": self.uses} + + +def extract(src: str, api_probes: Tuple[str, ...] = API_PROBES_DEFAULT) -> dict: + """Return language-neutral facts for one Swift source file.""" + return _Extractor(src, api_probes).run() diff --git a/tools/codegraph/cgcore/adapters/swift_lexer.py b/tools/codegraph/cgcore/adapters/swift_lexer.py new file mode 100644 index 0000000..bb4ee64 --- /dev/null +++ b/tools/codegraph/cgcore/adapters/swift_lexer.py @@ -0,0 +1,240 @@ +"""Swift lexer for codegraph. + +Pure function: source text in, token list out. No I/O, no global state. + +Tokens are (kind, text, line) tuples: + id identifier or keyword (backticks stripped) + num numeric literal + str string literal; text is the literal's raw content for simple + literals, or "" when the literal holds interpolation (the + interpolated code is emitted as ordinary tokens between a + `str_open` and `str_close` pair so calls inside it still count) + attr attribute, e.g. "@escaping" + pound compiler directive / literal, e.g. "#if", "#available" + op operator run ("->", "==", "+=", ...); "<", ">", "?", "!" and "." + are always single-character tokens so generics and optional + chaining stay parseable + punct one of { } ( ) [ ] , : ; \\ +Comments (line, block, nested block) are dropped. +""" +from __future__ import annotations + +from typing import List, Tuple + +Token = Tuple[str, str, int] + +_PUNCT = set("{}()[],:;\\") +_SINGLE_OPS = set("<>?!.") +_OP_CHARS = set("+-*/%=&|^~") + + +def _is_ident_start(ch: str) -> bool: + return ch == "_" or ch.isalpha() + + +def _is_ident_char(ch: str) -> bool: + return ch == "_" or ch.isalnum() + + +class _Lexer: + """Single-use lexer; call run() once.""" + + def __init__(self, src: str) -> None: + self.src = src + self.n = len(src) + self.i = 0 + self.line = 1 + self.out: List[Token] = [] + + # ── helpers ──────────────────────────────────────────────────────────── + def _peek(self, k: int = 0) -> str: + j = self.i + k + return self.src[j] if j < self.n else "" + + def _emit(self, kind: str, text: str, line: int) -> None: + self.out.append((kind, text, line)) + + def _advance(self, count: int = 1) -> None: + for _ in range(count): + if self.i < self.n and self.src[self.i] == "\n": + self.line += 1 + self.i += 1 + + # ── entry ────────────────────────────────────────────────────────────── + def run(self) -> List[Token]: + self._code(stop_at_paren=False) + return self.out + + def _code(self, stop_at_paren: bool) -> None: + """Lex code. If stop_at_paren, return after the ')' closing an + interpolation (depth counted from the '\\(' that opened it).""" + depth = 0 + while self.i < self.n: + ch = self._peek() + nxt = self._peek(1) + if ch in " \t\r\n": + self._advance() + elif ch == "/" and nxt == "/": + while self.i < self.n and self._peek() != "\n": + self._advance() + elif ch == "/" and nxt == "*": + self._block_comment() + elif ch == '"' or (ch == "#" and self._raw_string_ahead()): + self._string() + elif _is_ident_start(ch): + self._ident() + elif ch == "`": + self._backtick_ident() + elif ch.isdigit(): + self._number() + elif ch == "@" and _is_ident_start(nxt): + line = self.line + self._advance() + start = self.i + while self.i < self.n and _is_ident_char(self._peek()): + self._advance() + self._emit("attr", "@" + self.src[start:self.i], line) + elif ch == "#" and _is_ident_start(nxt): + line = self.line + self._advance() + start = self.i + while self.i < self.n and _is_ident_char(self._peek()): + self._advance() + self._emit("pound", "#" + self.src[start:self.i], line) + elif ch == "$" and (nxt.isdigit() or _is_ident_start(nxt)): + line = self.line + start = self.i + self._advance() + while self.i < self.n and _is_ident_char(self._peek()): + self._advance() + self._emit("id", self.src[start:self.i], line) + elif ch in _PUNCT: + if stop_at_paren and ch == "(": + depth += 1 + if stop_at_paren and ch == ")": + if depth == 0: + self._advance() + return + depth -= 1 + self._emit("punct", ch, self.line) + self._advance() + elif ch == "-" and nxt == ">": + self._emit("op", "->", self.line) + self._advance(2) + elif ch in _SINGLE_OPS: + self._emit("op", ch, self.line) + self._advance() + elif ch in _OP_CHARS: + line = self.line + start = self.i + while self.i < self.n and self._peek() in _OP_CHARS: + if self._peek() == "/" and self._peek(1) in "/*": + break + self._advance() + self._emit("op", self.src[start:self.i], line) + else: + # Unknown character (e.g. stray unicode): skip it, never crash. + self._advance() + + # ── comments ─────────────────────────────────────────────────────────── + def _block_comment(self) -> None: + depth = 0 + while self.i < self.n: + if self._peek() == "/" and self._peek(1) == "*": + depth += 1 + self._advance(2) + elif self._peek() == "*" and self._peek(1) == "/": + depth -= 1 + self._advance(2) + if depth == 0: + return + else: + self._advance() + + # ── identifiers and numbers ──────────────────────────────────────────── + def _ident(self) -> None: + line = self.line + start = self.i + while self.i < self.n and _is_ident_char(self._peek()): + self._advance() + self._emit("id", self.src[start:self.i], line) + + def _backtick_ident(self) -> None: + line = self.line + self._advance() + start = self.i + while self.i < self.n and self._peek() not in "`\n": + self._advance() + text = self.src[start:self.i] + self._advance() + self._emit("id", text, line) + + def _number(self) -> None: + line = self.line + start = self.i + while self.i < self.n: + ch = self._peek() + if _is_ident_char(ch): + self._advance() + elif ch == "." and self._peek(1).isdigit(): + self._advance() + elif ch in "+-" and self._peek(1).isdigit() and self._exponent_sign(start): + self._advance() + else: + break + self._emit("num", self.src[start:self.i], line) + + def _exponent_sign(self, start: int) -> bool: + """True when the +/- at self.i is an exponent sign (1e-5, 0x1p+3).""" + prev = self.src[self.i - 1] + is_hex = self.src[start:self.i].lower().startswith("0x") + return (prev in "pP") if is_hex else (prev in "eE") + + # ── strings ──────────────────────────────────────────────────────────── + def _raw_string_ahead(self) -> bool: + j = self.i + while j < self.n and self.src[j] == "#": + j += 1 + return j < self.n and self.src[j] == '"' and j > self.i + + def _string(self) -> None: + line = self.line + hashes = 0 + while self._peek() == "#": + hashes += 1 + self._advance() + multiline = self.src.startswith('"""', self.i) + self._advance(3 if multiline else 1) + closer = ('"""' if multiline else '"') + "#" * hashes + escape = "\\" + "#" * hashes + parts: List[str] = [] + interpolated = False + open_index = len(self.out) + while self.i < self.n: + if self.src.startswith(closer, self.i): + self._advance(len(closer)) + break + if self.src.startswith(escape + "(", self.i): + if not interpolated: + self.out.insert(open_index, ("str_open", "", line)) + interpolated = True + self._advance(len(escape) + 1) + self._code(stop_at_paren=True) + continue + if self.src.startswith(escape, self.i): + parts.append(self.src[self.i:self.i + len(escape) + 1]) + self._advance(len(escape) + 1) + continue + if not multiline and self._peek() == "\n": + break # unterminated single-line literal: stop at EOL + parts.append(self._peek()) + self._advance() + if interpolated: + self._emit("str_close", "", self.line) + else: + self._emit("str", "".join(parts), line) + + +def tokenize(src: str) -> List[Token]: + """Return the token list for Swift source text.""" + return _Lexer(src).run() diff --git a/tools/codegraph/cgcore/adapters/swiftpm.py b/tools/codegraph/cgcore/adapters/swiftpm.py new file mode 100644 index 0000000..79f6c46 --- /dev/null +++ b/tools/codegraph/cgcore/adapters/swiftpm.py @@ -0,0 +1,164 @@ +"""SwiftPM adapter: read Package.swift and Package.resolved statically. + +Pure functions; nothing is executed, nothing is fetched. The manifest is +lexed with the Swift lexer and the well-known PackageDescription calls are +read off the token stream. A manifest that builds its targets with loops or +variables will be under-read; that shows up as missing targets, not as a +crash. + +Contract (language-neutral manifest facts, consumed by cgcore/build.py): + {package, targets: [{name, kind, path, deps: [{kind, name, package}]}], + products: [{name, kind, targets}], + packages: [{identity, location, requirement}], + pins: [{identity, location, version, revision, branch}]} +""" +from __future__ import annotations + +import json +from typing import Dict, List, Optional, Tuple + +from .swift_lexer import Token, tokenize + +TARGET_CALLS = { + "target": "library", "executableTarget": "executable", "testTarget": "test", + "macro": "macro", "plugin": "plugin", "systemLibrary": "system", + "binaryTarget": "binary", +} +PRODUCT_CALLS = {"library": "library", "executable": "executable", "plugin": "plugin"} + + +def _match(tokens: List[Token], i: int, open_ch: str, close_ch: str) -> int: + depth = 0 + for j in range(i, len(tokens)): + if tokens[j][1] == open_ch and tokens[j][0] == "punct": + depth += 1 + elif tokens[j][1] == close_ch and tokens[j][0] == "punct": + depth -= 1 + if depth == 0: + return j + return len(tokens) - 1 + + +def _args(tokens: List[Token], open_i: int) -> Tuple[Dict[str, Tuple[int, int]], int]: + """Labelled argument ranges of the call whose '(' is at open_i.""" + close_i = _match(tokens, open_i, "(", ")") + out: Dict[str, Tuple[int, int]] = {} + depth, start, pos = 0, open_i + 1, 0 + for j in range(open_i + 1, close_i + 1): + text = tokens[j][1] + if text in "([{" and tokens[j][0] == "punct": + depth += 1 + elif text in ")]}" and tokens[j][0] == "punct" and j != close_i: + depth -= 1 + if (text == "," and depth == 0) or j == close_i: + if j > start: + if tokens[start][0] == "id" and start + 1 < j and tokens[start + 1][1] == ":": + out[tokens[start][1]] = (start + 2, j) + else: + out["_" + str(pos)] = (start, j) + pos += 1 + start = j + 1 + return out, close_i + + +def _first_str(tokens: List[Token], rng: Optional[Tuple[int, int]]) -> str: + if rng is None: + return "" + for kind, text, _ in tokens[rng[0]:rng[1]]: + if kind == "str": + return text + return "" + + +def _strs(tokens: List[Token], rng: Optional[Tuple[int, int]]) -> List[str]: + if rng is None: + return [] + return [text for kind, text, _ in tokens[rng[0]:rng[1]] if kind == "str"] + + +def _deps(tokens: List[Token], rng: Optional[Tuple[int, int]]) -> List[dict]: + if rng is None: + return [] + out, j = [], rng[0] + while j < rng[1]: + kind, text, _ = tokens[j] + if kind == "str" and tokens[j - 1][1] in ("[", ","): + out.append({"kind": "byName", "name": text, "package": ""}) + elif kind == "id" and tokens[j - 1][1] == "." and j + 1 < rng[1] \ + and tokens[j + 1][1] == "(" and text in ("product", "target", "byName"): + args, close_i = _args(tokens, j + 1) + out.append({"kind": text, "name": _first_str(tokens, args.get("name")), + "package": _first_str(tokens, args.get("package"))}) + j = close_i + j += 1 + return out + + +def _requirement(tokens: List[Token], args: Dict[str, Tuple[int, int]]) -> str: + for key in ("exact", "from", "branch", "revision", "path"): + if key in args: + return key + " " + _first_str(tokens, args[key]) + for key, rng in sorted(args.items()): + if key.startswith("_"): + texts = " ".join(t[1] if t[0] != "str" else '"' + t[1] + '"' + for t in tokens[rng[0]:rng[1]]) + return texts + return "" + + +def parse_manifest(src: str) -> dict: + """Read Package.swift source into manifest facts.""" + t = tokenize(src) + facts = {"package": "", "targets": [], "products": [], "packages": []} + for i, (kind, text, _) in enumerate(t): + if kind != "id" or i + 1 >= len(t) or t[i + 1][1] != "(": + continue + args, _ = _args(t, i + 1) + prev = t[i - 1][1] if i else "" + if text == "Package" and prev != "." and not facts["package"]: + facts["package"] = _first_str(t, args.get("name")) + elif prev == "." and text in TARGET_CALLS and "name" in args: + name = _first_str(t, args.get("name")) + tkind = TARGET_CALLS[text] + default_root = "Tests/" if tkind == "test" else "Sources/" + facts["targets"].append({ + "name": name, "kind": tkind, + "path": _first_str(t, args.get("path")) or default_root + name, + "deps": _deps(t, args.get("dependencies")), + }) + elif prev == "." and text in PRODUCT_CALLS and "targets" in args: + facts["products"].append({"name": _first_str(t, args.get("name")), + "kind": PRODUCT_CALLS[text], + "targets": _strs(t, args.get("targets"))}) + elif prev == "." and text == "package" and ("url" in args or "path" in args or "id" in args): + location = _first_str(t, args.get("url") or args.get("path") or args.get("id")) + identity = location.rstrip("/").split("/")[-1].lower() + if identity.endswith(".git"): + identity = identity[:-4] + facts["packages"].append({"identity": identity, "location": location, + "requirement": _requirement(t, args)}) + for key in ("targets", "products", "packages"): + facts[key].sort(key=lambda d: json.dumps(d, sort_keys=True)) + return facts + + +def parse_resolved(src: str) -> List[dict]: + """Read Package.resolved (format v1, v2 or v3) into pins.""" + try: + data = json.loads(src) + except ValueError: + return [] + raw = data.get("pins") or data.get("object", {}).get("pins") or [] + pins = [] + for pin in raw: + state = pin.get("state", {}) + location = pin.get("location") or pin.get("repositoryURL") or "" + pins.append({ + "identity": (pin.get("identity") or pin.get("package") or "").lower(), + "location": location, + "version": state.get("version") or "", + "revision": state.get("revision") or "", + "branch": state.get("branch") or "", + }) + pins.sort(key=lambda d: (d["identity"], d["location"])) + return pins diff --git a/tools/codegraph/cgcore/build.py b/tools/codegraph/cgcore/build.py new file mode 100644 index 0000000..eba348d --- /dev/null +++ b/tools/codegraph/cgcore/build.py @@ -0,0 +1,142 @@ +"""Project one snapshot (one commit's tree) into a graph. + +Pure: inputs are already-parsed facts; output is a Graph. Language-neutral: +it reads only the adapter contract (see cgcore/adapters/swift_facts.py and +swiftpm.py docstrings). + +Node id prefixes: + pkg: the package product: a built product + module: a target / module dep: an external package dependency + fw: an imported module that is not a target (system framework) + file: a source file type: a type (module-qualified) + func: a function / init extern: a conformance target not in the repo + api: an API probe from the config (e.g. hashValue) +""" +from __future__ import annotations + +import hashlib +from typing import Any, Dict, List, Optional, Tuple + +from . import model, resolve + + +def module_of(path: str, manifest: Optional[dict], fallback: List[dict]) -> str: + if manifest: + best = "" + best_len = -1 + for target in manifest["targets"]: + root = target["path"].rstrip("/") + "/" + if path.startswith(root) and len(root) > best_len: + best, best_len = target["name"], len(root) + if best: + return best + for rule in fallback: + if path.startswith(rule["prefix"]): + if "name" in rule: + return rule["name"] + parts = path.split("/") + if len(parts) > rule["segment"] + 1: + return parts[rule["segment"]] + return "(root)" + + +def _add_edge(g: model.Graph, src: str, kind: str, dst: str, resolution: str = "exact") -> None: + if src == dst: + return + key = model.edge_key(src, kind, dst) + rank = resolve.RESOLUTION_RANK + cur = g["edges"].get(key) + if cur is None: + g["edges"][key] = {"count": 1, "resolution": resolution} + else: + cur["count"] += 1 + if rank[resolution] < rank[cur["resolution"]]: + cur["resolution"] = resolution + + +def _manifest_nodes(g: model.Graph, manifest: Optional[dict], pins: List[dict]) -> None: + if not manifest: + return + pkg = "pkg:" + (manifest["package"] or "(package)") + g["nodes"][pkg] = {"kind": "package", "name": manifest["package"]} + target_names = {t["name"] for t in manifest["targets"]} + pin_by_id = {p["identity"]: p for p in pins} + for dep in manifest["packages"]: + pin = pin_by_id.get(dep["identity"], {}) + g["nodes"]["dep:" + dep["identity"]] = { + "kind": "dependency", "name": dep["identity"], "location": dep["location"], + "requirement": dep["requirement"], "version": pin.get("version", ""), + "revision": pin.get("revision", ""), "branch": pin.get("branch", ""), "direct": True} + _add_edge(g, pkg, "requires", "dep:" + dep["identity"]) + for pin in pins: # transitive pins: present in the lockfile, not the manifest + nid = "dep:" + pin["identity"] + if nid not in g["nodes"]: + g["nodes"][nid] = {"kind": "dependency", "name": pin["identity"], + "location": pin["location"], "requirement": "", + "version": pin["version"], "revision": pin["revision"], + "branch": pin["branch"], "direct": False} + _add_edge(g, pkg, "pins", nid) + for target in manifest["targets"]: + mid = "module:" + target["name"] + g["nodes"][mid] = {"kind": "module", "subkind": target["kind"], + "name": target["name"], "path": target["path"]} + _add_edge(g, pkg, "contains", mid) + for dep in target["deps"]: + if dep["kind"] == "product" and dep["package"]: + _add_edge(g, mid, "depends-on", "dep:" + dep["package"].lower()) + elif dep["name"] in target_names: + _add_edge(g, mid, "depends-on", "module:" + dep["name"]) + else: + _add_edge(g, mid, "depends-on", "dep:" + dep["name"].lower()) + for product in manifest["products"]: + pid = "product:" + product["name"] + g["nodes"][pid] = {"kind": "product", "subkind": product["kind"], "name": product["name"]} + _add_edge(g, pkg, "contains", pid) + for name in product["targets"]: + _add_edge(g, pid, "built-from", "module:" + name) + + +def _file_nodes(g: model.Graph, files: List[Tuple[str, dict]], modules: Dict[str, str], + target_names: set) -> None: + for path, facts in files: + mod = modules[path] + fid = "file:" + path + g["nodes"][fid] = {"kind": "file", "name": path.split("/")[-1], "path": path, + "module": mod} + mid = "module:" + mod + if mid not in g["nodes"]: + g["nodes"][mid] = {"kind": "module", "subkind": "inferred", "name": mod, "path": ""} + _add_edge(g, mid, "contains", fid) + for imp in facts["imports"]: + target = "module:" + imp["module"] if imp["module"] in target_names \ + else "fw:" + imp["module"] + if target not in g["nodes"]: + g["nodes"][target] = {"kind": "framework", "name": imp["module"]} + _add_edge(g, fid, "imports", target) + + +def project(files: List[Tuple[str, dict]], manifest: Optional[dict], pins: List[dict], + cfg: Dict[str, Any], ambient: Tuple[str, ...] = ()) -> model.Graph: + """Build the graph for one snapshot. `files` must be sorted by path.""" + g = model.empty() + _manifest_nodes(g, manifest, pins) + modules = {path: module_of(path, manifest, cfg["module_fallback"]) for path, _ in files} + target_names = {t["name"] for t in manifest["targets"]} if manifest else set() + target_names |= set(modules.values()) + _file_nodes(g, files, modules, target_names) + symbols = resolve.Symbols(files, modules, ambient) + for nid, attrs in symbols.nodes.items(): + g["nodes"][nid] = attrs + for src, kind, dst in symbols.structure_edges: + _add_edge(g, src, kind, dst) + for src, kind, dst, resolution in resolve.use_edges(files, modules, symbols): + if kind == "uses-api" and dst not in g["nodes"]: + g["nodes"][dst] = {"kind": "api", "name": dst[len("api:"):]} + if kind == "conforms" and dst.startswith("extern:") and dst not in g["nodes"]: + g["nodes"][dst] = {"kind": "extern", "name": dst[len("extern:"):]} + _add_edge(g, src, kind, dst, resolution) + return g + + +def blob_cache_key(adapter_version: str, cfg_fingerprint: str, blob: str) -> str: + return hashlib.sha256((adapter_version + "\0" + cfg_fingerprint + "\0" + blob).encode()).hexdigest() diff --git a/tools/codegraph/cgcore/config.py b/tools/codegraph/cgcore/config.py new file mode 100644 index 0000000..8018877 --- /dev/null +++ b/tools/codegraph/cgcore/config.py @@ -0,0 +1,40 @@ +"""Load and validate a codegraph config file. + +Everything repo-specific lives in the config; the core never hard-codes a +path, module name or language. Unknown keys are rejected so a typo fails +loudly instead of being silently ignored. +""" +from __future__ import annotations + +import json +from typing import Any, Dict + +DEFAULTS: Dict[str, Any] = { + "schema": "codegraph-config/1", + "project": "", + "language": "swift", + "manifest": "", + "exclude_prefixes": [], + "module_fallback": [], + "api_probes": [], + "test_modules": [], + "output_dir": "codegraph-vault", +} + + +def load(path: str) -> Dict[str, Any]: + with open(path, "r", encoding="utf-8") as handle: + raw = json.load(handle) + unknown = sorted(set(raw) - set(DEFAULTS)) + if unknown: + raise ValueError("unknown config keys: " + ", ".join(unknown)) + if raw.get("schema", DEFAULTS["schema"]) != DEFAULTS["schema"]: + raise ValueError("unsupported config schema: " + str(raw.get("schema"))) + cfg = dict(DEFAULTS) + cfg.update(raw) + return cfg + + +def fingerprint(cfg: Dict[str, Any]) -> str: + """Canonical text of the config, recorded in every output manifest.""" + return json.dumps(cfg, sort_keys=True, separators=(",", ":")) diff --git a/tools/codegraph/cgcore/fold.py b/tools/codegraph/cgcore/fold.py new file mode 100644 index 0000000..886e4d3 --- /dev/null +++ b/tools/codegraph/cgcore/fold.py @@ -0,0 +1,148 @@ +"""Fold over the git log: project every commit, diff against its first +parent, and track each node's history. + +Reads git objects only (never the working tree), so the result is a pure +function of (repository objects, rev, config, adapter version). + +Memory: keeps one graph per commit so merge commits can diff against any +earlier parent. Fine for hundreds of commits; for very long histories, +evict graphs once all children are processed. +""" +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Tuple + +from . import build, gitio, model +from .adapters import ADAPTER_VERSION, LANGUAGES, MANIFESTS + + +class _Parser: + """Parses blobs through the configured adapters, cached by blob sha.""" + + def __init__(self, reader: gitio.BlobReader, cfg: Dict[str, Any]) -> None: + self.reader = reader + self.cfg = cfg + self.suffixes, self.extract, self.ambient = LANGUAGES[cfg["language"]] + self.probes = tuple(cfg["api_probes"]) + self.cache: Dict[str, Any] = {} + + def _text(self, blob: str) -> str: + return self.reader.read(blob).decode("utf-8", "replace") + + def source(self, blob: str) -> dict: + key = "src:" + blob + if key not in self.cache: + self.cache[key] = self.extract(self._text(blob), self.probes) + return self.cache[key] + + def manifest(self, blob: Optional[str], lock_blob: Optional[str]) -> Tuple[Optional[dict], List[dict]]: + if not self.cfg["manifest"] or blob is None: + return None, [] + _, _, parse_manifest, parse_lock = MANIFESTS[self.cfg["manifest"]] + key = "man:" + blob + if key not in self.cache: + self.cache[key] = parse_manifest(self._text(blob)) + pins: List[dict] = [] + if lock_blob: + lkey = "lock:" + lock_blob + if lkey not in self.cache: + self.cache[lkey] = parse_lock(self._text(lock_blob)) + pins = self.cache[lkey] + return self.cache[key], pins + + +def _snapshot(repo: str, sha: str, parser: _Parser) -> Tuple[model.Graph, Dict[str, str]]: + cfg = parser.cfg + names, locks = ([], []) + if cfg["manifest"]: + names, locks, _, _ = MANIFESTS[cfg["manifest"]] + excluded = tuple(cfg["exclude_prefixes"]) + files: List[Tuple[str, dict]] = [] + manifest_blob: Optional[str] = None + lock_blob: Optional[str] = None + blobs: Dict[str, str] = {} + for path, blob in gitio.tree(repo, sha): + if path in names: + manifest_blob = blob + blobs[path] = blob + elif path in locks: + lock_blob = blob + blobs[path] = blob + elif path.endswith(parser.suffixes) and not path.startswith(excluded): + files.append((path, parser.source(blob))) + blobs[path] = blob + manifest, pins = parser.manifest(manifest_blob, lock_blob) + return build.project(files, manifest, pins, cfg, parser.ambient), blobs + + +def run(repo: str, rev: str, cfg: Dict[str, Any]) -> Dict[str, Any]: + """Fold the history reachable from rev. Returns everything the writers + need: commits, per-commit deltas, node history, the head graph, and the + fold-law verification result.""" + head = gitio.resolve(repo, rev) + commits = gitio.commits(repo, head) + graphs: Dict[str, model.Graph] = {} + deltas: Dict[str, Dict[str, Any]] = {} + history: Dict[str, Dict[str, Any]] = {} + with gitio.BlobReader(repo) as reader: + parser = _Parser(reader, cfg) + for c in commits: + sha = str(c["sha"]) + graph, _ = _snapshot(repo, sha, parser) + parents = list(c["parents"]) # type: ignore[arg-type] + base = graphs[parents[0]] if parents else model.empty() + change = model.delta(base, graph) + graphs[sha] = graph + deltas[sha] = change + _track(history, sha, change) + verified = _verify_fold(commits, graphs, deltas, head) + return {"head": head, "commits": commits, "deltas": deltas, "history": history, + "graph": graphs[head], "fold_law": verified, "adapter": ADAPTER_VERSION} + + +def _track(history: Dict[str, Dict[str, Any]], sha: str, change: Dict[str, Any]) -> None: + for nid in change["nodes_added"]: + entry = history.setdefault(nid, {"first_commit": sha, "last_commit": sha, + "changes": 0, "removed_in": ""}) + entry["removed_in"] = "" + for nid in model.semantic_touched(change): + entry = history.setdefault(nid, {"first_commit": sha, "last_commit": sha, + "changes": 0, "removed_in": ""}) + entry["last_commit"] = sha + entry["changes"] += 1 + for nid in change["nodes_removed"]: + history[nid]["removed_in"] = sha + for source in ("nodes_added", "nodes_changed"): + for nid, attrs in change[source].items(): + history[nid]["attrs"] = attrs + + +def _verify_fold(commits: List[Dict[str, Any]], graphs: Dict[str, model.Graph], + deltas: Dict[str, Dict[str, Any]], head: str) -> Dict[str, Any]: + """Check apply(parent, delta) == projection for every commit, and that + folding deltas along HEAD's first-parent chain from empty reproduces + the HEAD projection.""" + per_commit_ok = 0 + failures: List[str] = [] + for c in commits: + sha = str(c["sha"]) + parents = list(c["parents"]) + base = graphs[parents[0]] if parents else model.empty() + if model.canonical(model.apply(base, deltas[sha])) == model.canonical(graphs[sha]): + per_commit_ok += 1 + else: + failures.append(sha) + parent_of = {str(c["sha"]): (list(c["parents"]) or [None])[0] for c in commits} + chain: List[str] = [] + cur: Optional[str] = head + while cur: + chain.append(cur) + cur = parent_of[cur] + state = model.empty() + for sha in reversed(chain): + state = model.apply(state, deltas[sha]) + chain_ok = model.canonical(state) == model.canonical(graphs[head]) + return {"commits_checked": len(commits), "commits_ok": per_commit_ok, + "failures": failures, "mainline_length": len(chain), + "mainline_fold_equals_head": chain_ok, + "head_digest": model.digest(graphs[head])} diff --git a/tools/codegraph/cgcore/gitio.py b/tools/codegraph/cgcore/gitio.py new file mode 100644 index 0000000..648312b --- /dev/null +++ b/tools/codegraph/cgcore/gitio.py @@ -0,0 +1,105 @@ +"""Read-only git plumbing. Reads objects; never touches the working tree. + +Side effects: spawns `git` subprocesses against the given repository. All +output is parsed from NUL- or unit-separator-delimited plumbing formats so +user config (quotepath, color, pager, locale) cannot change the result. +""" +from __future__ import annotations + +import os +import subprocess +from typing import Dict, List, Optional, Tuple + +_ENV_PIN = { + "LC_ALL": "C", "LANG": "C", "GIT_PAGER": "cat", "GIT_OPTIONAL_LOCKS": "0", + "GIT_CONFIG_NOSYSTEM": "1", "GIT_TERMINAL_PROMPT": "0", +} + + +def _env() -> Dict[str, str]: + env = dict(os.environ) + env.update(_ENV_PIN) + env.pop("GIT_DIR", None) + env.pop("GIT_WORK_TREE", None) + return env + + +def git(repo: str, *args: str) -> bytes: + return subprocess.run(["git", "-C", repo, "-c", "core.quotepath=off", *args], + check=True, capture_output=True, env=_env()).stdout + + +def resolve(repo: str, rev: str) -> str: + return git(repo, "rev-parse", "--verify", rev + "^{commit}").decode().strip() + + +def commits(repo: str, rev: str) -> List[Dict[str, object]]: + """All commits reachable from rev, parents before children (topo order). + + Each: {sha, parents, date (committer, ISO 8601), subject, generation}. + generation = 1 + max(parent generations); it never changes when new + commits are added, unlike a position in the list. + """ + fmt = "%H%x1f%P%x1f%cI%x1f%s%x1e" + raw = git(repo, "log", "--topo-order", "--reverse", "--format=" + fmt, rev).decode("utf-8", "replace") + out: List[Dict[str, object]] = [] + gen: Dict[str, int] = {} + for record in raw.split("\x1e"): + record = record.strip("\n") + if not record: + continue + sha, parents, date, subject = record.split("\x1f", 3) + plist = parents.split() if parents else [] + gen[sha] = 1 + max((gen.get(p, 0) for p in plist), default=0) + out.append({"sha": sha, "parents": plist, "date": date, "subject": subject, + "generation": gen[sha]}) + return out + + +def tree(repo: str, sha: str) -> List[Tuple[str, str]]: + """(path, blob sha) for every blob in the commit's tree, sorted by path.""" + raw = git(repo, "ls-tree", "-r", "--full-tree", "-z", sha) + out = [] + for entry in raw.split(b"\0"): + if not entry: + continue + meta, path = entry.split(b"\t", 1) + mode, kind, obj = meta.split(b" ") + if kind == b"blob" and mode != b"160000": + out.append((path.decode("utf-8", "surrogateescape"), obj.decode())) + out.sort() + return out + + +class BlobReader: + """Persistent `git cat-file --batch` reader. Use as a context manager.""" + + def __init__(self, repo: str) -> None: + self.proc: Optional[subprocess.Popen] = subprocess.Popen( + ["git", "-C", repo, "cat-file", "--batch"], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, env=_env()) + + def read(self, sha: str) -> bytes: + assert self.proc and self.proc.stdin and self.proc.stdout + self.proc.stdin.write(sha.encode() + b"\n") + self.proc.stdin.flush() + header = self.proc.stdout.readline().split() + if len(header) < 3 or header[1] == b"missing": + raise KeyError("missing object " + sha) + size = int(header[2]) + data = self.proc.stdout.read(size) + self.proc.stdout.read(1) # trailing newline + return data + + def close(self) -> None: + if self.proc: + assert self.proc.stdin + self.proc.stdin.close() + self.proc.wait() + self.proc = None + + def __enter__(self) -> "BlobReader": + return self + + def __exit__(self, *exc: object) -> None: + self.close() diff --git a/tools/codegraph/cgcore/matrix.py b/tools/codegraph/cgcore/matrix.py new file mode 100644 index 0000000..0b50cb5 --- /dev/null +++ b/tools/codegraph/cgcore/matrix.py @@ -0,0 +1,107 @@ +"""Dependency matrices rolled up from the graph. + +Pure. Three square matrices: types x types, files x files, modules x +modules. Cell (row, col) = number of use sites in `row` that depend on +`col` (sum of edge `count`). Structural edges (contains, declares, +extends) are excluded so a cell means "depends on", not "is inside". +Edges resolved as `ambiguous` are excluded and counted separately, so a +non-zero cell is never a guess. +""" +from __future__ import annotations + +import csv +import io +from typing import Any, Dict, List, Optional, Tuple + +from . import model + +STRUCTURAL = {"contains", "declares", "extends", "built-from", "requires", "pins"} + + +def _type_of(nid: str, nodes: Dict[str, Dict[str, Any]]) -> Optional[str]: + attrs = nodes.get(nid) + if attrs is None: + return None + if attrs["kind"] == "type": + return nid + if attrs["kind"] == "func" and attrs["container"]: + return attrs["container"] + return None + + +def _file_of(nid: str, nodes: Dict[str, Dict[str, Any]]) -> Optional[str]: + attrs = nodes.get(nid) + if attrs is None: + return None + if attrs["kind"] == "file": + return nid + if attrs["kind"] in ("type", "func"): + return "file:" + attrs["loc"]["file"] + return None + + +def _module_of(nid: str, nodes: Dict[str, Dict[str, Any]]) -> Optional[str]: + attrs = nodes.get(nid) + if attrs is None: + return None + if attrs["kind"] in ("module", "dependency", "framework"): + return nid + if attrs["kind"] == "file": + return "module:" + attrs["module"] + if attrs["kind"] in ("type", "func"): + return "module:" + attrs["module"] + return None + + +_ROLLUPS = {"types": _type_of, "files": _file_of, "modules": _module_of} + + +def build(graph: model.Graph, level: str) -> Dict[str, Any]: + """Return {labels, cells: {(row, col): count}, excluded_ambiguous}.""" + roll = _ROLLUPS[level] + nodes = graph["nodes"] + cells: Dict[Tuple[str, str], int] = {} + excluded = 0 + for key in sorted(graph["edges"]): + src, kind, dst = model.split_edge(key) + if kind in STRUCTURAL: + continue + row, col = roll(src, nodes), roll(dst, nodes) + if row is None or col is None or row == col: + continue + attrs = graph["edges"][key] + if attrs["resolution"] == "ambiguous": + excluded += attrs["count"] + continue + cells[(row, col)] = cells.get((row, col), 0) + attrs["count"] + labels = sorted({n for n in nodes if roll(n, nodes) == n}) + return {"labels": labels, "cells": cells, "excluded_ambiguous": excluded} + + +def to_csv(m: Dict[str, Any]) -> str: + buf = io.StringIO() + writer = csv.writer(buf, lineterminator="\n") + writer.writerow([""] + m["labels"]) + for row in m["labels"]: + writer.writerow([row] + [m["cells"].get((row, col), 0) for col in m["labels"]]) + return buf.getvalue() + + +def to_edge_csv(m: Dict[str, Any]) -> str: + """Sparse form: one line per non-zero cell; easier to diff and load.""" + buf = io.StringIO() + writer = csv.writer(buf, lineterminator="\n") + writer.writerow(["source", "target", "sites"]) + for (row, col) in sorted(m["cells"]): + writer.writerow([row, col, m["cells"][(row, col)]]) + return buf.getvalue() + + +def stats(m: Dict[str, Any]) -> List[Tuple[str, int, int]]: + """(label, fan_out, fan_in) per label: distinct non-zero columns/rows.""" + out = [] + for label in m["labels"]: + fan_out = sum(1 for (r, _c) in m["cells"] if r == label) + fan_in = sum(1 for (_r, c) in m["cells"] if c == label) + out.append((label, fan_out, fan_in)) + return out diff --git a/tools/codegraph/cgcore/model.py b/tools/codegraph/cgcore/model.py new file mode 100644 index 0000000..06112df --- /dev/null +++ b/tools/codegraph/cgcore/model.py @@ -0,0 +1,107 @@ +"""Graph model: canonical form, delta, and apply. + +A Graph is {"nodes": {id: attrs}, "edges": {edge_key: attrs}} where +edge_key is "src\\tkind\\tdst". Attribute values are JSON scalars, lists or +dicts. Every function here is pure. + +The fold law the pipeline relies on (and verifies on every run): + + apply(project(parent), delta(project(parent), project(commit))) + == project(commit) + +so folding the deltas along a first-parent chain from the empty graph +reproduces the projection at its tip. +""" +from __future__ import annotations + +import hashlib +import json +from typing import Any, Dict, List, Tuple + +Graph = Dict[str, Dict[str, Dict[str, Any]]] +LOCATION_KEYS = ("loc",) + + +def empty() -> Graph: + return {"nodes": {}, "edges": {}} + + +def edge_key(src: str, kind: str, dst: str) -> str: + return src + "\t" + kind + "\t" + dst + + +def split_edge(key: str) -> Tuple[str, str, str]: + src, kind, dst = key.split("\t") + return src, kind, dst + + +def canonical(obj: Any) -> str: + """Byte-stable JSON: sorted keys, fixed separators, no NaN, UTF-8 safe.""" + return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, + allow_nan=False) + + +def digest(obj: Any) -> str: + return hashlib.sha256(canonical(obj).encode("utf-8")).hexdigest() + + +def semantic(attrs: Dict[str, Any]) -> Dict[str, Any]: + """Attributes minus location (line numbers move on unrelated edits).""" + return {k: v for k, v in attrs.items() if k not in LOCATION_KEYS} + + +def delta(old: Graph, new: Graph) -> Dict[str, Any]: + """Difference old -> new. Changed entries carry their full new attrs. + + nodes_changed is split into `semantic` (meaning changed) and `moved` + (only location changed) for reporting; apply() treats both the same. + """ + out: Dict[str, Any] = { + "nodes_added": {}, "nodes_removed": [], "nodes_changed": {}, "nodes_moved": [], + "edges_added": {}, "edges_removed": [], "edges_changed": {}, + } + for nid in sorted(new["nodes"]): + attrs = new["nodes"][nid] + if nid not in old["nodes"]: + out["nodes_added"][nid] = attrs + elif old["nodes"][nid] != attrs: + out["nodes_changed"][nid] = attrs + if semantic(old["nodes"][nid]) == semantic(attrs): + out["nodes_moved"].append(nid) + out["nodes_removed"] = sorted(n for n in old["nodes"] if n not in new["nodes"]) + for key in sorted(new["edges"]): + attrs = new["edges"][key] + if key not in old["edges"]: + out["edges_added"][key] = attrs + elif old["edges"][key] != attrs: + out["edges_changed"][key] = attrs + out["edges_removed"] = sorted(k for k in old["edges"] if k not in new["edges"]) + return out + + +def apply(graph: Graph, change: Dict[str, Any]) -> Graph: + """Return a new graph with `change` applied. Does not mutate inputs.""" + nodes = dict(graph["nodes"]) + edges = dict(graph["edges"]) + for nid in change["nodes_removed"]: + nodes.pop(nid, None) + nodes.update(change["nodes_added"]) + nodes.update(change["nodes_changed"]) + for key in change["edges_removed"]: + edges.pop(key, None) + edges.update(change["edges_added"]) + edges.update(change["edges_changed"]) + return {"nodes": nodes, "edges": edges} + + +def semantic_touched(change: Dict[str, Any]) -> List[str]: + """Node ids whose meaning changed: added, removed, or semantically changed.""" + moved = set(change["nodes_moved"]) + ids = set(change["nodes_added"]) | set(change["nodes_removed"]) + ids |= {n for n in change["nodes_changed"] if n not in moved} + return sorted(ids) + + +def is_empty(change: Dict[str, Any]) -> bool: + return not any(change[k] for k in ("nodes_added", "nodes_removed", "nodes_changed", + "edges_added", "edges_removed", "edges_changed")) diff --git a/tools/codegraph/cgcore/resolve.py b/tools/codegraph/cgcore/resolve.py new file mode 100644 index 0000000..1c4848a --- /dev/null +++ b/tools/codegraph/cgcore/resolve.py @@ -0,0 +1,218 @@ +"""Symbol table and name resolution for one snapshot. + +Pure. Resolution is name-based (no type inference), so every resolved edge +carries how it was resolved: + exact receiver or scope pins the target, or a type name matched + unique no scope, but exactly one visible function fits the call + ambiguous several visible functions fit; an edge goes to each +Callers that need precision (the matrices) skip `ambiguous`. +""" +from __future__ import annotations + +import hashlib +from typing import Dict, Iterator, List, Optional, Tuple + +RESOLUTION_RANK = {"exact": 0, "unique": 1, "ambiguous": 2} + + +def _combine(digests: List[str]) -> str: + return hashlib.sha256("\x1f".join(sorted(digests)).encode()).hexdigest()[:16] + + +def compatible(params: List[dict], labels: List[str], trailing: bool) -> bool: + """Can a call with these argument labels bind to these parameters?""" + ptr = 0 + for param in params: + if ptr < len(labels) and labels[ptr] == param["label"]: + ptr += 1 + elif param["default"]: + continue + elif trailing and ptr == len(labels) and param["closure"]: + continue + else: + return False + return ptr == len(labels) + + +class Symbols: + """Types and functions declared in a snapshot, plus lookup tables.""" + + def __init__(self, files: List[Tuple[str, dict]], modules: Dict[str, str], + ambient: Tuple[str, ...] = ()) -> None: + self.modules = modules + self.ambient = set(ambient) + self.nodes: Dict[str, dict] = {} + self.structure_edges: List[Tuple[str, str, str]] = [] + self.by_qual: Dict[Tuple[str, str], str] = {} + self.by_simple: Dict[str, List[str]] = {} + self.keymap: Dict[Tuple[str, str], str] = {} + self.funcs_by_name: Dict[str, List[str]] = {} + self.inits: Dict[str, List[str]] = {} + self.inherits: List[Tuple[str, str, str]] = [] # (path, type id, name) + self.visible: Dict[str, List[str]] = {} + self._digests: Dict[str, List[str]] = {} + names = set(modules.values()) + for path, facts in files: + own = modules[path] + imported = sorted({i["module"] for i in facts["imports"] if i["module"] in names} - {own}) + self.visible[path] = [own] + imported + for path, facts in files: + self._types(path, facts, extensions=False) + for path, facts in files: + self._types(path, facts, extensions=True) + for path, facts in files: + self._funcs(path, facts) + for nid, digests in self._digests.items(): + self.nodes[nid]["digest"] = _combine(digests) + for name in self.by_simple: + self.by_simple[name].sort() + for name in self.funcs_by_name: + self.funcs_by_name[name].sort() + + # ── lookups ─────────────────────────────────────────────────────────── + def type_named(self, qual: str, path: str) -> Optional[str]: + for mod in self.visible[path]: + hit = self.by_qual.get((mod, qual)) + if hit: + return hit + last = qual.split(".")[-1] + cands = [t for t in self.by_simple.get(last, []) if self.nodes[t]["module"] in self.visible[path]] + return cands[0] if len(cands) == 1 else None + + def types_simple(self, name: str, path: str) -> List[str]: + """Candidates for a bare type name, nearest visibility tier first.""" + for mod in self.visible[path]: + tier = [t for t in self.by_simple.get(name, []) if self.nodes[t]["module"] == mod] + if tier: + return tier + return [] + + # ── declaration passes ──────────────────────────────────────────────── + def _register_type(self, tid: str, attrs: dict, path: str, digest: str) -> None: + if tid not in self.nodes: + self.nodes[tid] = attrs + self.by_qual[(attrs["module"], attrs["qual"])] = tid + self.by_simple.setdefault(attrs["name"], []).append(tid) + node = self.nodes[tid] + if path not in node["files"]: + node["files"] = sorted(node["files"] + [path]) + self._digests.setdefault(tid, []).append(digest) + + def _types(self, path: str, facts: dict, extensions: bool) -> None: + mod = self.modules[path] + fid = "file:" + path + for d in facts["decls"]: + if d["kind"] != "type" or d["extension"] != extensions: + continue + qual = d["key"][len("type:"):] + if extensions: + tid = self.type_named(qual, path) + if tid is None: + tid = "type:" + mod + "." + qual + self._register_type(tid, self._type_attrs(d, mod, qual, path, external=True), path, d["digest"]) + else: + self._register_type(tid, self.nodes[tid], path, d["digest"]) + self.structure_edges.append((fid, "extends", tid)) + else: + tid = "type:" + mod + "." + qual + self._register_type(tid, self._type_attrs(d, mod, qual, path, external=False), path, d["digest"]) + parent = self.by_qual.get((mod, d["container"])) if d["container"] else None + self.structure_edges.append((parent or fid, "contains", tid)) + if parent: + self.structure_edges.append((fid, "declares", tid)) + self.keymap[(path, d["key"])] = tid + for name in d["inherits"]: + self.inherits.append((path, tid, name)) + + @staticmethod + def _type_attrs(d: dict, mod: str, qual: str, path: str, external: bool) -> dict: + return {"kind": "type", "subkind": d["subkind"], "name": qual.split(".")[-1], "qual": qual, + "module": mod, "access": d["access"], "external": external, "files": [], + "loc": {"file": path, "line": d["line"], "end_line": d["end_line"]}} + + def _funcs(self, path: str, facts: dict) -> None: + mod = self.modules[path] + for d in facts["decls"]: + if d["kind"] != "func": + continue + container = self.type_named(d["container"], path) if d["container"] else None + if d["container"] and container is None: + container = "type:" + mod + "." + d["container"] + if container not in self.nodes: + stub = dict(d, subkind="extension", line=d["line"], end_line=d["line"]) + self._register_type(container, self._type_attrs(stub, mod, d["container"], path, True), + path, "") + qual = self.nodes[container]["qual"] + "." if container else "" + owner_mod = self.nodes[container]["module"] if container else mod + fnid = "func:" + owner_mod + "." + qual + d["selector"] + if fnid not in self.nodes: + self.nodes[fnid] = { + "kind": "func", "subkind": d["subkind"], "name": d["name"], + "selector": d["selector"], "module": owner_mod, "container": container or "", + "access": d["access"], "static": d["static"], "requirement": d["requirement"], + "params": d["params"], "file": path, + "loc": {"file": path, "line": d["line"], "end_line": d["end_line"]}} + self.funcs_by_name.setdefault(d["name"], []).append(fnid) + if d["name"] == "init" and container: + self.inits.setdefault(container, []).append(fnid) + self.structure_edges.append((container or "file:" + path, "contains", fnid)) + if container: + self.structure_edges.append(("file:" + path, "declares", fnid)) + self._digests.setdefault(fnid, []).append(d["digest"]) + self.keymap[(path, d["key"])] = fnid + + +def _call_targets(sym: Symbols, path: str, owner: str, use: dict) -> Tuple[List[str], str]: + name, labels, trailing, receiver = use["name"], use["labels"], use["trailing"], use["receiver"] + owner_type = owner if owner.startswith("type:") else sym.nodes.get(owner, {}).get("container", "") + if name[:1].isupper() and receiver is None: + types = sym.types_simple(name, path) + if len(types) != 1: + return [], "exact" + inits = [f for f in sym.inits.get(types[0], []) + if compatible(sym.nodes[f]["params"], labels, trailing)] + return (inits, "exact") if len(inits) == 1 else (types, "exact") + scope: Optional[str] = None + if receiver in ("self", "Self"): + scope = owner_type or None + elif receiver and receiver[:1].isupper(): + scope = sym.type_named(receiver, path) + if scope is None: + return [], "exact" + cands = [f for f in sym.funcs_by_name.get(name, []) + if sym.nodes[f]["module"] in sym.visible[path] + and compatible(sym.nodes[f]["params"], labels, trailing)] + if scope: + return [f for f in cands if sym.nodes[f]["container"] == scope], "exact" + if receiver is None: + for tier in ([f for f in cands if owner_type and sym.nodes[f]["container"] == owner_type], + [f for f in cands if not sym.nodes[f]["container"]]): + if tier: + return tier, "exact" if len(tier) == 1 else "ambiguous" + if len(cands) == 1 and name not in sym.ambient: + return cands, "unique" + return cands, "ambiguous" + + +def use_edges(files: List[Tuple[str, dict]], modules: Dict[str, str], + sym: Symbols) -> Iterator[Tuple[str, str, str, str]]: + """Yield (src, kind, dst, resolution) for every resolvable use.""" + for path, tid, name in sym.inherits: + hit = sym.type_named(name, path) + yield tid, "conforms", hit or "extern:" + name, "exact" + for path, facts in files: + fid = "file:" + path + for use in facts["uses"]: + owner = sym.keymap.get((path, use["owner"]), fid) if use["owner"] else fid + if use["kind"] == "api": + yield owner, "uses-api", "api:" + use["name"], "exact" + elif use["kind"] == "ref": + cands = sym.types_simple(use["name"], path) + res = "exact" if len(cands) == 1 else "ambiguous" + for dst in cands: + yield owner, "references", dst, res + else: + targets, res = _call_targets(sym, path, owner, use) + for dst in targets: + kind = "instantiates" if dst.startswith("type:") else "calls" + yield owner, kind, dst, res diff --git a/tools/codegraph/cgcore/review.py b/tools/codegraph/cgcore/review.py new file mode 100644 index 0000000..96540b0 --- /dev/null +++ b/tools/codegraph/cgcore/review.py @@ -0,0 +1,131 @@ +"""Graph-grounded review queries. Pure; every finding cites graph nodes. + +These are leads for a human or model reviewer, not verdicts: a function +with no caller may be called through a protocol or from outside the repo. +""" +from __future__ import annotations + +from typing import Any, Dict, List, Set, Tuple + +from . import matrix, model +from . import vault_names as vn + + +def _callers(graph: model.Graph) -> Dict[str, Set[str]]: + inc: Dict[str, Set[str]] = {} + for key in graph["edges"]: + src, kind, dst = model.split_edge(key) + if kind in ("calls", "instantiates"): + inc.setdefault(dst, set()).add(src) + return inc + + +def _reach(graph: model.Graph, roots: Set[str]) -> Set[str]: + out: Dict[str, Set[str]] = {} + for key in graph["edges"]: + src, kind, dst = model.split_edge(key) + if kind in ("calls", "instantiates"): + out.setdefault(src, set()).add(dst) + seen, stack = set(roots), sorted(roots) + while stack: + cur = stack.pop() + for nxt in sorted(out.get(cur, ())): + if nxt not in seen: + seen.add(nxt) + stack.append(nxt) + return seen + + +def _sccs(labels: List[str], cells: Dict[Tuple[str, str], int]) -> List[List[str]]: + """Tarjan's strongly connected components, deterministic order.""" + adj: Dict[str, List[str]] = {lab: [] for lab in labels} + for (row, col) in sorted(cells): + adj[row].append(col) + index: Dict[str, int] = {} + low: Dict[str, int] = {} + stack: List[str] = [] + on: Set[str] = set() + out: List[List[str]] = [] + counter = [0] + + def visit(v: str) -> None: + index[v] = low[v] = counter[0] + counter[0] += 1 + stack.append(v) + on.add(v) + for w in adj[v]: + if w not in index: + visit(w) + low[v] = min(low[v], low[w]) + elif w in on: + low[v] = min(low[v], index[w]) + if low[v] == index[v]: + comp = [] + while True: + w = stack.pop() + on.discard(w) + comp.append(w) + if w == v: + break + if len(comp) > 1: + out.append(sorted(comp)) + + for v in labels: + if v not in index: + visit(v) + return sorted(out) + + +def findings(graph: model.Graph, history: Dict[str, Dict[str, Any]], + names: Dict[str, Tuple[str, str]], cfg: Dict[str, Any]) -> str: + nodes = graph["nodes"] + lk = lambda nid: vn.link(*names[nid]) # noqa: E731 + test_mods = set(cfg["test_modules"]) + funcs = {n: a for n, a in nodes.items() if a["kind"] == "func"} + callers = _callers(graph) + lines = [vn.frontmatter({"codegraph": "review"}, ["codegraph", "codegraph/review"]), + "# Review - Graph Findings", "", + "Leads computed from the HEAD graph. Each is a query result, not a verdict.", ""] + + lines += ["## API probe sites", ""] + for key in sorted(graph["edges"]): + src, kind, dst = model.split_edge(key) + if kind == "uses-api" and nodes.get(src, {}).get("module") not in test_mods: + lines.append("- " + lk(dst) + " in " + lk(src) + " ×" + str(graph["edges"][key]["count"])) + + lines += ["", "## Private functions with no caller in the graph", ""] + for nid in sorted(funcs): + a = funcs[nid] + if a["access"] in ("private", "fileprivate") and a["subkind"] == "func" and nid not in callers: + lines.append("- " + lk(nid)) + + lines += ["", "## Non-test functions no test reaches (direct or transitive calls)", ""] + roots = {n for n, a in nodes.items() if a.get("module") in test_mods} + reached = _reach(graph, roots) + untested = [n for n, a in sorted(funcs.items()) + if a["module"] not in test_mods and not a["requirement"] and n not in reached] + lines.append(str(len(untested)) + " of " + str(sum(1 for a in funcs.values() + if a["module"] not in test_mods)) + + " non-test functions. Resolution is by name, so this undercounts reach through protocols and closures.") + lines += ["- " + lk(n) for n in untested] + + for level in ("types", "files"): + m = matrix.build(graph, level) + lines += ["", "## Dependency cycles between " + level, ""] + cycles = _sccs(m["labels"], m["cells"]) + lines += ["- " + " ↔ ".join(lk(n) for n in comp) for comp in cycles] or ["- none"] + lines += ["", "## Highest fan-in " + level, ""] + ranked = sorted(matrix.stats(m), key=lambda s: (-s[2], s[0]))[:10] + lines += ["- " + lk(lab) + " · in " + str(fi) + " · out " + str(fo) for lab, fo, fi in ranked] + + lines += ["", "## Most-changed nodes across the fold", ""] + churn = sorted(((h["changes"], n) for n, h in history.items() if n in nodes + and nodes[n]["kind"] in ("func", "type")), key=lambda x: (-x[0], x[1]))[:15] + lines += ["- " + lk(n) + " · " + str(c) + " semantic changes" for c, n in churn] + + res: Dict[str, int] = {} + for attrs in graph["edges"].values(): + res[attrs["resolution"]] = res.get(attrs["resolution"], 0) + attrs["count"] + lines += ["", "## Resolution quality", ""] + lines += ["- " + k + ": " + str(res[k]) + " sites" for k in sorted(res)] + return "\n".join(lines) + "\n" diff --git a/tools/codegraph/cgcore/sbom.py b/tools/codegraph/cgcore/sbom.py new file mode 100644 index 0000000..1411803 --- /dev/null +++ b/tools/codegraph/cgcore/sbom.py @@ -0,0 +1,62 @@ +"""CycloneDX 1.5 JSON SBOM from the graph's dependency nodes. + +Pure and deterministic: no timestamp, no random serialNumber, sorted +components. This is the hand-off format for Theatre of Dependencies +(`theatre scan --json --offline`), which reads CycloneDX by purl. +With no external dependencies the SBOM is empty but valid. +""" +from __future__ import annotations + +from typing import Any, Dict, List +from urllib.parse import urlparse + +from . import model + + +def _purl(attrs: Dict[str, Any]) -> str: + """pkg:swift//@ per the purl Swift type.""" + loc = attrs.get("location", "") + parsed = urlparse(loc) + if parsed.scheme in ("http", "https") and parsed.netloc: + path = parsed.path.strip("/") + if path.endswith(".git"): + path = path[:-4] + purl = "pkg:swift/" + parsed.netloc.lower() + "/" + path + else: + purl = "pkg:swift/" + attrs["name"] + version = attrs.get("version") or attrs.get("revision") or "" + return purl + ("@" + version if version else "") + + +def build(graph: model.Graph, project: str) -> Dict[str, Any]: + nodes = graph["nodes"] + pkg = next((n for n in sorted(nodes) if nodes[n]["kind"] == "package"), "") + root_ref = "root:" + (nodes[pkg]["name"] if pkg else project) + components: List[Dict[str, Any]] = [] + direct: List[str] = [] + for nid in sorted(nodes): + attrs = nodes[nid] + if attrs["kind"] != "dependency": + continue + purl = _purl(attrs) + comp: Dict[str, Any] = {"type": "library", "bom-ref": purl, "name": attrs["name"], + "purl": purl} + if attrs.get("version"): + comp["version"] = attrs["version"] + if attrs.get("location"): + comp["externalReferences"] = [{"type": "vcs", "url": attrs["location"]}] + components.append(comp) + if attrs.get("direct"): + direct.append(purl) + return { + "bomFormat": "CycloneDX", "specVersion": "1.5", "version": 1, + "metadata": { + "tools": {"components": [{"type": "application", "name": "codegraph"}]}, + "component": {"type": "application", "bom-ref": root_ref, + "name": nodes[pkg]["name"] if pkg else project}, + }, + "components": components, + # Only the root's edges are known offline. Listing a component with + # an empty dependsOn would assert it has none, so they are omitted. + "dependencies": [{"ref": root_ref, "dependsOn": sorted(direct)}], + } diff --git a/tools/codegraph/cgcore/vault_names.py b/tools/codegraph/cgcore/vault_names.py new file mode 100644 index 0000000..f47d2f8 --- /dev/null +++ b/tools/codegraph/cgcore/vault_names.py @@ -0,0 +1,92 @@ +"""Obsidian note names, folders, links and safe text. Pure. + +Obsidian forbids * " \\ / < > : | ? # ^ [ ] in note names, and link text +cannot hold | or ]. Every name is derived from the node id alone, so the +same node always gets the same note, in every run and at every commit. +""" +from __future__ import annotations + +import json +import re +from typing import Any, Dict, List + +FOLDERS = { + "package": "Package", "product": "Products", "module": "Modules", + "dependency": "Dependencies", "framework": "Frameworks", "file": "Files", + "type": "Types", "func": "Functions", "extern": "External", "api": "API", +} +PREFIX = { + "package": "Package", "product": "Product", "module": "Module", + "dependency": "Dependency", "framework": "Framework", "file": "File", + "type": "Type", "func": "Func", "extern": "Extern", "api": "API", +} +_FORBIDDEN = re.compile(r'[*"\\/<>:|?#^\[\]]') + + +def _clean(text: str) -> str: + return _FORBIDDEN.sub("_", text) + + +def selector_display(selector: str) -> str: + """lighthouseFloor(for:isLighthouse:) -> lighthouseFloor(for,isLighthouse)""" + if "(" not in selector: + return selector + name, rest = selector.split("(", 1) + labels = [p for p in rest.rstrip(")").split(":") if p] + return name + "(" + ",".join(labels) + ")" + + +def note_name(nid: str, attrs: Dict[str, Any]) -> str: + kind = attrs["kind"] + body = nid.split(":", 1)[1] + if kind == "file": + body = " › ".join(attrs["path"].split("/")) + elif kind == "func": + head = body[: len(body) - len(attrs["selector"])] + body = head + selector_display(attrs["selector"]) + return PREFIX[kind] + " - " + _clean(body) + + +def commit_name(sha: str) -> str: + return "Commit " + sha[:12] + + +def folder(attrs: Dict[str, Any], removed: bool) -> str: + return "Removed" if removed else FOLDERS[attrs["kind"]] + + +def short_label(nid: str, attrs: Dict[str, Any]) -> str: + kind = attrs["kind"] + if kind == "func": + owner = attrs["container"].split(".")[-1] + "." if attrs["container"] else "" + return owner + attrs["selector"] + if kind == "type": + return attrs["qual"] + if kind == "file": + return attrs["path"] + return attrs.get("name", nid) + + +def link(name: str, label: str = "") -> str: + label = label.replace("|", "¦").replace("]", ")").replace("[", "(") + return "[[" + name + ("|" + label if label and label != name else "") + "]]" + + +def text(value: str) -> str: + """Neutralise wiki/markup syntax in text copied from git (subjects).""" + value = value.replace("[[", "[ [").replace("]]", "] ]").replace("|", "¦") + return value.lstrip("#>").strip() or "(empty)" + + +def frontmatter(fields: Dict[str, Any], tags: List[str]) -> str: + """YAML frontmatter; values are JSON-encoded, which YAML 1.2 parses.""" + lines = ["---"] + for key in sorted(fields): + lines.append(key + ": " + json.dumps(fields[key], ensure_ascii=False, sort_keys=True)) + lines.append("tags: " + json.dumps(sorted(set(tags)), ensure_ascii=False)) + lines.append("---") + return "\n".join(lines) + "\n" + + +def tag(text_value: str) -> str: + return re.sub(r"[^A-Za-z0-9_/-]", "-", text_value) diff --git a/tools/codegraph/cgcore/vault_nodes.py b/tools/codegraph/cgcore/vault_nodes.py new file mode 100644 index 0000000..232af18 --- /dev/null +++ b/tools/codegraph/cgcore/vault_nodes.py @@ -0,0 +1,127 @@ +"""One Obsidian note per graph node (live at HEAD, or removed in history). + +Pure: returns {relative path: note text}. +""" +from __future__ import annotations + +from typing import Any, Dict, List, Tuple + +from . import model +from . import vault_names as vn + +INCOMING = { + "calls": "called by", "references": "referenced by", "contains": "contained in", + "declares": "declared in", "extends": "extended in", "conforms": "conformed to by", + "imports": "imported by", "instantiates": "instantiated by", "uses-api": "used by", + "depends-on": "depended on by", "built-from": "builds", "requires": "required by", + "pins": "pinned by", +} +_MARK = {"exact": "", "unique": " · by selector", "ambiguous": " · ambiguous"} + + +def _adjacency(graph: model.Graph) -> Tuple[Dict[str, list], Dict[str, list]]: + out: Dict[str, list] = {} + inc: Dict[str, list] = {} + for key in sorted(graph["edges"]): + src, kind, dst = model.split_edge(key) + attrs = graph["edges"][key] + out.setdefault(src, []).append((kind, dst, attrs)) + inc.setdefault(dst, []).append((kind, src, attrs)) + return out, inc + + +def _edge_lines(entries: List[tuple], names: Dict[str, Tuple[str, str]], label_of) -> List[str]: + lines: List[str] = [] + by_kind: Dict[str, List[tuple]] = {} + for kind, other, attrs in entries: + by_kind.setdefault(kind, []).append((other, attrs)) + for kind in sorted(by_kind): + items = sorted(by_kind[kind], key=lambda x: x[0]) + lines.append("### " + label_of(kind) + " (" + str(len(items)) + ")") + for other, attrs in items: + name, label = names[other] + count = " ×" + str(attrs["count"]) if attrs["count"] > 1 else "" + lines.append("- " + vn.link(name, label) + count + _MARK[attrs["resolution"]]) + lines.append("") + return lines + + +def _summary(nid: str, attrs: Dict[str, Any], names: Dict[str, Tuple[str, str]]) -> List[str]: + lines = [] + loc = attrs.get("loc") + if loc: + fname = names.get("file:" + loc["file"], (loc["file"], "")) + lines.append("Declared in " + vn.link(*fname) + " · lines " + str(loc["line"]) + + "–" + str(loc["end_line"])) + if attrs["kind"] == "func" and attrs["container"]: + lines.append("Member of " + vn.link(*names[attrs["container"]])) + if attrs["kind"] == "func" and attrs["requirement"]: + lines.append("Requirement only (no body).") + if attrs.get("external"): + lines.append("Extension of a type not declared in this repo.") + for key in ("requirement", "version", "revision", "location"): + if attrs["kind"] == "dependency" and attrs.get(key): + lines.append(key.capitalize() + ": `" + str(attrs[key]) + "`") + return lines + + +def _fields(nid: str, attrs: Dict[str, Any], hist: Dict[str, Any], status: str) -> Dict[str, Any]: + fields: Dict[str, Any] = {"codegraph": "node", "id": nid, "kind": attrs["kind"], + "status": status} + for key in ("subkind", "module", "access", "digest", "selector", "qual", "path"): + if attrs.get(key) not in (None, ""): + fields[key] = attrs[key] + if attrs.get("loc"): + fields["path"] = attrs["loc"]["file"] + fields["lines"] = str(attrs["loc"]["line"]) + "-" + str(attrs["loc"]["end_line"]) + if hist: + fields["first_commit"] = hist["first_commit"][:12] + fields["last_commit"] = hist["last_commit"][:12] + fields["semantic_changes"] = hist["changes"] + if hist.get("removed_in"): + fields["removed_in"] = hist["removed_in"][:12] + return fields + + +def _history_lines(hist: Dict[str, Any]) -> List[str]: + if not hist: + return [] + line = ("First seen " + vn.link(vn.commit_name(hist["first_commit"])) + + " · last changed " + vn.link(vn.commit_name(hist["last_commit"])) + + " · " + str(hist["changes"]) + " semantic change(s)") + if hist.get("removed_in"): + line += " · removed in " + vn.link(vn.commit_name(hist["removed_in"])) + return [line] + + +def render(graph: model.Graph, history: Dict[str, Dict[str, Any]]) -> Dict[str, str]: + nodes = dict(graph["nodes"]) + removed = {nid: h["attrs"] for nid, h in history.items() + if nid not in nodes and "attrs" in h} + every = dict(removed) + every.update(nodes) + names = {nid: (vn.note_name(nid, a), vn.short_label(nid, a)) for nid, a in every.items()} + out_adj, in_adj = _adjacency(graph) + notes: Dict[str, str] = {} + for nid in sorted(every): + attrs = every[nid] + is_removed = nid in removed + hist = history.get(nid, {}) + tags = ["codegraph", "codegraph/" + attrs["kind"], "status/" + ("removed" if is_removed else "live")] + if attrs.get("module"): + tags.append("module/" + vn.tag(attrs["module"])) + if attrs.get("subkind"): + tags.append("kind/" + vn.tag(attrs["subkind"])) + body = [vn.frontmatter(_fields(nid, attrs, hist, "removed" if is_removed else "live"), tags), + "# " + vn.short_label(nid, attrs), ""] + body += _summary(nid, attrs, names) + _history_lines(hist) + [""] + if is_removed: + body.append("Not present at HEAD; attributes are the last known projection.") + body.append("") + else: + body += ["## Outgoing", ""] + _edge_lines(out_adj.get(nid, []), names, lambda k: k) + body += ["## Incoming", ""] + _edge_lines(in_adj.get(nid, []), names, + lambda k: INCOMING.get(k, k + " (in)")) + path = vn.folder(attrs, is_removed) + "/" + names[nid][0] + ".md" + notes[path] = "\n".join(body).rstrip("\n") + "\n" + return notes diff --git a/tools/codegraph/cgcore/vault_pages.py b/tools/codegraph/cgcore/vault_pages.py new file mode 100644 index 0000000..8cc7fa8 --- /dev/null +++ b/tools/codegraph/cgcore/vault_pages.py @@ -0,0 +1,136 @@ +"""Commit notes, timeline, matrices and the index. Pure.""" +from __future__ import annotations + +from typing import Any, Dict, List, Tuple + +from . import matrix, model +from . import vault_names as vn + + +def _names(graph: model.Graph, history: Dict[str, Dict[str, Any]]) -> Dict[str, Tuple[str, str]]: + every = {nid: h["attrs"] for nid, h in history.items() if "attrs" in h} + every.update(graph["nodes"]) + return {nid: (vn.note_name(nid, a), vn.short_label(nid, a)) for nid, a in every.items()} + + +def _counts(change: Dict[str, Any]) -> Dict[str, int]: + moved = len(change["nodes_moved"]) + return {"nodes_added": len(change["nodes_added"]), "nodes_removed": len(change["nodes_removed"]), + "nodes_changed": len(change["nodes_changed"]) - moved, "nodes_moved": moved, + "edges_added": len(change["edges_added"]), "edges_removed": len(change["edges_removed"]), + "edges_changed": len(change["edges_changed"])} + + +def _edge_line(key: str, names: Dict[str, Tuple[str, str]]) -> str: + src, kind, dst = model.split_edge(key) + return "- " + vn.link(*names[src]) + " —" + kind + "→ " + vn.link(*names[dst]) + + +def commit_notes(commits: List[Dict[str, Any]], deltas: Dict[str, Dict[str, Any]], + names: Dict[str, Tuple[str, str]]) -> Dict[str, str]: + """One immutable note per commit: depends only on that commit and its + first parent, so adding history never rewrites an existing commit note.""" + notes = {} + for c in commits: + sha = c["sha"] + change = deltas[sha] + counts = _counts(change) + fields = {"codegraph": "commit", "sha": sha, "parents": c["parents"], + "generation": c["generation"], "date": c["date"], "subject": c["subject"]} + fields.update(counts) + body = [vn.frontmatter(fields, ["codegraph", "codegraph/commit"]), + "# " + vn.text(c["subject"]), "", + "`" + sha[:12] + "` · " + c["date"] + " · generation " + str(c["generation"])] + if c["parents"]: + body.append("Parents: " + " · ".join(vn.link(vn.commit_name(p)) for p in c["parents"]) + + (" (merge; delta is against the first parent)" if len(c["parents"]) > 1 else "")) + else: + body.append("Root commit; delta is against the empty graph.") + body.append("") + if model.is_empty(change): + body.append("No change to the code graph.") + else: + body.append("Nodes +{nodes_added} −{nodes_removed} ~{nodes_changed} (moved only: {nodes_moved}) · " + "edges +{edges_added} −{edges_removed} ~{edges_changed}".format(**counts)) + moved = set(change["nodes_moved"]) + sections = [("Added", sorted(change["nodes_added"])), + ("Removed", change["nodes_removed"]), + ("Changed", sorted(n for n in change["nodes_changed"] if n not in moved))] + for title, ids in sections: + if ids: + body += ["", "## " + title + " nodes (" + str(len(ids)) + ")"] + body += ["- " + vn.link(*names[n]) for n in ids] + for title, keys in (("added", sorted(change["edges_added"])), + ("removed", change["edges_removed"])): + if keys: + body += ["", "## Edges " + title + " (" + str(len(keys)) + ")"] + body += [_edge_line(k, names) for k in keys] + notes["Commits/" + vn.commit_name(sha) + ".md"] = "\n".join(body).rstrip("\n") + "\n" + return notes + + +def timeline(commits: List[Dict[str, Any]], deltas: Dict[str, Dict[str, Any]]) -> str: + rows = ["| # | commit | date | subject | +n | −n | ~n | +e | −e |", + "|---|---|---|---|---|---|---|---|---|"] + for i, c in enumerate(commits, 1): + k = _counts(deltas[c["sha"]]) + rows.append("| {} | {} | {} | {} | {} | {} | {} | {} | {} |".format( + i, vn.link(vn.commit_name(c["sha"]), c["sha"][:7]), c["date"][:10], vn.text(c["subject"]), + k["nodes_added"], k["nodes_removed"], k["nodes_changed"], k["edges_added"], k["edges_removed"])) + head = vn.frontmatter({"codegraph": "timeline", "commits": len(commits)}, ["codegraph"]) + intro = ("# Timeline\n\nThe fold, oldest first (git topo order). Replay a change by opening " + "its commit note; each delta is against the commit's first parent, and folding the " + "deltas along the first-parent chain reproduces the HEAD graph.\n\n") + return head + intro + "\n".join(rows) + "\n" + + +def matrix_note(level: str, m: Dict[str, Any], names: Dict[str, Tuple[str, str]]) -> str: + labels = m["labels"] + width = len(str(len(labels))) + code = {lab: level[0].upper() + str(i).zfill(width) for i, lab in enumerate(labels, 1)} + lines = [vn.frontmatter({"codegraph": "matrix", "level": level, "size": len(labels), + "excluded_ambiguous_sites": m["excluded_ambiguous"]}, ["codegraph", "codegraph/matrix"]), + "# Dependency matrix: " + level, "", + "Row depends on column; a cell is the number of use sites. Structural edges are left out; " + + str(m["excluded_ambiguous"]) + " ambiguous call sites are left out so no cell is a guess. " + "Full data: `_data/matrix-" + level + ".csv` (dense) and `_data/matrix-" + level + "-edges.csv`.", + "", "## Legend", ""] + fan = {lab: (o, i) for lab, o, i in matrix.stats(m)} + for lab in labels: + lines.append("- `" + code[lab] + "` " + vn.link(*names[lab]) + " · out " + str(fan[lab][0]) + + " · in " + str(fan[lab][1])) + lines += ["", "## Matrix", "", "| | " + " | ".join(code[c] for c in labels) + " |", + "|---|" + "---|" * len(labels)] + for row in labels: + cells = [str(m["cells"].get((row, col), "")) for col in labels] + lines.append("| `" + code[row] + "` | " + " | ".join(cells) + " |") + return "\n".join(lines) + "\n" + + +def index(meta: Dict[str, Any], graph: model.Graph, names: Dict[str, Tuple[str, str]]) -> str: + kinds: Dict[str, int] = {} + for attrs in graph["nodes"].values(): + kinds[attrs["kind"]] = kinds.get(attrs["kind"], 0) + 1 + law = meta["fold_law"] + lines = [vn.frontmatter({"codegraph": "index", "head": meta["head"], "generator": meta["generator"], + "adapter": meta["adapter"], "nodes": len(graph["nodes"]), + "edges": len(graph["edges"]), "commits": law["commits_checked"], + "graph_digest": law["head_digest"]}, ["codegraph"]), + "# " + meta["title"], "", + "Generated by codegraph " + meta["generator"] + " from `" + meta["head"][:12] + + "`. Every note is a pure function of the git objects, the config and the generator " + "version; rerunning changes nothing.", "", + "## Fold law", "", + "- apply(parent, delta) == projection on " + str(law["commits_ok"]) + " of " + + str(law["commits_checked"]) + " commits", + "- folding " + str(law["mainline_length"]) + " first-parent deltas from empty reproduces HEAD: " + + ("yes" if law["mainline_fold_equals_head"] else "NO"), "", + "## Start here", "", + "- [[Timeline]] · [[Review - Graph Findings]]", + "- [[Matrix - modules]] · [[Matrix - files]] · [[Matrix - types]]", "", + "## Counts", ""] + lines += ["- " + k + ": " + str(kinds[k]) for k in sorted(kinds)] + lines += ["", "## Modules", ""] + lines += ["- " + vn.link(*names[n]) for n in sorted(graph["nodes"]) + if graph["nodes"][n]["kind"] in ("package", "product", "module", "dependency", "framework")] + return "\n".join(lines) + "\n" diff --git a/tools/codegraph/cgcore/writer.py b/tools/codegraph/cgcore/writer.py new file mode 100644 index 0000000..3d55c4a --- /dev/null +++ b/tools/codegraph/cgcore/writer.py @@ -0,0 +1,87 @@ +"""Write a generated tree to disk without ever destroying earlier output. + +Side effects (the only module in cgcore that writes files): + - refuses to write into a non-empty directory that has no manifest, so + it can never clobber a folder it did not create; + - writes a file only when its bytes change (idempotent: a rerun on the + same input writes nothing and leaves mtimes alone); + - before overwriting or dropping a file, moves the old copy to + .archive/-/ (Obsidian ignores + dot-folders), so hand edits and past builds stay recoverable; + - writes .codegraph-manifest.json last; it lists every file with its + sha256 and has no timestamp. +""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +from typing import Any, Dict + +MANIFEST = ".codegraph-manifest.json" +ARCHIVE = ".archive" + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _read(path: str) -> bytes: + with open(path, "rb") as handle: + return handle.read() + + +def _archive(out_dir: str, rel: str, slot: str) -> None: + src = os.path.join(out_dir, rel) + dst = os.path.join(out_dir, ARCHIVE, slot, rel) + if os.path.exists(dst) and _read(dst) == _read(src): + os.remove(src) + return + n = 1 + while os.path.exists(dst): + dst = os.path.join(out_dir, ARCHIVE, slot + "." + str(n), rel) + n += 1 + os.makedirs(os.path.dirname(dst), exist_ok=True) + shutil.move(src, dst) + + +def write_tree(out_dir: str, files: Dict[str, str], meta: Dict[str, Any]) -> Dict[str, int]: + """Sync `files` ({relative path: text}) into out_dir. Returns counts.""" + manifest_path = os.path.join(out_dir, MANIFEST) + previous: Dict[str, Any] = {"files": {}, "head": "none"} + if os.path.isdir(out_dir) and os.listdir(out_dir): + if not os.path.exists(manifest_path): + raise RuntimeError(out_dir + " is not empty and has no " + MANIFEST + + "; refusing to write into a folder codegraph did not create") + previous = json.loads(_read(manifest_path).decode("utf-8")) + slot = str(previous.get("head", "none"))[:12] + "-" + _sha( + json.dumps(previous, sort_keys=True).encode())[:8] + counts = {"written": 0, "unchanged": 0, "archived": 0} + encoded = {rel: text.encode("utf-8") for rel, text in files.items()} + for rel in sorted(encoded): + if rel.startswith((ARCHIVE + "/", MANIFEST)) or ".." in rel.split("/"): + raise ValueError("refusing generated path " + rel) + path = os.path.join(out_dir, rel) + if os.path.exists(path): + if _read(path) == encoded[rel]: + counts["unchanged"] += 1 + continue + _archive(out_dir, rel, slot) + counts["archived"] += 1 + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as handle: + handle.write(encoded[rel]) + counts["written"] += 1 + for rel in sorted(previous["files"]): + if rel not in encoded and os.path.exists(os.path.join(out_dir, rel)): + _archive(out_dir, rel, slot) + counts["archived"] += 1 + manifest = dict(meta) + manifest["files"] = {rel: _sha(encoded[rel]) for rel in sorted(encoded)} + text = json.dumps(manifest, sort_keys=True, indent=1, ensure_ascii=False) + "\n" + if not os.path.exists(manifest_path) or _read(manifest_path) != text.encode("utf-8"): + os.makedirs(out_dir, exist_ok=True) + with open(manifest_path, "wb") as handle: + handle.write(text.encode("utf-8")) + return counts diff --git a/tools/codegraph/codegraph.config.json b/tools/codegraph/codegraph.config.json new file mode 100644 index 0000000..c4260f3 --- /dev/null +++ b/tools/codegraph/codegraph.config.json @@ -0,0 +1,17 @@ +{ + "schema": "codegraph-config/1", + "project": "context-synapse", + "language": "swift", + "manifest": "swiftpm", + "exclude_prefixes": [".build/", "site/", "codegraph-vault/"], + "module_fallback": [ + {"prefix": "Sources/", "segment": 1}, + {"prefix": "Tests/", "name": "Tests"} + ], + "api_probes": [ + "hashValue", "Date()", "UUID()", "random()", "print()", "fatalError()", + "precondition()", "try!", "as!", "ProcessInfo", "FileManager", "URLSession" + ], + "test_modules": ["BayesianConvergenceTests", "Tests"], + "output_dir": "codegraph-vault" +} diff --git a/tools/codegraph/codegraph.py b/tools/codegraph/codegraph.py new file mode 100644 index 0000000..99322d5 --- /dev/null +++ b/tools/codegraph/codegraph.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""codegraph: fold a repo's git history into a code graph, dependency +matrices and an Obsidian vault. + +Usage (from the repo root): + python3 tools/codegraph/codegraph.py # HEAD -> codegraph-vault/ + python3 tools/codegraph/codegraph.py --rev v0.3.0 --out /tmp/vault-v030 + python3 tools/codegraph/codegraph.py --json-only # print the HEAD graph digest + +Deterministic: output is a pure function of the git objects reachable from +--rev, the config file, and GENERATOR. The working tree is never read. +Python 3.9+ standard library only; no network. +""" +from __future__ import annotations + +import argparse +import os +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) # our own package only; see README "Why sys.path" + +from cgcore import config, fold, matrix, model, review, sbom, writer # noqa: E402 +from cgcore import vault_nodes, vault_pages # noqa: E402 + +GENERATOR = "0.1.0" + + +def _repo_root(path: str) -> str: + return subprocess.run(["git", "-C", path, "rev-parse", "--show-toplevel"], check=True, + capture_output=True, text=True).stdout.strip() + + +def generate(repo: str, rev: str, cfg: dict) -> tuple: + """Return (files {rel: text}, meta, fold result). No side effects beyond + reading git objects.""" + result = fold.run(repo, rev, cfg) + graph, history = result["graph"], result["history"] + names = vault_pages._names(graph, history) + files = {} + files.update(vault_nodes.render(graph, history)) + files.update(vault_pages.commit_notes(result["commits"], result["deltas"], names)) + files["Timeline.md"] = vault_pages.timeline(result["commits"], result["deltas"]) + for level in ("modules", "files", "types"): + m = matrix.build(graph, level) + files["Matrix - " + level + ".md"] = vault_pages.matrix_note(level, m, names) + files["_data/matrix-" + level + ".csv"] = matrix.to_csv(m) + files["_data/matrix-" + level + "-edges.csv"] = matrix.to_edge_csv(m) + files["Review - Graph Findings.md"] = review.findings(graph, history, names, cfg) + files["_data/graph.json"] = model.canonical(graph) + "\n" + files["_data/sbom.cdx.json"] = model.canonical(sbom.build(graph, cfg["project"])) + "\n" + files["_data/fold.json"] = model.canonical({ + "fold_law": result["fold_law"], + "commits": [dict(c, delta_digest=model.digest(result["deltas"][c["sha"]])) + for c in result["commits"]]}) + "\n" + meta = {"generator": GENERATOR, "adapter": result["adapter"], "head": result["head"], + "config_digest": model.digest(config.fingerprint(cfg)), + "graph_digest": result["fold_law"]["head_digest"], + "title": (cfg["project"] or "Code") + " code graph", "fold_law": result["fold_law"]} + files["00 Index.md"] = vault_pages.index(meta, graph, names) + lowered = {} + for rel in files: # macOS volumes are case-insensitive by default + if rel.lower() in lowered: + raise RuntimeError("two notes collide on a case-insensitive disk: " + rel) + lowered[rel.lower()] = rel + return files, meta, result + + +def main(argv: list = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--repo", default=".", help="path inside the git repo (default: .)") + parser.add_argument("--rev", default="HEAD", help="revision to fold up to (default: HEAD)") + parser.add_argument("--config", default=os.path.join(HERE, "codegraph.config.json")) + parser.add_argument("--out", help="output folder (default: /)") + parser.add_argument("--json-only", action="store_true", + help="print the graph digest and fold law; write nothing") + args = parser.parse_args(argv) + repo = _repo_root(args.repo) + cfg = config.load(args.config) + files, meta, result = generate(repo, args.rev, cfg) + law = result["fold_law"] + print("head", meta["head"][:12], "· nodes", len(result["graph"]["nodes"]), + "· edges", len(result["graph"]["edges"]), "· commits", law["commits_checked"]) + print("fold law: per-commit", str(law["commits_ok"]) + "/" + str(law["commits_checked"]), + "· mainline fold == head:", law["mainline_fold_equals_head"]) + print("graph digest", meta["graph_digest"]) + ok = law["commits_ok"] == law["commits_checked"] and law["mainline_fold_equals_head"] + if args.json_only: + return 0 if ok else 1 + out = args.out or os.path.join(repo, cfg["output_dir"]) + counts = writer.write_tree(out, files, {k: v for k, v in meta.items() if k != "fold_law"}) + print("vault", out, "· files", len(files), "· written", counts["written"], + "· unchanged", counts["unchanged"], "· archived", counts["archived"]) + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/codegraph/tests/test_codegraph.py b/tools/codegraph/tests/test_codegraph.py new file mode 100644 index 0000000..ef03f43 --- /dev/null +++ b/tools/codegraph/tests/test_codegraph.py @@ -0,0 +1,191 @@ +"""Unit and end-to-end tests for codegraph. Standard library only. + +Run from the repo root: + python3 -m unittest discover -s tools/codegraph/tests -v +""" +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.dirname(HERE)) + +from cgcore import model, resolve, writer # noqa: E402 +from cgcore.adapters import swiftpm # noqa: E402 +from cgcore.adapters.swift_facts import extract # noqa: E402 +from cgcore.adapters.swift_lexer import tokenize # noqa: E402 + +SCRIPT = os.path.join(os.path.dirname(HERE), "codegraph.py") + + +class LexerTests(unittest.TestCase): + def test_comments_are_dropped_including_nested_blocks(self): + toks = tokenize("a /* x /* y */ z */ b // c\nd") + self.assertEqual([t[1] for t in toks], ["a", "b", "d"]) + + def test_interpolation_code_is_tokenised(self): + toks = tokenize('let s = "x\\(compute(a: 1))y"') + texts = [t[1] for t in toks] + self.assertIn("compute", texts) + self.assertIn("str_open", [t[0] for t in toks]) + + def test_raw_and_multiline_strings_hide_their_content(self): + toks = tokenize('let a = #"func fake() { }"#\nlet b = """\nfunc no()\n"""\nc') + self.assertNotIn("fake", [t[1] for t in toks]) + self.assertNotIn("no", [t[1] for t in toks]) + self.assertEqual(toks[-1][1:], ("c", 5)) + + def test_numbers_keep_exponents_and_ranges_split(self): + self.assertEqual([t[1] for t in tokenize("1e-5 0..<3")], ["1e-5", "0", ".", ".", "<", "3"]) + + +class FactsTests(unittest.TestCase): + SRC = """ +import Foundation +public struct Prior: Codable, Sendable { + public var alpha: Double + public init(alpha: Double, beta: Double = 1) { self.alpha = alpha } + public static func uniform() -> Prior { Prior(alpha: 1) } + class func notAType() {} +} +protocol Store { func load(id: String) -> Int } +extension Prior { mutating func widen(by amount: Double) { helper(amount) } } +func helper(_ x: Double) { let h = "k".hashValue; _ = try! Data() } +""" + + def setUp(self): + self.facts = extract(self.SRC, ("hashValue", "try!")) + self.keys = [d["key"] for d in self.facts["decls"]] + + def test_declarations_and_selectors(self): + for key in ("type:Prior", "func:Prior.init(alpha:beta:)", "func:Prior.uniform()", + "func:Prior.notAType()", "type:Store", "func:Store.load(id:)", + "func:Prior.widen(by:)", "func:helper(_:)"): + self.assertIn(key, self.keys) + + def test_class_func_is_a_modifier_not_a_type(self): + self.assertNotIn("type:func", self.keys) + + def test_protocol_requirement_has_no_body(self): + decl = next(d for d in self.facts["decls"] if d["key"] == "func:Store.load(id:)") + self.assertTrue(decl["requirement"]) + + def test_inheritance_defaults_and_probes(self): + prior = next(d for d in self.facts["decls"] if d["key"] == "type:Prior") + self.assertEqual(prior["inherits"], ["Codable", "Sendable"]) + init = next(d for d in self.facts["decls"] if d["key"] == "func:Prior.init(alpha:beta:)") + self.assertEqual([p["default"] for p in init["params"]], [False, True]) + probes = sorted(u["name"] for u in self.facts["uses"] if u["kind"] == "api") + self.assertEqual(probes, ["hashValue", "try!"]) + + def test_call_owner_is_enclosing_function(self): + call = next(u for u in self.facts["uses"] if u["kind"] == "call" and u["name"] == "helper") + self.assertEqual(call["owner"], "func:Prior.widen(by:)") + + +class ResolveTests(unittest.TestCase): + def test_default_and_trailing_closure_compatibility(self): + params = [{"label": "a", "default": False, "closure": False}, + {"label": "b", "default": True, "closure": False}, + {"label": "done", "default": False, "closure": True}] + self.assertTrue(resolve.compatible(params, ["a", "done"], False)) + self.assertTrue(resolve.compatible(params, ["a"], True)) + self.assertFalse(resolve.compatible(params, ["a"], False)) + self.assertFalse(resolve.compatible(params, ["b", "a"], False)) + + +class ModelTests(unittest.TestCase): + def test_delta_apply_roundtrip_and_moved_classification(self): + old = {"nodes": {"a": {"kind": "x", "loc": {"line": 1}}, "b": {"kind": "y"}}, + "edges": {model.edge_key("a", "calls", "b"): {"count": 1, "resolution": "exact"}, + model.edge_key("a", "uses", "a"): {"count": 1, "resolution": "exact"}}} + new = {"nodes": {"a": {"kind": "x", "loc": {"line": 9}}, "c": {"kind": "z"}}, + "edges": {model.edge_key("a", "calls", "c"): {"count": 2, "resolution": "exact"}, + model.edge_key("a", "uses", "a"): {"count": 5, "resolution": "unique"}}} + change = model.delta(old, new) + self.assertEqual(model.canonical(model.apply(old, change)), model.canonical(new)) + self.assertEqual(change["nodes_moved"], ["a"]) + self.assertEqual(model.semantic_touched(change), ["b", "c"]) + + +class ManifestTests(unittest.TestCase): + def test_package_dependencies_and_lockfile(self): + man = swiftpm.parse_manifest( + 'let p = Package(name: "P", dependencies: [.package(url: "https://github.com/a/b.git",' + ' from: "1.2.0")], targets: [.target(name: "T", dependencies: [.product(name: "B",' + ' package: "b")])])') + self.assertEqual(man["packages"][0]["identity"], "b") + self.assertEqual(man["targets"][0]["deps"][0]["package"], "b") + pins = swiftpm.parse_resolved('{"pins":[{"identity":"b","location":"x",' + '"state":{"version":"1.2.3","revision":"abc"}}],"version":2}') + self.assertEqual(pins[0]["version"], "1.2.3") + + +def _git(repo, *args): + env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid", + GIT_AUTHOR_DATE="2026-01-01T00:00:00Z", GIT_COMMITTER_DATE="2026-01-01T00:00:00Z") + subprocess.run(["git", "-C", repo, *args], check=True, capture_output=True, env=env) + + +class EndToEndTests(unittest.TestCase): + """Build a three-commit repo with a merge, fold it, check the law, and + check that rerunning is a no-op while a new HEAD archives old output.""" + + def _commit(self, repo, rel, text, msg): + path = os.path.join(repo, rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as handle: + handle.write(text) + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "-m", msg) + + def _run(self, repo, out): + cfg = os.path.join(repo, "cfg.json") + with open(cfg, "w", encoding="utf-8") as handle: + handle.write('{"project": "demo", "manifest": "swiftpm", ' + '"module_fallback": [{"prefix": "Sources/", "segment": 1}]}') + proc = subprocess.run([sys.executable, SCRIPT, "--repo", repo, "--config", cfg, "--out", out], + capture_output=True, text=True) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + return proc.stdout + + def test_fold_law_idempotence_and_archive(self): + with tempfile.TemporaryDirectory() as tmp: + repo = os.path.join(tmp, "repo") + os.makedirs(repo) + _git(repo, "init", "-q", "-b", "main") + self._commit(repo, "Sources/A/a.swift", "struct A { func f() {} }\n", "one") + _git(repo, "checkout", "-q", "-b", "side") + self._commit(repo, "Sources/A/b.swift", "struct B { func g() { A().f() } }\n", "side") + _git(repo, "checkout", "-q", "main") + self._commit(repo, "Sources/A/a.swift", "struct A { func f() {}\n func h() {} }\n", "two") + _git(repo, "merge", "-q", "--no-ff", "side", "-m", "merge") + out = os.path.join(tmp, "vault") + first = self._run(repo, out) + self.assertIn("per-commit 4/4", first) + self.assertIn("mainline fold == head: True", first) + self.assertIn("written 0 ", self._run(repo, out)) + note = os.path.join(out, "Functions", "Func - A.B.g().md") + with open(note, encoding="utf-8") as handle: + self.assertIn("[[Func - A.A.f()|A.f()]]", handle.read()) + self._commit(repo, "Sources/A/a.swift", "struct A { func f() {} }\n", "drop h") + third = self._run(repo, out) + self.assertNotIn("archived 0", third) + self.assertTrue(os.path.isdir(os.path.join(out, writer.ARCHIVE))) + self.assertTrue(os.path.exists(os.path.join(out, "Removed", "Func - A.A.h().md"))) + + def test_refuses_foreign_folder(self): + with tempfile.TemporaryDirectory() as tmp: + with open(os.path.join(tmp, "notes.md"), "w", encoding="utf-8") as handle: + handle.write("mine") + with self.assertRaises(RuntimeError): + writer.write_tree(tmp, {"x.md": "y"}, {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/codegraph/verify_determinism.py b/tools/codegraph/verify_determinism.py new file mode 100644 index 0000000..65e5bfd --- /dev/null +++ b/tools/codegraph/verify_determinism.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Prove codegraph is deterministic and idempotent on this repository. + +Checks (each prints PASS/FAIL; exit status 1 if any fail): + 1. hash-seed independence: three fresh runs under PYTHONHASHSEED=0, + 12345 and random produce byte-identical trees. + 2. idempotence: rerunning into an existing output writes nothing, + archives nothing, and leaves every byte unchanged. + 3. clean copy: the generator as committed at HEAD (exported with + `git archive`, so uncommitted edits cannot leak in) produces the same + bytes as the working copy. Skipped if HEAD has no tools/codegraph. + 4. fold law: per-commit apply(parent, delta) == projection, and the + mainline fold reproduces HEAD (read back from _data/fold.json). + +Usage, from the repo root: + python3 tools/codegraph/verify_determinism.py [--rev REV] +Writes only inside a temporary directory, which it removes at the end. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import tempfile +from typing import Dict, List + +HERE = os.path.dirname(os.path.abspath(__file__)) +SCRIPT = os.path.join(HERE, "codegraph.py") + + +def tree_digest(root: str) -> Dict[str, str]: + out = {} + for base, _dirs, files in os.walk(root): + for name in files: + path = os.path.join(base, name) + with open(path, "rb") as handle: + out[os.path.relpath(path, root)] = hashlib.sha256(handle.read()).hexdigest() + return dict(sorted(out.items())) + + +def run(script: str, repo: str, rev: str, out: str, seed: str) -> str: + env = dict(os.environ, PYTHONHASHSEED=seed) + proc = subprocess.run([sys.executable, script, "--repo", repo, "--rev", rev, "--out", out], + capture_output=True, text=True, env=env) + if proc.returncode != 0: + raise SystemExit("codegraph failed:\n" + proc.stdout + proc.stderr) + return proc.stdout + + +def diff(a: Dict[str, str], b: Dict[str, str]) -> List[str]: + keys = sorted(set(a) | set(b)) + return [k for k in keys if a.get(k) != b.get(k)] + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--rev", default="HEAD") + args = parser.parse_args() + repo = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, + text=True, check=True).stdout.strip() + failures = 0 + + def report(name: str, ok: bool, detail: str) -> None: + nonlocal failures + failures += 0 if ok else 1 + print(("PASS " if ok else "FAIL ") + name + " · " + detail) + + with tempfile.TemporaryDirectory(prefix="codegraph-verify-") as tmp: + trees = {} + for seed in ("0", "12345", "random"): + out = os.path.join(tmp, "seed-" + seed) + run(SCRIPT, repo, args.rev, out, seed) + trees[seed] = tree_digest(out) + bad = diff(trees["0"], trees["12345"]) + diff(trees["0"], trees["random"]) + report("hash-seed independence", not bad, + str(len(trees["0"])) + " files identical across 3 seeds" if not bad + else "differs: " + ", ".join(bad[:5])) + + first = os.path.join(tmp, "seed-0") + stdout = run(SCRIPT, repo, args.rev, first, "0") + after = tree_digest(first) + quiet = "written 0 " in stdout and "archived 0" in stdout + report("idempotence", quiet and after == trees["0"], + stdout.strip().splitlines()[-1]) + + clean = os.path.join(tmp, "clean") + os.makedirs(clean) + listed = subprocess.run(["git", "-C", repo, "ls-tree", "-r", "--name-only", "HEAD", + "tools/codegraph/codegraph.py"], capture_output=True, text=True) + if not listed.stdout.strip(): + print("SKIP clean copy · HEAD has no committed tools/codegraph yet") + else: + archive = subprocess.run(["git", "-C", repo, "archive", "HEAD", "tools/codegraph"], + capture_output=True, check=True).stdout + subprocess.run(["tar", "-x", "-C", clean], input=archive, check=True) + out = os.path.join(tmp, "from-clean") + run(os.path.join(clean, "tools", "codegraph", "codegraph.py"), repo, args.rev, out, "0") + bad = diff(trees["0"], tree_digest(out)) + report("clean copy of committed generator", not bad, + "identical" if not bad else "differs: " + ", ".join(bad[:5]) + + " (commit your generator changes, or this is a real leak)") + + with open(os.path.join(first, "_data", "fold.json"), encoding="utf-8") as handle: + law = json.load(handle)["fold_law"] + ok = law["commits_ok"] == law["commits_checked"] and law["mainline_fold_equals_head"] + report("fold law", ok, str(law["commits_ok"]) + "/" + str(law["commits_checked"]) + + " commits · mainline fold of " + str(law["mainline_length"]) + " deltas == HEAD") + print("OK" if failures == 0 else str(failures) + " check(s) failed") + return 0 if failures == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main())