Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
4 changes: 4 additions & 0 deletions docs/journal/DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
83 changes: 83 additions & 0 deletions docs/review/codegraph-review_v1.0.0_2026-11-27.md
Original file line number Diff line number Diff line change
@@ -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.
133 changes: 133 additions & 0 deletions tools/codegraph/README.md
Original file line number Diff line number Diff line change
@@ -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 <rev>` folds up to any commit or tag; `--out <dir>` writes
elsewhere; `--json-only` prints the graph digest and fold-law result and
writes nothing; `--config <file>` 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 <sha12>.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/<previous-head>-<manifest-digest>/` 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.
Empty file.
26 changes: 26 additions & 0 deletions tools/codegraph/cgcore/adapters/__init__.py
Original file line number Diff line number Diff line change
@@ -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),
}
Loading
Loading