You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tinkerpop.apache.org by sp...@apache.org on 2026/08/10 18:20:17 UTC
(tinkerpop) 01/03: Backport tinker-review to 3.7-dev
This is an automated email from the ASF dual-hosted git repository.
spmallette pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
commit e1ca7ea3e41404913a301c8c7ce9cef1959652f0
Author: Stephen Mallette <st...@amazon.com>
AuthorDate: Mon Aug 10 13:50:12 2026 -0400
Backport tinker-review to 3.7-dev
Makes the PR review skill reachable from a 3.7-dev checkout. Playbook routing
now matches both gremlin-js/ and gremlin-javascript/ so any copy routes
correctly whichever branch's pull request it reviews.
Assisted-by: Claude Code:claude-opus-5
---
.gitignore | 1 +
.skills/tinker-review/.gitignore | 2 +
.skills/tinker-review/DESIGN.md | 119 +++
.skills/tinker-review/SKILL.md | 297 ++++++
.skills/tinker-review/package-lock.json | 322 +++++++
.skills/tinker-review/package.json | 21 +
.skills/tinker-review/playbooks/bug-fix.md | 47 +
.skills/tinker-review/playbooks/driver-server.md | 72 ++
.skills/tinker-review/playbooks/general.md | 86 ++
.skills/tinker-review/playbooks/glv.md | 51 +
.skills/tinker-review/playbooks/grammar.md | 44 +
.skills/tinker-review/playbooks/new-step.md | 55 ++
.skills/tinker-review/playbooks/removal.md | 59 ++
.skills/tinker-review/references/enrichment-cli.md | 183 ++++
.../tinker-review/references/functional-testing.md | 96 ++
.skills/tinker-review/references/interfaces.md | 393 ++++++++
.skills/tinker-review/references/schema.md | 184 ++++
.../tinker-review/scripts/discovery/discussions.js | 349 +++++++
.skills/tinker-review/scripts/enrichment/api.js | 496 ++++++++++
.skills/tinker-review/scripts/enrichment/cli.js | 240 +++++
.../scripts/extraction/tree-sitter.js | 1006 ++++++++++++++++++++
.skills/tinker-review/scripts/functional/cli.js | 92 ++
.skills/tinker-review/scripts/functional/setup.js | 218 +++++
.../tinker-review/scripts/graph/change-levels.js | 177 ++++
.skills/tinker-review/scripts/graph/confidence.js | 85 ++
.skills/tinker-review/scripts/graph/externals.js | 87 ++
.../scripts/graph/populate-discussions.js | 305 ++++++
.skills/tinker-review/scripts/graph/populate.js | 389 ++++++++
.skills/tinker-review/scripts/graph/references.js | 85 ++
.../tinker-review/scripts/infrastructure/docker.js | 95 ++
.../tinker-review/scripts/infrastructure/net.js | 78 ++
.../tinker-review/scripts/patterns/architecture.js | 177 ++++
.../tinker-review/scripts/patterns/blast-radius.js | 180 ++++
.../tinker-review/scripts/patterns/centrality.js | 146 +++
.../scripts/patterns/classify-externals.js | 83 ++
.../scripts/patterns/cluster-analysis.js | 86 ++
.../scripts/patterns/community-detection.js | 411 ++++++++
.../tinker-review/scripts/patterns/completeness.js | 101 ++
.../scripts/patterns/confidence-audit.js | 154 +++
.../scripts/patterns/coverage-gaps.js | 87 ++
.skills/tinker-review/scripts/patterns/orphans.js | 89 ++
.../tinker-review/scripts/patterns/removal-refs.js | 106 +++
.skills/tinker-review/scripts/renderer/render.js | 612 ++++++++++++
.../tinker-review/scripts/renderer/template.html | 74 ++
.skills/tinker-review/scripts/review.js | 565 +++++++++++
.skills/tinker-review/test/cli-docs.test.js | 119 +++
.../tinker-review/test/community-detection.test.js | 148 +++
.skills/tinker-review/test/discovery.test.js | 97 ++
.skills/tinker-review/test/extraction.test.js | 173 ++++
.skills/tinker-review/test/fingerprint.test.js | 136 +++
.../tinker-review/test/playbook-sections.test.js | 101 ++
bin/agent-setup.sh | 3 +-
.../dev/developer/development-environment.asciidoc | 7 +
53 files changed, 9388 insertions(+), 1 deletion(-)
diff --git a/.gitignore b/.gitignore
index d3b966f9a2..aeef7709f9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -55,3 +55,4 @@ CLAUDE.md
.codex/
.github/skills/
gremlin-python/src/main/python/build/
+.skills/tinker-review/node_modules/
diff --git a/.skills/tinker-review/.gitignore b/.skills/tinker-review/.gitignore
new file mode 100644
index 0000000000..b1bd373ae5
--- /dev/null
+++ b/.skills/tinker-review/.gitignore
@@ -0,0 +1,2 @@
+pr-review-*.html
+pr-review-*.json
diff --git a/.skills/tinker-review/DESIGN.md b/.skills/tinker-review/DESIGN.md
new file mode 100644
index 0000000000..130a3c655c
--- /dev/null
+++ b/.skills/tinker-review/DESIGN.md
@@ -0,0 +1,119 @@
+# tinker-review — Design
+
+How the skill is built and how to change it. What a review *does* and the
+guidance it applies live in `SKILL.md`, the playbooks, and `references/`. This
+document is only the machinery and its extension points.
+
+## How it works
+
+The pipeline is two phases, split by what is mechanical and what needs judgment.
+
+**Phase 1 — deterministic** (`scripts/review.js`) builds the graph and writes
+`evidence.json`: fetch PR → worktree → start Gremlin Server → tree-sitter
+extract → populate → discover discussions → run the structural checks. It exits
+cleanly (a `PHASE1_COMPLETE` sentinel) so a caller can detect completion; the
+Gremlin Server container stays up.
+
+**Phase 2 — agent-driven** does everything that needs judgment: enrich the graph
+via the enrichment CLI, an optional functional test, then the report. It ends by
+tearing down the container and worktree. The functional test itself splits along
+the same mechanical/judgment line: `functional/setup.js` builds the PR and starts
+a server from its artifacts (mechanical), while a blind subagent designs and runs
+the test battery per the playbooks' Verify sections (judgment).
+
+Data flows one direction through three artifacts:
+
+```
+source → [Phase 1] → evidence.json → [agent adds narrative] → report.json → [renderer] → HTML
+```
+
+The knowledge graph is a live **Gremlin Server (TinkerGraph)** — the skill
+dogfoods TinkerPop. Phase 1 talks to it directly; Phase 2 opens a fresh
+connection per enrichment CLI call, because the process that populated the graph
+has already exited.
+
+### Module map
+
+| Path | Role |
+|------|------|
+| `scripts/review.js` | Phase 1 orchestrator — `setup` / `phase1` / `teardown` |
+| `scripts/extraction/tree-sitter.js` | source → structural extraction |
+| `scripts/graph/*.js` | populate the graph; `confidence.js` / `externals.js` / `references.js` hold the data-model vocabularies and shared edge helpers |
+| `scripts/patterns/*.js` | one structural check per file; each defines its own result `@typedef` |
+| `scripts/enrichment/{api,cli}.js` | Phase 2 read/write commands over the live graph |
+| `scripts/functional/{setup,cli}.js` | Phase 2 functional test — build the PR, launch a server from its artifacts (mechanical half of step 4) |
+| `scripts/infrastructure/{docker,net}.js` | Phase 1 stock-image server (`docker.js`); shared port/readiness helpers (`net.js`) |
+| `scripts/renderer/{render.js,template.html}` | `report.json` → HTML |
+| `playbooks/*.md` | domain review guidance — prompt scaffolds, not code |
+| `references/{schema,interfaces}.md` | the graph schema and the evidence composite |
+
+## Constraints that bound a change
+
+- **One source of truth per fact.** Each check's result shape is a `@typedef` in
+ the pattern file that produces it; `references/interfaces.md` holds only the
+ composite `Evidence` / `ReportPackage` and points at those typedefs. The graph
+ schema lives once in `references/schema.md`. Never re-declare a shape in a
+ second place.
+- **Type docs carry meaning.** A `@typedef` field gets a prose line saying what
+ it means and how to weigh it, not just its type — that is what the Interpret
+ sections and the reviewer consume.
+- **Plain JS + JSDoc, no build step.** The skill runs under `node` directly.
+ Don't add TypeScript, a bundler, or a compile step.
+- **Edges obey the data model.** Every edge carries a `confidence`
+ (`EXTRACTED | INFERRED | AMBIGUOUS`); an edge whose endpoint may fall outside
+ the changed set is created find-or-create against a marker vertex so it can't
+ silently vanish. A new edge must follow both.
+- **Mechanical vs judgment decides where code goes.** Anything reproducible is a
+ Phase-1 module; anything needing judgment is a Phase-2 command the agent drives
+ from a playbook. "Reproducible" means the signal is strong enough to act on
+ without judgment — not merely that a script *could* run. Finding references to
+ removed code is mechanical (grep a known symbol), so it is a Phase-1 pass
+ (`removal-refs.js`); `addReference` stays as the manual escape hatch for the
+ non-code cases the pass can't see. Mapping a method to a Gremlin step is *not*
+ mechanical — step names collide with ordinary method names, so it needs the
+ judgment the GLV playbook describes, and stays a Phase-2 command.
+
+## How to change it
+
+- **Add a structural check** — new `scripts/patterns/<name>.js` exporting the
+ function and its result `@typedef`; call it in `review.js` Phase 1 and add it
+ to `evidence.checks`; add the type to `Evidence` in `interfaces.md`; reference
+ it from the relevant playbook's Interpret.
+- **Add an enrichment command** — a function in `scripts/enrichment/api.js` (or a
+ pattern module), wired into `cli.js` (COMMANDS + help + switch), documented in
+ `SKILL.md`. Edge-creating commands take a `confidence`, default `INFERRED`.
+- **Add a playbook** — six sections. **Context** is prose stating when the
+ playbook applies (an applicability gate, read while choosing playbooks). The
+ four working sections — **Enrich**, **Inspect**, **Verify**, **Interpret** —
+ are bullet checklists, one item per action so the agent runs them dependably
+ rather than parsing prose. They split by data flow:
+ - **Enrich** — each bullet names a registered enrichment command and mutates
+ the graph only (name at least one command, or state that none applies).
+ - **Inspect** — each bullet names a source-read concern to record as a
+ *candidate finding* for Interpret. List only the concerns; the "read the
+ changed source, record each as a candidate finding" instruction is stated
+ once in `SKILL.md` and must not be repeated per playbook. An Inspect section
+ may open with a single `Context:` line naming its lens (e.g. `Context:
+ API-design concerns mined from TinkerPop reviewer patterns`) when that framing
+ guides the read. If a playbook has no source-read work (its judgment is
+ structural), say so in one line rather than inventing items.
+ - **Verify** — each bullet shapes the optional functional test's battery for
+ this class of change: which GLVs/layers to exercise and what adversarial cases
+ matter. The gate (whether to test at all) and the shared battery framework
+ live once in `general.md`'s Verify and must not be repeated per playbook; a
+ domain playbook adds only its specialization. If a change class rarely has a
+ black-box surface, say when to skip in one line rather than inventing items.
+ The mechanical build+start is `functional/setup.js`, not a playbook concern.
+ - **Interpret** — each bullet weighs an `evidence.json` field or an Inspect
+ candidate into `findings` or `openQuestions`. List only the weighing bullets;
+ the "weigh the evidence.json signals and Inspect candidates into `findings` /
+ `openQuestions`" instruction is stated once in `SKILL.md` and must not be
+ repeated per playbook. `findings` is an ordered list: rank it most-severe-first
+ and grade each entry blocking / high / low. Prominence is expressed by that
+ ordering, not a per-finding field.
+
+ **Escape** sets stop/escalate gates. `test/playbook-sections.test.js` enforces
+ that every playbook carries the six sections in order and that Enrich names a
+ command. Add an orient rule in `SKILL.md`.
+- **Add an edge or vertex type** — document it in `references/schema.md`; tag new
+ edges with `confidence`; use find-or-create for cross-boundary endpoints.
diff --git a/.skills/tinker-review/SKILL.md b/.skills/tinker-review/SKILL.md
new file mode 100644
index 0000000000..b165f05fc4
--- /dev/null
+++ b/.skills/tinker-review/SKILL.md
@@ -0,0 +1,297 @@
+---
+name: tinker-review
+description: >
+ Graph-based PR review for Apache TinkerPop. Builds a knowledge graph from
+ PR source code, enriches it with semantic relationships guided by domain
+ playbooks, runs structural analysis, and produces an HTML evidence package.
+ Use when asked to review a TinkerPop PR by number.
+license: Apache-2.0
+compatibility: Requires Docker, Node.js 20+, git. Network access for fetching PR refs.
+metadata:
+ version: "0.1.0"
+ project: Apache TinkerPop
+---
+
+# Graph Review Skill
+
+## Prerequisites
+
+- Docker running (for Gremlin Server)
+- `upstream` remote pointing to `git@github.com:apache/tinkerpop.git` (fetch only)
+- Node.js 20+ with dependencies installed in `.skills/tinker-review/`
+
+
+## References (load on demand)
+
+- Read [references/schema.md](references/schema.md) when you need to understand what vertices, edges, or properties exist in the knowledge graph (typically during enrichment or when writing raw Gremlin)
+- Read [references/interfaces.md](references/interfaces.md) when you need the exact function signatures or data type definitions for a module
+- Read [references/enrichment-cli.md](references/enrichment-cli.md) when you need to know what an enrichment CLI command *does* and when to reach for it (the command names below are terse; this is where their meaning lives)
+- Read [references/functional-testing.md](references/functional-testing.md) when you run the optional functional test (step 4) — what `functional/cli.js` does, how the built server is configured, and how to drive it from the subagent
+
+## Execution Sequence
+
+When invoked with `/review <pr-number>`:
+
+The run has two phases (see [DESIGN.md](DESIGN.md)). **Phase 1** (step 1) is
+deterministic and builds the graph. **Phase 2** (steps 3–5) is agent-driven —
+enrichment, an optional functional test, then the report. Step 2 chooses the
+playbooks that guide Phase 2; step 6 tears down.
+
+### 1. Setup + Phase 1 (deterministic)
+
+Run the review script. This handles everything mechanical:
+
+```bash
+npm install --prefix .skills/tinker-review # only needed once
+node .skills/tinker-review/scripts/review.js <pr-number> <repo-path>
+```
+
+This performs: fetch PR → create worktree → start Gremlin Server → extract
+structure via Tree-sitter → populate knowledge graph → discover discussions
+(JIRA, dev list, proposals, PR comments) → run pattern checks (completeness,
+coverage gaps, centrality, blast radius, cluster analysis) → write evidence JSON.
+
+**Output:** `/tmp/pr-review-<pr>/evidence.json`
+**Server:** remains running (the agent needs it for enrichment)
+**Worktree:** available at `/tmp/pr-review-<pr>/src/`
+
+If re-running, the script cleans up stale worktrees/branches automatically.
+
+### 2. Choose the playbooks
+
+Playbooks carry the domain judgment for Phase 2. `general.md` always applies;
+select the domain playbooks in two passes:
+
+1. **Orient** — from the changed file paths, gather the candidates:
+ - `gremlin-dart/`, `gremlin-go/`, `gremlin-python/`, `gremlin-dotnet/`, `gremlin-js/`, `gremlin-javascript/` → `playbooks/glv.md`
+ - `gremlin-core/` with new step patterns → `playbooks/new-step.md`
+ - `gremlin-driver/`, `gremlin-server/`, `gremlin-util/` → `playbooks/driver-server.md`
+ - Small change set with linked issue → `playbooks/bug-fix.md`
+ - `gremlin-language/` or `*.g4` → `playbooks/grammar.md`
+ - Deletion-heavy change set (removes a feature/module/dependency; `listDeleted` returns entries) → `playbooks/removal.md`
+2. **Confirm** — read each candidate's **Context** and keep only the ones that
+ truly fit this PR. A path can match a playbook that doesn't apply: a
+ `gremlin-core/` change that adds no step, or a `gremlin-driver/` fix that's
+ really a bug-fix.
+
+Then apply each kept playbook's sections at the point each is used:
+
+The three working sections (**Enrich**, **Inspect**, **Interpret**) are bullet
+checklists — one item per action.
+
+| Section | Used when | What you do |
+|---------|-----------|-------------|
+| **Context** | choosing playbooks (above) | Confirm the path-matched playbook fits this PR; set aside the ones that don't. |
+| **Enrich** | improving the graph (step 3) | Run each command bullet to add or re-grade semantic edges. Graph mutation only. |
+| **Inspect** | reading the changed source (step 3) | Check each bullet against the source; record what you find as a *candidate finding* for Interpret. |
+| **Verify** | functional testing (step 4) | Apply the gate, then shape the blind subagent's test battery. `general.md` holds the shared gate/framework; domains specialize it. |
+| **Interpret** | writing the report (step 5) | Weigh the named `evidence.json` fields together with the Inspect and Verify candidates into `findings` / `openQuestions`. |
+| **Escape** | any time | Honor its stop/escalate gates; halt or flag when one holds. |
+
+The working sections split by data flow: **Enrich** writes to the graph,
+**Inspect** reads the changed source into candidate findings, **Verify** exercises
+the built feature as a user would, and **Interpret** reads the computed
+`evidence.json` checks and weighs the Inspect and Verify candidates into the
+report. `findings` is an ordered list — Interpret ranks it most-severe-first,
+grading each entry blocking / high / low.
+
+Phase 1 already computes every structural check — completeness, coverageGaps,
+centrality, blastRadius, clusters, confidence, externals, orphans — into
+`evidence.json`. Playbooks' Interpret sections reference those results **by field
+name** (e.g. `checks.blastRadius`); they do not re-run checks. The shape and
+meaning of every field is documented in
+[references/interfaces.md](references/interfaces.md) (`Evidence`), which points
+to the per-check `@typedef`s in `scripts/patterns/*.js`.
+
+### 3. Phase 2 — Enrichment
+
+The Gremlin Server is still running. Use `scripts/enrichment/cli.js` to
+read from and write to the knowledge graph. Do NOT write your own connection
+code or import gremlin-js directly — the CLI handles connections for you. For
+what each command does and when to use it, see
+[references/enrichment-cli.md](references/enrichment-cli.md).
+
+Every command takes `--workDir /tmp/pr-review-<pr>`, connects using that dir's
+`session.json`, prints its JSON result to stdout, and disconnects:
+```bash
+node scripts/enrichment/cli.js <command> --workDir /tmp/pr-review-<pr> [--options...]
+```
+
+The command catalog — what each does and when to reach for it — lives in
+[references/enrichment-cli.md](references/enrichment-cli.md); run
+`node scripts/enrichment/cli.js --help` for exact flags. In brief: **read
+commands** (`listFunctions`, `listDeleted`, `listExternalRefs`, …) orient you and
+feed the playbooks; **write commands** (`mapStep`, `addReference`,
+`setEdgeConfidence`, …) add the semantic edges. Edges you create default to
+`INFERRED` — pass `--confidence AMBIGUOUS` for a flagged guess or `EXTRACTED`
+when the source states it directly.
+
+The confidence loop is the backbone of enrichment: `auditConfidence` →
+`listInferred` (your verification worklist) → read the source → `setEdgeConfidence`
+to promote or downgrade, then re-run `auditConfidence` and reflect anything still
+`AMBIGUOUS` in `openQuestions`. It is defined once in `general.md`'s **Enrich**
+section and inherited by every playbook.
+
+**Read source files:** worktree at `/tmp/pr-review-<pr>/src/`
+
+Follow the playbook's Enrich section (graph writes) and its Inspect section (read
+the changed source, recording concerns as candidate findings for Interpret to
+weigh at report time). Check Escape conditions.
+
+### 4. Phase 2 — Functional Testing (optional, subagent)
+
+**IMPORTANT: Functional testing is NOT running the project's unit tests.**
+DO NOT use `mvn test`. DO NOT run TreeTest, DO NOT run any existing test class.
+The project's own tests are the author's responsibility — running them tells
+the reviewer nothing new.
+
+Functional testing means: test the feature AS A USER WOULD. Connect to a
+Gremlin Server built from the PR and submit traversals. Try to use the feature
+based only on what the documentation says. Try to break it with adversarial
+inputs.
+
+**Gate — decide whether to run it.** Consult the applicable playbooks' **Verify**
+sections. `general.md`'s Verify holds the shared gate: skip functional testing
+when the change has no user-facing runtime surface (tests-only, docs-only, a pure
+internal refactor, build/CI plumbing) and either omit `functionalTest` or record
+the skip reason. Otherwise continue.
+
+**Build the PR and start the server (mechanical).** The `functional/cli.js`
+command builds the full reactor, locates the assembly, and launches a Gremlin
+Server from the built artifacts on a fresh port (distinct from the knowledge
+graph server). It reads `pr`/`repoPath` from `session.json` and writes the
+handle to `functional.json` so teardown can find it:
+
+```bash
+node .skills/tinker-review/scripts/functional/cli.js start --workDir /tmp/pr-review-<pr>
+```
+
+This prints `{ url, port, pid, assemblyDir, logFile, ... }`. The build is slow
+(full reactor); on failure, the error names the server log to inspect. See
+[references/functional-testing.md](references/functional-testing.md) for what the
+command does and how to drive it.
+
+**Test from the outside.** Spawn a subagent that receives ONLY:
+- PR title/description (what the change claims to do)
+- Relevant documentation sections
+- Relevant Gherkin test features (for expected behavior reference)
+- The Gremlin Server URL (the `url` from the command above)
+
+The subagent does NOT get: source code, the knowledge graph, code review findings,
+or access to the analysis worktree. Brief it as a **minimally experienced
+TinkerPop user** who has only the docs — it tests blind, and its stumbles are
+signal about how usable the feature is.
+
+**The subagent tests by submitting Gremlin traversals** via the Gremlin Console
+or a GLV client. It devises its own test plan from the docs, executes traversals,
+and attempts adversarial edge cases. The **shape** of the battery comes from the
+applicable playbooks' Verify sections — which languages/layers to exercise and
+what adversarial cases matter for this class of change.
+
+**Layer decision** (the Verify sections say which applies to this PR):
+- **Layer 1 (embedded):** Gremlin Console with TinkerGraph. For core logic changes.
+- **Layer 2 (per-GLV wire):** Connect from each GLV to the server. For
+ serialization/type changes. Skip if purely computational.
+
+**Label every scenario in the code (required).** Instruct the subagent to keep
+the test code as the single source of truth for *what* was tested, and to label
+each scenario with a comment carrying a stable id and a one-line intent, e.g.:
+
+```groovy
+// Scenario A1: group().by(T.id) — validates the id key survives when its reduction is productive
+g.V().group().by(id).by(out().count())
+```
+
+The subagent returns:
+- **Complete, unabbreviated test code**, every scenario labeled as above — this is
+ `appendixFunctional.testCode` (raw text; the renderer wraps it — do NOT add
+ `<pre>`/`<code>`). No `...`, no "(abbrev)"; if the battery is large, that is
+ what the appendix is for.
+- **Themes, not a scenario dump** — group the scenarios into a handful of themes,
+ each citing the labels it spans (e.g. "Barrier family (A4–A12): …").
+- Results, adversarial findings, and observations keyed to those labels.
+
+Fold these into the `functionalTest` / `appendixFunctional` report fields (step 5)
+and weigh them in Interpret. The count and granularity of `functionalTest.results`
+rows must match the themes, not inflate to imply more tests than the appendix
+actually lists.
+
+### 5. Phase 2 — Produce Report
+
+Write the narrative JSON, then render.
+
+**Step A:** Read `/tmp/pr-review-<pr>/evidence.json`. Add narrative fields to
+produce a complete evidence-with-narrative JSON file. Write it to
+`/tmp/pr-review-<pr>/report.json`. The narrative fields you must provide:
+
+- `summary` — HTML paragraph describing the PR
+- `clusters.assessment` — HTML prose about what the connected-component clusters mean
+- `communityAssessment` — HTML, **light by default**: usually one or two sentences on
+ whether the change is coherent/localized and what its dominant theme is. Expand *only*
+ when the community **structure itself** shows something non-obvious that no other section
+ captures — e.g. disconnected communities hinting at bundled unrelated changes, a community
+ bridging subsystems that shouldn't be coupled, a changed file stranded in a community about
+ an unrelated concern, or diffuse modularity on a supposedly focused change. Absent such a
+ structural surprise, keep it short and instead use the communities as *supporting evidence*
+ cited in other sections (Guided Walk, Findings, Change Coherence). Do NOT restate the graph
+ literally (vertices/edges/labels/counts), do NOT re-narrate what Removal References,
+ Coverage, or Blast Radius already report, and do NOT pad. The renderer draws the diagram
+ and the appendix lists membership; you supply only the judgment.
+- `guidedWalk` — array of `{ title, badge, badgeText, body }` objects
+- `findings` — array of `{ title, snippet, body }` objects, ordered most-severe-first (Interpret grades each blocking / high / low)
+- `openQuestions` — array of `{ title, body, meta }` objects
+- `functionalTest` — `{ plan, results: [{name, pass, output}], observations }` (if testing was done).
+ `plan` and `observations` are HTML and surface **themes and insights** — what
+ families of behavior were exercised and what was learned — not a per-scenario
+ list. `results` rows are **theme-level**: each `name` names a theme and the
+ scenario labels it spans (e.g. `"Barrier family (A4–A12)"`), so the PASS/FAIL
+ grid stays scannable and every row is backed by labeled code in the appendix.
+ Do not enumerate every scenario here and do not let the row count imply more
+ tests than the appendix lists.
+- `appendixFunctional` — `{ environment, testCode, fullOutput }` (if testing was done).
+ `environment` is HTML. `testCode` and `fullOutput` are **raw text** — the
+ renderer wraps them in `<pre><code>`, so do NOT add `<pre>`/`<code>`/`<p>`
+ yourself. `testCode` is the **complete, unabbreviated** labeled battery from the
+ subagent (see step 4); it is the source of truth the Functional Test section
+ summarizes by label.
+
+All `body` fields (and `functionalTest.plan`/`observations`, `appendixFunctional.environment`)
+are HTML — use `<code>`, `<strong>`, `<ul>`, `<p>` as needed. The raw-text fields
+noted above are the exception. The renderer handles all layout, CSS, and structure.
+
+**Step B:** Render the report:
+
+```bash
+node .skills/tinker-review/scripts/renderer/render.js /tmp/pr-review-<pr>/report.json /tmp/pr-review-<pr>/report.html
+```
+
+The renderer produces a complete HTML report with consistent structure.
+Every section is always present — if you didn't provide a field, it shows
+"Section not provided" in red. DO NOT write HTML yourself.
+
+### 6. Teardown
+
+```bash
+node -e "import { teardown } from './scripts/review.js'; await teardown('/tmp/pr-review-<pr>');"
+```
+
+Or simply stop the Docker container and clean up manually:
+```bash
+docker stop $(cat /tmp/pr-review-<pr>/session.json | python3 -c "import json,sys; print(json.load(sys.stdin)['containerId'])")
+rm -rf /tmp/pr-review-<pr>
+git worktree prune
+git branch -D pr-review/<pr>
+```
+
+This stops the knowledge graph server, removes worktrees, deletes the branch.
+If a functional test ran (step 4), teardown also stops that server (via its
+`pid` in `functional.json`) and removes the `build/` worktree. Call this ONLY
+after all phases are complete.
+
+## Important Notes
+
+- NEVER push to the `upstream` remote. It is fetch-only.
+- ALL output goes to `/tmp/pr-review-<pr>/` — never write inside the git repo.
+- The Gremlin Server stays alive until teardown. Don't kill it early.
+- If re-running, the script auto-cleans stale state.
+- The agent populates JSON narrative fields; the renderer produces HTML. No agent writes raw HTML.
diff --git a/.skills/tinker-review/package-lock.json b/.skills/tinker-review/package-lock.json
new file mode 100644
index 0000000000..87b38cb952
--- /dev/null
+++ b/.skills/tinker-review/package-lock.json
@@ -0,0 +1,322 @@
+{
+ "name": "@tinkerpop/graph-review",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@tinkerpop/graph-review",
+ "version": "0.1.0",
+ "dependencies": {
+ "graphology": "^0.26.0",
+ "graphology-communities-louvain": "^2.0.2",
+ "gremlin": "^3.8.1",
+ "tree-sitter-wasms": "^0.1.13",
+ "web-tree-sitter": "^0.24.7"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/abort-controller": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
+ "license": "MIT",
+ "dependencies": {
+ "event-target-shim": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=6.5"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/buffer": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.2.1"
+ }
+ },
+ "node_modules/event-target-shim": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/eventemitter3": {
+ "version": "5.0.4",
+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
+ "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
+ "license": "MIT"
+ },
+ "node_modules/events": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.x"
+ }
+ },
+ "node_modules/graphology": {
+ "version": "0.26.0",
+ "resolved": "https://registry.npmjs.org/graphology/-/graphology-0.26.0.tgz",
+ "integrity": "sha512-8SSImzgUUYC89Z042s+0r/vMibY7GX/Emz4LDO5e7jYXhuoWfHISPFJYjpRLUSJGq6UQ6xlenvX1p/hJdfXuXg==",
+ "license": "MIT",
+ "dependencies": {
+ "events": "^3.3.0"
+ },
+ "peerDependencies": {
+ "graphology-types": ">=0.24.0"
+ }
+ },
+ "node_modules/graphology-communities-louvain": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/graphology-communities-louvain/-/graphology-communities-louvain-2.0.2.tgz",
+ "integrity": "sha512-zt+2hHVPYxjEquyecxWXoUoIuN/UvYzsvI7boDdMNz0rRvpESQ7+e+Ejv6wK7AThycbZXuQ6DkG8NPMCq6XwoA==",
+ "license": "MIT",
+ "dependencies": {
+ "graphology-indices": "^0.17.0",
+ "graphology-utils": "^2.4.4",
+ "mnemonist": "^0.39.0",
+ "pandemonium": "^2.4.1"
+ },
+ "peerDependencies": {
+ "graphology-types": ">=0.19.0"
+ }
+ },
+ "node_modules/graphology-indices": {
+ "version": "0.17.0",
+ "resolved": "https://registry.npmjs.org/graphology-indices/-/graphology-indices-0.17.0.tgz",
+ "integrity": "sha512-A7RXuKQvdqSWOpn7ZVQo4S33O0vCfPBnUSf7FwE0zNCasqwZVUaCXePuWo5HBpWw68KJcwObZDHpFk6HKH6MYQ==",
+ "license": "MIT",
+ "dependencies": {
+ "graphology-utils": "^2.4.2",
+ "mnemonist": "^0.39.0"
+ },
+ "peerDependencies": {
+ "graphology-types": ">=0.20.0"
+ }
+ },
+ "node_modules/graphology-types": {
+ "version": "0.24.8",
+ "resolved": "https://registry.npmjs.org/graphology-types/-/graphology-types-0.24.8.tgz",
+ "integrity": "sha512-hDRKYXa8TsoZHjgEaysSRyPdT6uB78Ci8WnjgbStlQysz7xR52PInxNsmnB7IBOM1BhikxkNyCVEFgmPKnpx3Q==",
+ "license": "MIT",
+ "peer": true
+ },
+ "node_modules/graphology-utils": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/graphology-utils/-/graphology-utils-2.5.2.tgz",
+ "integrity": "sha512-ckHg8MXrXJkOARk56ZaSCM1g1Wihe2d6iTmz1enGOz4W/l831MBCKSayeFQfowgF8wd+PQ4rlch/56Vs/VZLDQ==",
+ "license": "MIT",
+ "peerDependencies": {
+ "graphology-types": ">=0.23.0"
+ }
+ },
+ "node_modules/gremlin": {
+ "version": "3.8.1",
+ "resolved": "https://registry.npmjs.org/gremlin/-/gremlin-3.8.1.tgz",
+ "integrity": "sha512-ft0R47ugLkyQys7v3qbi0kUkeSe8VY2HUj4YqwKuxC2OYxQJtFMuSNGCyXpAND4vA34PJLJOMo0vTCEqwinVTg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "buffer": "^6.0.3",
+ "eventemitter3": "^5.0.1",
+ "readable-stream": "^4.5.2",
+ "uuid": "^9.0.1",
+ "ws": "^8.16.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/mnemonist": {
+ "version": "0.39.8",
+ "resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.39.8.tgz",
+ "integrity": "sha512-vyWo2K3fjrUw8YeeZ1zF0fy6Mu59RHokURlld8ymdUPjMlD9EC9ov1/YPqTgqRvUN9nTr3Gqfz29LYAmu0PHPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "obliterator": "^2.0.1"
+ }
+ },
+ "node_modules/obliterator": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz",
+ "integrity": "sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==",
+ "license": "MIT"
+ },
+ "node_modules/pandemonium": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/pandemonium/-/pandemonium-2.4.1.tgz",
+ "integrity": "sha512-wRqjisUyiUfXowgm7MFH2rwJzKIr20rca5FsHXCMNm1W5YPP1hCtrZfgmQ62kP7OZ7Xt+cR858aB28lu5NX55g==",
+ "license": "MIT",
+ "dependencies": {
+ "mnemonist": "^0.39.2"
+ }
+ },
+ "node_modules/process": {
+ "version": "0.11.10",
+ "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
+ "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
+ "node_modules/readable-stream": {
+ "version": "4.7.0",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
+ "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
+ "license": "MIT",
+ "dependencies": {
+ "abort-controller": "^3.0.0",
+ "buffer": "^6.0.3",
+ "events": "^3.3.0",
+ "process": "^0.11.10",
+ "string_decoder": "^1.3.0"
+ },
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "node_modules/tree-sitter-wasms": {
+ "version": "0.1.13",
+ "resolved": "https://registry.npmjs.org/tree-sitter-wasms/-/tree-sitter-wasms-0.1.13.tgz",
+ "integrity": "sha512-wT+cR6DwaIz80/vho3AvSF0N4txuNx/5bcRKoXouOfClpxh/qqrF4URNLQXbbt8MaAxeksZcZd1j8gcGjc+QxQ==",
+ "license": "Unlicense",
+ "dependencies": {
+ "tree-sitter-wasms": "^0.1.11"
+ }
+ },
+ "node_modules/uuid": {
+ "version": "9.0.1",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
+ "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
+ "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
+ "funding": [
+ "https://github.com/sponsors/broofa",
+ "https://github.com/sponsors/ctavan"
+ ],
+ "license": "MIT",
+ "bin": {
+ "uuid": "dist/bin/uuid"
+ }
+ },
+ "node_modules/web-tree-sitter": {
+ "version": "0.24.7",
+ "resolved": "https://registry.npmjs.org/web-tree-sitter/-/web-tree-sitter-0.24.7.tgz",
+ "integrity": "sha512-CdC/TqVFbXqR+C51v38hv6wOPatKEUGxa39scAeFSm98wIhZxAYonhRQPSMmfZ2w7JDI0zQDdzdmgtNk06/krQ==",
+ "license": "MIT"
+ },
+ "node_modules/ws": {
+ "version": "8.21.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/.skills/tinker-review/package.json b/.skills/tinker-review/package.json
new file mode 100644
index 0000000000..3eece6b32d
--- /dev/null
+++ b/.skills/tinker-review/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@tinkerpop/graph-review",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "description": "Graph-based PR review skill for Apache TinkerPop",
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "scripts": {
+ "test": "node --test \"test/**/*.test.js\"",
+ "review": "node review.js"
+ },
+ "dependencies": {
+ "graphology": "^0.26.0",
+ "graphology-communities-louvain": "^2.0.2",
+ "gremlin": "^3.8.1",
+ "tree-sitter-wasms": "^0.1.13",
+ "web-tree-sitter": "^0.24.7"
+ }
+}
diff --git a/.skills/tinker-review/playbooks/bug-fix.md b/.skills/tinker-review/playbooks/bug-fix.md
new file mode 100644
index 0000000000..8c95e63eb4
--- /dev/null
+++ b/.skills/tinker-review/playbooks/bug-fix.md
@@ -0,0 +1,47 @@
+# Playbook: Bug Fix
+
+## Context
+A fix for a reported issue. Should be minimal, targeted, include a
+regression test, and not introduce new API surface. The fix should
+address the root cause, not just the symptom.
+
+## Enrich
+- `linkDiscussion` — record the referenced JIRA (TINKERPOP-XXXX) or dev-list
+ thread (`--source jira|devlist`). Creates the `addresses` edge Interpret checks.
+
+## Inspect
+- Fix location — which functions changed to address the bug; does the regression
+ test reproduce the reported symptom?
+- Scope creep — changes to functions unrelated to the reported bug.
+- Error messages — meaningful to users, not just developers? (a common TinkerPop
+ reviewer concern)
+- Log levels — error stays error for unexpected failures; not downgraded to info
+ without justification.
+- Resource cleanup on error paths — if the bug involves connection/channel
+ handling, no leak when the fix triggers.
+
+## Verify
+- Reproduce the reported symptom first, then confirm the fix resolves it: derive
+ the failing scenario from the linked issue and run it against the built server.
+- Pick the layer by where the bug lives — an embedded Console/TinkerGraph
+ exercise for core logic; the affected GLV's native client for a driver/wire bug.
+- Adversarial: nearby inputs the fix might have missed (the boundary just past
+ the reported case, the empty/null variant) — a fix that only patches the exact
+ reported value is a finding.
+- If the bug has no black-box surface (e.g. an internal-only refactor of the
+ fix), state that; rely on the author's regression test instead.
+
+## Interpret
+- `checks.blastRadius` — high on a bug fix is a warning: verify the fix doesn't
+ subtly change behavior for existing callers.
+- `checks.centrality` — if a hot function changed, say explicitly that every
+ caller needs a behavioral-change check.
+- `checks.coverageGaps` / `checks.orphans` — a fix with no new or modified test
+ is blocking; it can't be shown to prevent regression.
+- `checks.completeness` on `addresses` — no linked issue means correctness can't
+ be assessed.
+- Out-of-scope changes — flag as "necessary for fix?", not "wrong."
+
+## Escape
+- if no linked issue — "Cannot assess whether fix is correct without knowing the bug"
+- if public API signature changed — "Bug fix changes public API — needs broader discussion before merge"
diff --git a/.skills/tinker-review/playbooks/driver-server.md b/.skills/tinker-review/playbooks/driver-server.md
new file mode 100644
index 0000000000..55fba6045c
--- /dev/null
+++ b/.skills/tinker-review/playbooks/driver-server.md
@@ -0,0 +1,72 @@
+# Playbook: Driver / Server / Serialization
+
+## Context
+Changes to gremlin-driver, gremlin-server, or gremlin-util. These modules
+handle connections, protocol, serialization, and request lifecycle. Changes
+here affect all users and all GLV drivers. Correctness under concurrency
+and backwards compatibility are critical concerns.
+
+## Enrich
+- `linkDoc` — if the change adds or removes a serializer type code, record the
+ documentation that covers that format (`--entity File --name <doc>`).
+- `linkDiscussion` — record a referenced proposal or JIRA.
+
+## Inspect
+Context: layered — identify the layer (connection lifecycle / protocol /
+serialization / server init / auth) first, then check the matching group.
+
+**Connection management:**
+- HttpClient/WebSocket instances shared or created per-connection? (shared is
+ correct for pooling; per-connection defeats the pool)
+- Could pool size = 1 cause deadlock?
+- Connection-tracking data structures: `CopyOnWriteArraySet` has write overhead;
+ `ConcurrentLinkedQueue` is better for frequent insert/remove.
+- Settings kept as a cohesive object, or extracted into individual fields that
+ drift from the source of truth? (prefer the object)
+
+**Serialization:**
+- De-bulking happens lazily at traversal iteration, not eagerly on response
+ arrival (eager puts all objects in memory at once).
+- Removed type IDs leave a comment documenting what they were ("122 was Bytecode
+ until removed in 4.x").
+- Error-response fallback: GraphBinary errors may return as JSON when the server
+ can't serialize the error in binary.
+- Numeric types: longs need an `L` suffix in GremlinLang text format.
+
+**API migration:**
+- New code uses GremlinLang, not Bytecode (removed in 4.x).
+- New code uses `with_()`, not `withRemote` (deprecated).
+- Server configuration uses gremlin-lang expressions, not Groovy scripts.
+- No commented-out old code left behind — remove it cleanly.
+
+## Verify
+- Focus on the wire: connect a GLV client to the built server and round-trip the
+ serializers or protocol paths the PR touches. Confirm the bytes survive both
+ directions (GraphBinary and GraphSON if both are affected).
+- If a type code was added or removed, confirm the new code path works and the
+ removed one fails cleanly rather than mis-deserializing.
+- Adversarial: a payload larger than a batch (exercise result streaming), a
+ server-side error (confirm it comes back as a usable error, per the GraphBinary
+ → JSON error fallback), and a malformed request.
+- Pure connection-lifecycle or concurrency changes have no single-query surface —
+ say so; the confidence here comes from the author's concurrency tests, not this
+ black-box pass.
+
+## Interpret
+- `checks.blastRadius` — inherently high (shared infrastructure); don't flag the
+ reach itself, name the specific callers most affected.
+- `checks.centrality` with `listExternalRefs` — separate project coupling
+ (`origin: project`/`unresolved`) from library noise (`origin: library`);
+ centrality already drops library calls, so a function ranking high is
+ genuinely central.
+- `checks.coverageGaps` / `checks.orphans` in connection-lifecycle or
+ concurrency code — blocking; these are the hardest bugs to reproduce and the
+ most impactful in production.
+- Serialization type-code change with no `documents` edge from Enrich — high;
+ flag the missing IO/upgrade doc.
+- "Good enough for now" patterns (strategy handling, migration scaffolding) —
+ acceptable if clearly marked temporary; flag if they look like permanent debt.
+
+## Escape
+- if connection pool logic modified without concurrency tests — "Pool changes need concurrency testing — flag for manual review of deadlock/race conditions"
+- if serialization type codes added/removed without IO doc update — "Serialization changes need IO documentation updates"
diff --git a/.skills/tinker-review/playbooks/general.md b/.skills/tinker-review/playbooks/general.md
new file mode 100644
index 0000000000..ce4f197ea5
--- /dev/null
+++ b/.skills/tinker-review/playbooks/general.md
@@ -0,0 +1,86 @@
+# Playbook: General (applies to all PRs)
+
+## Context
+These are concerns TinkerPop reviewers consistently raise regardless of
+the type of change. This playbook always applies in addition to any
+domain-specific playbook.
+
+## Enrich
+The confidence pass runs on every review; it lives here and every playbook
+inherits it. Run in order:
+- `auditConfidence` — read the edge-confidence distribution and the `AMBIGUOUS` list.
+- `listInferred` — pull the verification worklist (`--relation implements_step`
+ first, then any `calls` edges your findings lean on); read each against the
+ worktree source.
+- `setEdgeConfidence` — re-grade what you verified: promote a confirmed edge to
+ `EXTRACTED`, downgrade a wrong name-resolution to `AMBIGUOUS`.
+- `auditConfidence` again — anything still `AMBIGUOUS` goes to `openQuestions`,
+ never asserted as fact.
+
+## Inspect
+**Style:**
+- Wildcard imports in Java (`import foo.*`)
+- Formatting/indentation changes mixed with functional changes
+- Unused variables or imports
+- Non-final variables that should be final
+
+**Deprecated API:**
+- `withRemote` (deprecated in 4.0, use `with_()`)
+- Groovy script strings where gremlin-lang should be used
+- Any `@Deprecated` API used in new code
+
+**Tests:**
+- Tests that drop/clear all data instead of isolating with specialized labels
+- Assertions that don't clearly explain what they verify
+- Error/exception paths that aren't tested
+- Test helpers without guard clauses (missing else/throw for invalid input)
+
+**Resource safety:**
+- Connections, channels, or streams opened without a clear cleanup path
+- Log levels: error for unexpected failures, info for expected lifecycle events
+- Concurrency-implicated data structures (`CopyOnWriteArraySet`, synchronized
+ collections) introduced without profiling justification
+
+## Verify
+Context: this is the shared gate and battery-design framework for the optional
+functional test (SKILL.md step 4). Domain playbooks add their own Verify bullets;
+they do not repeat this framework.
+
+**Gate — does functional testing run at all?** Run it only when the change has a
+user-facing runtime surface. Skip (state why in `functionalTest`, or omit the
+field) when the change is tests-only, docs-only, a pure internal refactor with no
+observable behavior change, or build/CI plumbing.
+
+**Design the battery to match the change** — exercise what changed, then try the
+mistakes a real user would make:
+- New or changed **step / API surface** → submit native queries against the built
+ server in every affected GLV. A step that spans grammar + core + all GLVs is
+ tested per language.
+- **Semantics changed, API stable** → a small embedded exercise (Layer 1: Gremlin
+ Console / TinkerGraph, or a short Java snippet) that drives the feature is
+ enough; per-GLV wire tests add nothing.
+- **Serialization / type / protocol** → round-trip the affected types over the
+ wire from at least one GLV (Layer 2).
+- Always include adversarial cases: wrong argument types, empty/null inputs,
+ boundary values, and the feature used against the grain of the docs.
+
+The blind subagent designs and runs this battery from the docs alone — see
+SKILL.md step 4 for how it is briefed and isolated.
+
+## Interpret
+- `checks.coverageGaps` / `checks.orphans` — missing tests on changed code; a
+ test-quality concern, weighed alongside the Inspect smells.
+- `functionalTest` observations (if testing ran) — a failing or surprising result
+ is a finding graded by severity; a documented-but-unusable feature is blocking.
+ Adversarial gaps the subagent found (unclear errors, silent wrong answers) are
+ high. If testing was skipped, the gate reason is not itself a finding.
+- Safety concerns (resource leaks, concurrency risks, missing error handling)
+ and test-quality issues — high; make these the focus.
+- Style nits and unused variables — low; note them, don't let them dominate.
+- Formatting mixed with functional changes — high; it makes the PR harder to
+ review and should ideally be separate commits.
+- Deprecated API in new code — high. Deprecated API already present in modified
+ code — low, unless the PR is specifically a migration away from it.
+
+## Escape
+None — this playbook always completes. No conditions warrant stopping.
diff --git a/.skills/tinker-review/playbooks/glv.md b/.skills/tinker-review/playbooks/glv.md
new file mode 100644
index 0000000000..03f9ee5cec
--- /dev/null
+++ b/.skills/tinker-review/playbooks/glv.md
@@ -0,0 +1,51 @@
+# Playbook: GLV Implementation
+
+## Context
+A new or updated Gremlin Language Variant. Implements the full traversal
+API in a host language. Must pass the Gremlin test suite. Should be
+idiomatic for the target language, not a mechanical translation. The
+reference GLV for structural comparison is typically gremlin-go (most
+recent accepted GLV).
+
+## Enrich
+- `getCanonicalSteps` — pull the authoritative step vocabulary from `Gremlin.g4`;
+ validate every step name against it before mapping.
+- `mapStep` — map each real traversal-step method to its canonical step. A step
+ method is on a traversal class, returns the traversal (fluent), is named to
+ match the canonical step (cased per language), and is public DSL — not internal
+ plumbing. Never map boilerplate (`toString`, `equals`, `close`) or helpers
+ (`getLocalChildren`, `setTraversal`). Pass `--confidence AMBIGUOUS` when you
+ can't tell whether a method is a real step (it surfaces in the review list
+ instead of being asserted).
+- `listInferred --relation implements_step` then `setEdgeConfidence` — promote a
+ mapping to `EXTRACTED` once confirmed against the reference GLV or grammar.
+- `linkDiscussion` — record a referenced JIRA or dev-list thread.
+
+## Inspect
+- Connection acquisition and release points — trace resource lifecycle through
+ error paths; the common GLV bug is leaking a connection when a traversal fails
+ mid-execution.
+
+## Verify
+- Test from the GLV under review by connecting its native client to the built
+ server — this is the language whose wire behavior the PR changes.
+- Round-trip the value types the GLV serializes (numbers, lists, maps, vertices,
+ the language's date/UUID types) and confirm they survive the trip unchanged.
+- Adversarial: submit a traversal that errors server-side and confirm the GLV
+ surfaces a usable error rather than hanging or leaking the connection.
+- If the change is idiomatic-only (no wire/serialization impact), an embedded
+ Java exercise is not required — state that in `functionalTest`.
+
+## Interpret
+- `checks.completeness` — distinguish genuinely missing steps from steps present
+ under a language-specific name (Python `addV` vs Go `AddV` — same step).
+- Divergence from the reference GLV — judge whether the host language justifies
+ it. Goroutines where Python uses asyncio is fine; a different serialization
+ format is a concern.
+- `checks.coverageGaps` — expected for driver internals (connection management,
+ serialization); traversal-step methods should have test coverage.
+
+## Escape
+- if not test_suite_passes(glv): stop("Cannot proceed — GLV must pass test suite first")
+- if not exists(reference_glv(language_family(glv))): escalate("Need human familiar with language")
+- if step_mapping_confidence < 0.7: escalate("Cannot reliably map methods to steps — need human verification of API surface")
diff --git a/.skills/tinker-review/playbooks/grammar.md b/.skills/tinker-review/playbooks/grammar.md
new file mode 100644
index 0000000000..03b476ca43
--- /dev/null
+++ b/.skills/tinker-review/playbooks/grammar.md
@@ -0,0 +1,44 @@
+# Playbook: Grammar Change
+
+## Context
+A change to Gremlin.g4 or related language infrastructure. Grammar changes
+are inherently high-risk — they affect all parsers, all GLVs, and all
+downstream tooling. Backwards compatibility is critical.
+
+## Enrich
+- `addGrammarRule` — record each grammar rule the PR adds.
+- `linkRule` — wire each rule to the step it defines (`has_rule`), so
+ completeness can check every rule reaches a step.
+- `linkDiscussion --source proposal` — record the proposal or dev-list thread
+ (grammar changes need prior community consensus).
+
+## Inspect
+- New vs modified syntax — a modified rule that changes the parse of existing
+ syntax is the high-risk case: could valid Gremlin become invalid?
+- ANTLR targets — Java, Python, and Go parsers all updated?
+- Step wiring — is there a step implementation for each new rule?
+- New keywords — TinkerPop has special handling for keywords as map keys (#3091);
+ a new keyword can break queries that use it as an identifier.
+
+## Verify
+- Submit a query using the new syntax against the built server and confirm it
+ parses and returns the intended result.
+- Backwards-compat is the priority: run a handful of pre-existing query forms and
+ confirm the grammar change did not break them — especially if a rule was
+ modified rather than added.
+- If a new keyword was introduced, submit a query using that word as an
+ identifier / map key (the #3091 hazard) and confirm it still parses.
+- Test across the ANTLR targets the PR updates (Java, Python, Go) — the same
+ query should parse the same in each.
+
+## Interpret
+- `checks.blastRadius` / `checks.centrality` — grammar touches everything; don't
+ flag the reach, focus on backwards compatibility.
+- `checks.completeness` on `has_rule` — shows whether the recorded rules are
+ wired to a step.
+- New-syntax rule (existing queries still parse) — low. Modified rule (changes
+ the parse of existing syntax) — high; needs explicit backwards-compat analysis.
+
+## Escape
+- if no proposal or dev-list discussion found — "Grammar changes require community consensus — flagging for discussion"
+- if existing grammar rules are modified (not just added) — "Potential backwards-incompatible change — needs explicit compatibility analysis"
diff --git a/.skills/tinker-review/playbooks/new-step.md b/.skills/tinker-review/playbooks/new-step.md
new file mode 100644
index 0000000000..fecbb64876
--- /dev/null
+++ b/.skills/tinker-review/playbooks/new-step.md
@@ -0,0 +1,55 @@
+# Playbook: New Step
+
+## Context
+A new traversal step added to Gremlin. Must propagate across grammar,
+core implementation, all active GLVs, documentation, and test suite.
+The proposal (dev list or JIRA) is the source of truth for intended
+semantics.
+
+## Enrich
+- `getCanonicalSteps` — validate the step name before mapping.
+- `mapStep` — link the core implementation to its canonical name. Map the
+ `GraphTraversal`/`GraphTraversalSource` method users call, not the internal
+ methods on the Step class (e.g., `TreeStep`).
+- `mapCoverage` — record each test that exercises the step (`covers`), so
+ completeness/coverageGaps can confirm the new step is tested.
+- `linkDoc` — record the documentation that references the step.
+- `linkDiscussion` — record the proposal or JIRA that defines the step's semantics.
+
+## Inspect
+- Default interface implementations — justified? If something implements an
+ interface, should it have a proper implementation?
+- Naming — consistent with sibling steps?
+- Class design — wrapping and extending the same parent is suspicious.
+- Type restrictions — not too narrow (provider implementations vary).
+- Cross-GLV signatures — parameter count should match; types differ by language.
+ Judge semantic equivalence, not syntactic identity.
+
+## Verify
+- Test the step in every active GLV, not just Java — a new step must work
+ end-to-end per language. Submit native queries against the built server from
+ each GLV client.
+- Drive the step's documented signature: required args, optional args, and the
+ no-arg form if the docs describe one.
+- Adversarial: wrong argument types, the step in an illegal position (start vs
+ mid-traversal), and composition with a common neighbor step (`by`, `as`).
+- Cross-check observed behavior against the step's Gherkin feature — the results
+ should agree with what the feature asserts.
+
+## Interpret
+- `checks.completeness` over `implements_step` / `has_rule` / `covers` /
+ `documents` / `proposed_in` — what's missing. Missing from some GLVs is
+ acceptable if a follow-up issue tracks it (check the PR or linked JIRA for
+ phased rollout). Missing docs (no `documents`) — blocking; an undocumented
+ step is undiscoverable. Missing tests (`checks.coverageGaps`, no `covers`) —
+ blocking; a new step must be exercised.
+- `checks.blastRadius` — usually low (nothing calls a new step yet); high means
+ it hooks into shared infrastructure — verify those integration points.
+- `checks.centrality` — high in step infrastructure (TraversalStrategy, Step
+ implementations) is expected; note it, don't treat it as a problem. Ignore
+ out-degree that's just library calls (`checks.externals`, origin=library).
+
+## Escape
+- if missing: proposal — "Cannot assess intent — need human to confirm expected semantics"
+- if touches: graph_computer — "GraphComputer interactions require deep architectural knowledge — flagging for senior review"
+- if step has no core_impl in PR — "Step concept referenced but no core implementation found — is this a GLV-only addition?"
diff --git a/.skills/tinker-review/playbooks/removal.md b/.skills/tinker-review/playbooks/removal.md
new file mode 100644
index 0000000000..73ba2a6296
--- /dev/null
+++ b/.skills/tinker-review/playbooks/removal.md
@@ -0,0 +1,59 @@
+# Playbook: Removal / Deprecation
+
+## Context
+The PR deletes code — a feature, a module, a dependency, or a deprecated API.
+The change set is deletion-heavy (many removed files, net-negative diff). The
+central review question is not "is the new code correct?" but **"does anything
+left behind still depend on what was removed?"** A removal that leaves dangling
+references, stale config, or orphaned docs is worse than no removal — it breaks
+the build or misleads users.
+
+Load this playbook when `listDeleted` returns entries (or the PR is dominated by
+deletions). It runs in addition to `general.md` and any module playbook.
+
+## Enrich
+- `listDeleted` — the removed files and the symbol each likely defined
+ (`Krb5Authenticator.java` -> `Krb5Authenticator`). The entry point; its results
+ are the valid `--toPath` targets for `addReference`.
+- Read `checks.removalRefs` (and `checks.removalRefs.externalCallers`) — Phase 1
+ already grepped the surviving worktree for each removed code symbol and wrote a
+ `references` edge per hit. Once you've classified each (see Interpret), confirm
+ or downgrade it with `setEdgeConfidence`.
+- `addReference` — record the non-code hits the automatic pass can't see, grepped
+ off `listDeleted`: config/resources (`*.yaml`, `*.conf`, `*.properties`), build
+ files (`pom.xml`, `*.gradle`), docs (`docs/src/**/*.asciidoc`, `CHANGELOG.asciidoc`),
+ Docker/CI setup (`*.sh`, compose files).
+
+## Inspect
+None specific to removal — the review judgment here is structural (classifying
+the `references` edges recorded in Enrich) and is handled in Interpret rather
+than by reading changed source.
+
+## Verify
+- The build worktree compiling at all is the first signal — a removal that left a
+ dangling reference fails `mvn install`, and `buildAndStart` reports it.
+- Confirm the removed surface is actually gone: submit a query using the removed
+ step / feature against the built server and confirm it now errors rather than
+ silently working.
+- Confirm what remains still works: exercise a neighboring feature that shared
+ code with the removed one, to catch an over-broad deletion.
+- A removal with no user-facing runtime surface (internal class, build-only
+ dependency) needs no query test — say so; the reference analysis carries it.
+
+## Interpret
+The `references` edges in `checks.removalRefs` (plus any you added) and
+`checks.coverageGaps` on surviving code are the primary outputs.
+Classify each surviving reference and state where it lives:
+- Active code / build / config / live docs referencing a removed symbol —
+ blocking; the build breaks or the feature is half-removed.
+- Historical release notes (e.g. `docs/src/upgrade/release-3.x.asciidoc`)
+ mentioning the removed symbol — expected and correct; note as verified-benign.
+- No current upgrade/CHANGELOG line announcing the removal — a finding; users
+ need to know the feature is gone.
+
+## Escape
+- if a removed symbol is still referenced by active source or build files —
+ "Removal is incomplete: <symbol> still referenced in <file>; the build or
+ feature is broken until this is resolved."
+- if the removal drops a dependency or public API without an upgrade-doc entry —
+ "User-facing removal needs an upgrade/CHANGELOG note."
diff --git a/.skills/tinker-review/references/enrichment-cli.md b/.skills/tinker-review/references/enrichment-cli.md
new file mode 100644
index 0000000000..e42247c603
--- /dev/null
+++ b/.skills/tinker-review/references/enrichment-cli.md
@@ -0,0 +1,183 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with this
+work for additional information regarding copyright ownership. The ASF
+licenses this file to You under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+License for the specific language governing permissions and limitations under
+the License.
+-->
+
+# Enrichment CLI — Command Reference
+
+This is the human-readable reference for `scripts/enrichment/cli.js`: what each
+command *does* and *when you'd reach for it* while writing a playbook or running
+an enrichment pass. The command names are terse and not always self-descriptive
+— this file is where the meaning lives.
+
+**Three sources, three jobs (keep them in sync):**
+
+| Source | Job |
+|--------|-----|
+| `scripts/enrichment/cli.js` — the `COMMANDS` registry | Single source of truth for **what commands exist** and whether each is `agent`- or `internal`-facing. |
+| `scripts/enrichment/api.js` — JSDoc on each function | Canonical **semantics** (params, return shape, edge confidence), co-located with the implementation. |
+| **this file** | The **narrative** — plain-language "what/when/gotchas" for a playbook author. |
+
+`test/cli-docs.test.js` fails the build if these drift: every registry command
+must have a `##` section here and a line in `cli.js --help`; agent-facing
+commands must also appear in `SKILL.md`. Add a command → document it in all
+three or CI goes red.
+
+## Invocation
+
+```bash
+node scripts/enrichment/cli.js <command> --workDir /tmp/pr-review-<pr> [--key value ...]
+```
+
+Every command connects using `/tmp/pr-review-<pr>/session.json`, prints a JSON
+result to stdout, and disconnects. Edges you create default to `INFERRED`
+confidence unless the command says otherwise; pass `--confidence AMBIGUOUS` for
+a flagged guess or `EXTRACTED` when the source states the fact directly.
+
+---
+
+## Agent-facing — read
+
+These answer "what's in the graph?" and never mutate it. Use them to orient
+before enriching and to pull the verification worklist.
+
+### listFunctions
+Lists functions the graph knows about. **Your first orientation read.**
+`--changeLevel STRUCTURAL` narrows to signature-level changes (also `BEHAVIORAL`,
+`FORMATTING`, `NONE`); `--changed true` is a back-compat alias for "anything but
+NONE" (and `--changed false` for NONE only); `--visibility public` narrows to the
+API surface. Each result carries its `changeLevel`, signature, and line span so
+you can open it in the worktree. Reach for it at the top of almost any playbook.
+
+### listTypes
+Lists types (classes, interfaces, enums), optionally filtered by `--kind` or
+`--file`. Use it to see the types a PR defines or touches before drilling into
+their functions.
+
+### getCallsFrom
+The direct callees of one function (its outgoing `calls` edges). **Keyed by
+`--function` AND `--file`** because names repeat across the codebase. Reach for
+it to trace what a changed function depends on — e.g. to confirm it no longer
+calls a symbol the PR removed.
+
+### getCanonicalSteps
+The canonical Gremlin step vocabulary, parsed straight from `Gremlin.g4`. This
+is the authoritative list of step names you map GLV methods onto with `mapStep`
+— validate against it so you never invent a step that doesn't exist. Reads the
+grammar file, not the graph. Central to the GLV playbook.
+
+### auditConfidence
+The edge-confidence distribution plus the list of `AMBIGUOUS` edges. **Run it
+twice**: once at the start of the confidence pass, and again after you enrich, so
+the audit reflects edges you added. Anything still `AMBIGUOUS` afterward belongs
+in the report's `openQuestions`, not asserted as fact.
+
+### listInferred
+Your **verification worklist**: the name-resolved / agent-mapped edges worth a
+source check, optionally narrowed with `--relation` (start with
+`implements_step`, then `calls`). After reading the source, promote or downgrade
+each with `setEdgeConfidence`. This is how INFERRED becomes EXTRACTED.
+
+### listDeleted
+The files the PR deleted (graph stubs marked `deleted: true`), each paired with
+the symbol name it likely defined. **The entry point for the removal playbook** —
+it gives you the symbols to grep the surviving tree for, and the valid `--toPath`
+targets for `addReference`.
+
+### listExternalRefs
+Unresolved external callees — names the changed code calls that weren't defined
+in the changed set. Shows each stub's `origin` (library/project/unresolved) and,
+crucially, **flags any whose name matches a deleted symbol**: a changed file
+still calling a just-removed name is a dangling reference the graph catches on
+its own. Sorted so the dangerous ones surface first.
+
+---
+
+## Agent-facing — write
+
+These mutate the graph. New edges default to `INFERRED`; grade honestly.
+
+### addReference
+**Manual escape hatch for the removal playbook.** The Phase-1 pass grepped for
+*code-symbol* references automatically; use this to record the ones it can't see
+— config strings, doc mentions, build-file references to a removed symbol.
+`--toPath` must be a file `listDeleted` returned. Creates the same `references`
+edge the automatic pass does.
+
+### mapStep
+Records that a GLV/host-language function implements a canonical Gremlin step, as
+an `implements_step` edge (creating the Step vertex on first use). **The core
+move of the GLV playbook.** Map only real traversal-step methods — never
+language boilerplate (`toString`, `equals`, `close`) or internal helpers.
+Validate `--step` against `getCanonicalSteps` first.
+
+### setEdgeConfidence
+Re-grades an existing edge after you verify it against source. Identify the edge
+by `--relation` + `--fromName` (optionally pin `--fromFile`, narrow `--toName`).
+**The other half of the `listInferred` loop**: promote a confirmed edge to
+`EXTRACTED`, or downgrade a wrong name-resolution to `AMBIGUOUS` so it surfaces
+in the report's review list.
+
+### linkDiscussion
+Attaches an external discussion you found (JIRA, dev-list thread, proposal) as a
+Discussion vertex, linked from the PR discussion via `addresses`. Use it when
+enrichment turns up prior context the Phase-1 discovery pass missed, so the
+report can cite where the change was debated. `--source` is `jira | devlist |
+proposal`.
+
+### linkDoc
+Records that a documentation file documents a graph entity, via a `documents`
+edge from a Doc vertex to the named entity (`--entity` label + `--name`). Use it
+to connect a step or feature to its reference docs / recipe, so the report can
+flag a change whose docs weren't updated.
+
+### addGrammarRule
+Adds a `GrammarRule` vertex for a rule the PR introduces. Reach for it in the
+grammar playbook when a `*.g4` change adds a production the graph should track so
+later steps can link to it.
+
+### linkRule
+Links a step to the grammar production that defines it, as a `has_rule` edge
+(Step → GrammarRule). Closes the loop `addGrammarRule` opens — both vertices must
+exist first (`mapStep` for the Step, `addGrammarRule` for the rule). The grammar
+playbook's `checks.completeness` on `has_rule` reports which steps still lack it.
+
+### mapCoverage
+Records that a test covers a step's behavior, as a `covers` edge (Test → Step).
+Key the test by `--test` name **and** `--file` (names repeat across suites); the
+Step must already exist (`mapStep`). The `new-step` playbook treats a step with
+no `covers` as a coverage gap — this is how you record the coverage you find.
+
+### annotate
+Sets an arbitrary `--key`/`--value` property on a vertex identified by `--label`
++ `--name`. The **general-purpose escape hatch** for a fact the schema has no
+dedicated edge for. Prefer a typed command when one fits; reach for this only
+when none does.
+
+---
+
+## Internal (Phase 1)
+
+`review.js` runs these itself while building the graph. They're exposed on the
+CLI only for manual re-runs during debugging — **you do not call them during
+enrichment**, and they intentionally do not appear in `SKILL.md`.
+
+### classifyExternals
+Tags each external callee stub with `origin` = `library | project | unresolved`.
+`listExternalRefs` and the centrality check read that tag. Runs once in Phase 1.
+
+### createPrDiscussion
+Creates the root PR Discussion vertex that every other discussion links back to
+via `addresses`. Idempotent (a second call is a no-op). Runs once in Phase 1.
diff --git a/.skills/tinker-review/references/functional-testing.md b/.skills/tinker-review/references/functional-testing.md
new file mode 100644
index 0000000000..9455146193
--- /dev/null
+++ b/.skills/tinker-review/references/functional-testing.md
@@ -0,0 +1,96 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with this
+work for additional information regarding copyright ownership. The ASF
+licenses this file to You under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+License for the specific language governing permissions and limitations under
+the License.
+-->
+
+# Functional Testing — Reference
+
+The mechanics behind SKILL.md step 4. *Whether* to run a functional test and
+*what* to test are judgment calls that live in the playbooks' **Verify** sections
+(`general.md` holds the shared gate and battery framework; domain playbooks
+specialize). This file covers only the reproducible half: building the PR and
+standing up a server to test against.
+
+## Why a second server
+
+Phase 1's knowledge-graph server (`infrastructure/docker.js`) runs the **stock
+published image** — it holds the review graph, not the PR's code. Functional
+testing must exercise the PR's **own compiled artifacts**, so it builds from
+source and launches natively. The two servers run on different ports and never
+share state.
+
+## `functional/cli.js`
+
+| Command | What it does |
+|---------|--------------|
+| `start --workDir <dir> [--port <n>]` | Reads `pr`/`repoPath` from `session.json`; adds a `build/` worktree on `pr-review/<pr>`; runs `mvn clean install -DskipTests` over the full reactor; locates the `*-standalone` assembly; writes a TinkerGraph config, an init script (binding `g` and `a`), and a server yaml; launches `bin/gremlin-server.sh` on a free port; polls until ready. Prints the handle as JSON and persists it to `functional.json`. |
+| `stop --workDir <dir>` | Reads `functional.json`, kills the server JVM, and removes the `build/` worktree. Also invoked automatically by `review.js` teardown. |
+
+The handle: `{ port, url, pid, buildWorktree, assemblyDir, logFile }`. `url` is
+the HTTP endpoint (`http://localhost:<port>/gremlin`) to hand the subagent.
+
+The build is the slow step (a full reactor build, minutes). If readiness times
+out, the error names `functional-server.log` in the work dir — inspect it for the
+JVM's own startup errors.
+
+## What the built server exposes
+
+Mirrors the Phase-1 server so a reviewer's queries look the same against either:
+
+- `g` — a standard traversal source over an empty TinkerGraph
+- `a` — the same graph `withComputer()`, for OLAP steps (`connectedComponent()`, …)
+
+Serializers are the project defaults (GraphSON V4 + GraphBinary V4) over the
+`HttpChannelizer`, so any current GLV client connects normally.
+
+## Driving it from the subagent
+
+The subagent connects to `url` and submits traversals — via a GLV client or the
+Gremlin Console — exactly as a user reading the docs would. It gets the server
+URL, the PR title/description, the relevant docs, and the relevant Gherkin
+features; it does **not** get source, the graph, or the review findings. See
+SKILL.md step 4 for the full briefing contract and the Verify sections for the
+per-change battery.
+
+## What the subagent must return (report inputs)
+
+The test code is the source of truth for *what* was tested, so the subagent
+returns it **complete and unabbreviated**, with every scenario labeled in a
+comment carrying a stable id and one-line intent:
+
+```groovy
+// Scenario A1: group().by(T.id) — id key survives when its reduction is productive
+g.V().group().by(id).by(out().count())
+```
+
+Those labels are the anchor between the report's two functional sections:
+
+- `appendixFunctional.testCode` — the full labeled battery (raw text; the
+ renderer wraps it — the subagent must not pre-wrap in `<pre>`/`<code>`).
+- `functionalTest` — **themes, not a scenario dump**. `results` rows are
+ theme-level, each citing the labels it spans (e.g. "Barrier family (A4–A12)");
+ `plan`/`observations` surface what was exercised and what was learned. The row
+ count must not imply more tests than the appendix lists.
+
+The renderer defensively strips a stray wrapper from the raw-text fields, but the
+contract is raw text — relying on the guard is a slip, not a plan.
+
+## Isolation notes
+
+- The `build/` worktree is separate from the enrichment worktree (`src/`) so
+ Maven's `target/` output never pollutes the tree the agent reads.
+- Teardown removes the `build/` worktree and stops the JVM. If a run is
+ interrupted, `functional/cli.js stop` (or the next `start`, which prunes a
+ stale worktree first) cleans up.
diff --git a/.skills/tinker-review/references/interfaces.md b/.skills/tinker-review/references/interfaces.md
new file mode 100644
index 0000000000..282e06adf1
--- /dev/null
+++ b/.skills/tinker-review/references/interfaces.md
@@ -0,0 +1,393 @@
+# Graph Review Skill — Module Interfaces
+
+Module contracts for the Phase 1 vertical slice. Each module is independently
+implementable against these signatures and data shapes.
+
+Design reference: `~/graph-review.md`
+
+---
+
+## Data Types
+
+```typescript
+// === Extraction Output ===
+
+interface ExtractionResult {
+ language: string;
+ files: FileInfo[];
+ functions: FunctionInfo[];
+ types: TypeInfo[];
+ calls: CallInfo[];
+ imports: ImportInfo[];
+}
+
+// How much the PR moved a vertex, graded by diffing base against PR-head.
+// Vocabulary/helpers: scripts/graph/change-levels.js.
+type ChangeLevel = "NONE" | "FORMATTING" | "BEHAVIORAL" | "STRUCTURAL";
+
+interface FileInfo {
+ path: string; // relative to worktree root
+ language: string; // e.g., "dart", "java", "go"
+ changeLevel: ChangeLevel; // rollup of the file's members + import/export delta
+}
+
+interface FunctionInfo {
+ name: string;
+ signature: string; // full signature as string
+ visibility: "public" | "private" | "protected" | "internal";
+ filePath: string; // which file this lives in
+ linesStart: number;
+ linesEnd: number;
+ changeLevel: ChangeLevel; // graded per function (untouched helper = NONE)
+}
+
+interface TypeInfo {
+ name: string;
+ kind: "class" | "interface" | "struct" | "enum";
+ visibility: "public" | "private" | "protected" | "internal";
+ filePath: string;
+ changeLevel: ChangeLevel; // graded over the type's declaration surface
+}
+
+interface CallInfo {
+ callerName: string; // function making the call
+ callerFile: string;
+ calleeName: string; // function being called
+ line: number; // line of the call site
+}
+
+interface ImportInfo {
+ filePath: string; // file containing the import
+ importedPath: string; // what is being imported
+ importedName: string; // specific symbol if applicable, or "*"
+}
+
+// === Infrastructure ===
+
+interface ServerHandle {
+ port: number;
+ containerId: string;
+ url: string; // ws://localhost:${port}/gremlin
+}
+
+// === Graph Population ===
+
+interface PopulationSummary {
+ vertices: number; // true count, queried from the graph after population
+ edges: number; // true count, queried from the graph after population
+ breakdown: { // per-type ATTEMPTED inserts (may exceed the real totals above)
+ files: number;
+ functions: number;
+ types: number;
+ tests: number;
+ calls: number;
+ defines: number;
+ testsEdges: number;
+ externalFunctions: number; // stub Functions minted for unresolved callees
+ stubFiles: number; // stub Files minted for changed files that weren't parsed
+ };
+}
+
+// === Pattern Results ===
+//
+// Each check's result type is defined — WITH per-field meaning — as a @typedef
+// in the pattern file that produces it. Those typedefs are canonical; read them
+// when interpreting a field. Do not re-declare them here (that is what drifts).
+//
+// CompletenessResult scripts/patterns/completeness.js
+// CoverageGapResult scripts/patterns/coverage-gaps.js
+// CentralityResult scripts/patterns/centrality.js
+// BlastRadiusResult scripts/patterns/blast-radius.js
+// ClusterResult scripts/patterns/cluster-analysis.js
+// ConfidenceResult scripts/patterns/confidence-audit.js
+// ExternalsResult scripts/patterns/classify-externals.js
+// OrphanResult scripts/patterns/orphans.js
+// ArchitectureResult scripts/patterns/architecture.js
+
+// === Evidence (evidence.json — what Phase 1 writes; the fields Interpret cites) ===
+
+interface Evidence {
+ meta: {
+ pr: number;
+ title: string;
+ domains: string[]; // e.g. ["general", "glv", "driver-server"]
+ language: string;
+ changedFileCount: number;
+ timestamp: string;
+ };
+ graphStats: PopulationSummary;
+ architecture: ArchitectureResult;
+ checks: {
+ completeness: CompletenessResult[];
+ coverageGaps: CoverageGapResult;
+ centrality: CentralityResult;
+ blastRadius: BlastRadiusResult;
+ clusters: ClusterResult;
+ confidence: ConfidenceResult;
+ externals: ExternalsResult;
+ orphans: OrphanResult;
+ };
+ discussions: DiscussionsResult; // jiras[], devList[], secondary[], proposals[], prComments{}
+ changedFiles: string[];
+}
+
+// === ReportPackage (report.json — renderer input; Evidence + agent narrative) ===
+// The agent adds these fields in Phase 5; render.js consumes the whole thing.
+
+interface ReportPackage extends Evidence {
+ summary: string; // HTML
+ clusters: { assessment: string }; // narrative prose — distinct from checks.clusters
+ guidedWalk: { title; badge; badgeText; body }[];
+ findings: { title; snippet; body }[];
+ openQuestions: { title; body; meta }[];
+ functionalTest?: { plan; results: { name; pass; output }[]; observations };
+ // plan/observations: HTML, theme-level. results rows are THEMES, each `name`
+ // naming the scenario labels it spans — not one row per scenario.
+ appendixFunctional?: { environment; testCode; fullOutput };
+ // environment: HTML. testCode/fullOutput: RAW TEXT (renderer wraps in
+ // <pre><code>; do not pre-wrap). testCode is the COMPLETE labeled battery.
+}
+```
+
+---
+
+## Module Signatures
+
+### extraction/tree-sitter.js
+
+```javascript
+/**
+ * Parse source files in a directory using Tree-sitter.
+ * Returns structured extraction data for graph population.
+ *
+ * @param {string} directory - Absolute path to the PR worktree
+ * @param {string} language - Primary language to parse (e.g., "dart")
+ * @param {object} options
+ * @param {string[]} [options.changedFiles] - List of files changed in PR (relative paths)
+ * @param {Object<string,string>} [options.baseContents] - Base-version source of
+ * each changed file, keyed by path, so each member's `changeLevel` can be graded
+ * by diffing base against head. A missing entry = a file the PR added (STRUCTURAL).
+ * @returns {Promise<ExtractionResult>}
+ */
+export async function extract(directory, language, options = {}) {}
+```
+
+**Responsibilities:**
+- Load the appropriate tree-sitter grammar for the language
+- Walk the directory, parse each source file
+- Grade each file/function/type's `changeLevel` against `options.baseContents`
+ (context / hierarchy-neighborhood files, absent from `changedFiles`, grade `NONE`)
+- Return the structured `ExtractionResult`
+
+**Does NOT:**
+- Connect to Gremlin Server
+- Create graph vertices/edges
+- Understand Gremlin step semantics
+
+---
+
+### infrastructure/docker.js
+
+```javascript
+/**
+ * Start a Gremlin Server Docker container with TinkerGraph.
+ * Uses a random available port. Polls until server is ready.
+ *
+ * @param {object} options
+ * @param {string} [options.image] - Docker image (default: "tinkerpop/gremlin-server:4.0.1")
+ * @param {number} [options.timeoutMs] - Max wait for readiness (default: 30000)
+ * @returns {Promise<ServerHandle>}
+ */
+export async function startServer(options = {}) {}
+
+/**
+ * Stop and remove the Gremlin Server container.
+ *
+ * @param {ServerHandle} handle - Handle returned by startServer
+ * @returns {Promise<void>}
+ */
+export async function stopServer(handle) {}
+```
+
+**Responsibilities:**
+- Find a random unused port
+- Run `docker run` with correct config (empty graph, GraphBinary)
+- Poll the HTTP endpoint until ready
+- Return connection details
+- Clean up container on stop
+
+**Does NOT:**
+- Manage the gremlin-js client connection (that's the caller's job)
+- Know anything about the graph schema
+
+---
+
+### graph/populate.js
+
+```javascript
+/**
+ * Populate TinkerGraph with extraction data.
+ * Creates vertices and edges matching the PR knowledge graph schema.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {ExtractionResult} extraction - Output from tree-sitter module
+ * @returns {Promise<PopulationSummary>}
+ */
+export async function populate(g, extraction) {}
+```
+
+**Schema mapping:**
+
+| Extraction data | Graph vertex | Key properties |
+|---|---|---|
+| `files[]` | `File` | path, language, changeLevel |
+| `functions[]` | `Function` | name, signature, visibility, lines_start, lines_end, changeLevel |
+| `types[]` | `Type` | name, kind, visibility, changeLevel |
+
+| Extraction data | Graph edge | From → To |
+|---|---|---|
+| `calls[]` | `calls` | Function → Function (matched by name+file) |
+| `functions[].filePath` | `defines` | File → Function |
+| `types[].filePath` | `defines` | File → Type |
+| `imports[]` | `depends_on` | File → File |
+
+**Responsibilities:**
+- Create all vertices with properties
+- Create all edges (matching by name for call targets)
+- Handle cases where call targets don't resolve (function in external dependency) — skip edge, don't fail
+- Return population summary with counts
+
+**Does NOT:**
+- Create semantic edges (implements_step, tests, covers) — that's agent enrichment
+- Parse source files — that's the extraction module's job
+
+---
+
+### patterns/completeness.js
+
+```javascript
+/**
+ * Check that a vertex has all expected outgoing/incoming edge labels.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource
+ * @param {object} params
+ * @param {string} params.vertexLabel - Label of vertex to check (e.g., "Step")
+ * @param {string} [params.vertexName] - Name property to filter by
+ * @param {string[]} params.expectedEdges - Edge labels that should exist
+ * Prefix with "in:" or "out:" for direction (default: "out:")
+ * e.g., ["out:has_rule", "in:implements_step", "in:covers", "in:documents"]
+ * @returns {Promise<CompletenessResult[]>}
+ */
+export async function completeness(g, params) {}
+```
+
+---
+
+### patterns/coverage-gaps.js
+
+```javascript
+/**
+ * Find changed functions that have no incoming 'tests' edge.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource
+ * @param {object} params
+ * @param {boolean} [params.changedOnly] - Only check meaningfully-changed functions
+ * — BEHAVIORAL or STRUCTURAL (default: true)
+ * @returns {Promise<CoverageGapResult>}
+ */
+export async function coverageGaps(g, params = {}) {}
+```
+
+---
+
+### renderer/render.js
+
+```javascript
+/**
+ * Render an evidence package to a self-contained HTML page.
+ *
+ * @param {EvidencePackage} evidence - Structured evidence data
+ * @returns {string} - Complete HTML document as a string
+ */
+export function render(evidence) {}
+```
+
+**Responsibilities:**
+- Produce a single self-contained HTML string (embedded CSS, no external deps)
+- Render header with PR metadata
+- Render completeness results as a visual checklist
+- Render coverage gaps as a list with file/line links
+- Render graph population summary
+
+**Does NOT:**
+- Fetch data or run queries
+- Produce graph visualizations (Phase 4)
+- Generate the guided walk narrative (needs agent synthesis)
+
+---
+
+### review.js (orchestrator)
+
+```javascript
+/**
+ * Execute a graph-based review of a PR.
+ * This is the skill entry point.
+ *
+ * @param {object} params
+ * @param {number} params.pr - PR number
+ * @param {string} params.repoPath - Path to the git repository
+ * @param {object} [params.options]
+ * @param {string} [params.options.outputPath] - Where to write the HTML (default: ./pr-review-${pr}.html)
+ * @returns {Promise<string>} - Path to the generated HTML file
+ */
+export async function review(params) {}
+```
+
+**Orchestration steps:**
+1. `git fetch origin pull/${pr}/head:pr-review/${pr}`
+2. `git worktree add /tmp/pr-review-${pr} pr-review/${pr}`
+3. Determine changed files via `git diff --name-only ${base}...pr-review/${pr}`, and
+ their base-version source via `git show ${base}:${path}` (for `changeLevel` grading)
+4. `startServer()`
+5. Connect gremlin-js to `handle.url`
+6. `extract(worktreePath, language, { changedFiles, baseContents })`
+7. `populate(g, extraction)`
+8. `completeness(g, { ... })`
+9. `coverageGaps(g, { ... })`
+10. Assemble `EvidencePackage`
+11. `render(evidence)` → write to file
+12. `stopServer(handle)`
+13. `git worktree remove ...` + `git branch -D ...`
+
+**Progress output** (emitted to stdout between steps):
+```
+[review] PR #${pr} — fetching...
+[review] Starting Gremlin Server on port ${port}...
+[review] Phase 1: Extracting structure...
+[review] Phase 1 complete: ${vertices} vertices, ${edges} edges
+[review] Running checks...
+[review] Done. Guidebook: ${outputPath}
+```
+
+---
+
+## Dependency Graph
+
+```
+INTERFACES.md (this file — defines contracts)
+ │
+ ├──→ extraction/tree-sitter.js ──┐
+ ├──→ infrastructure/docker.js ──┤
+ ├──→ renderer/render.js │
+ │ ▼
+ │ graph/populate.js
+ │ │
+ │ ▼
+ │ patterns/completeness.js
+ │ patterns/coverage-gaps.js
+ │ │
+ └──→ review.js (orchestrator) ◄───┘
+```
+
+Modules above the line can be implemented in parallel.
+Modules below the line depend on those above.
diff --git a/.skills/tinker-review/references/schema.md b/.skills/tinker-review/references/schema.md
new file mode 100644
index 0000000000..f80dbef8b4
--- /dev/null
+++ b/.skills/tinker-review/references/schema.md
@@ -0,0 +1,184 @@
+# PR Knowledge Graph Schema
+
+## Vertices (9 labels)
+
+### Code structure
+
+**File** `{ path, language, changeLevel }`
+A source file in the PR. `changeLevel` grades how much the PR moved it (see
+**Change levels** below); a file the PR touched is anything but `NONE`.
+
+*Stub Files* `{ path, language, changeLevel: "STRUCTURAL", parsed: false, deleted }`
+are markers for changed files the extractor didn't parse, so the PR's `modifies`
+edge still lands. Unparsed, so no fingerprint is possible — graded `STRUCTURAL`
+conservatively. `deleted: true` means the PR removed the file (absent from the
+PR-head worktree); `deleted: false` means it's present but an unparsed type
+(non-code, or a non-primary language). Real Files have no `parsed` property, so
+select materialized files with `.hasNot("parsed")` and markers with
+`.has("parsed", false)`.
+
+**Function** `{ name, signature, visibility, filePath, language, lines_start, lines_end, changeLevel }`
+A function or method. The primary unit of analysis. `changeLevel` is graded per
+function by diffing the base against the PR-head version — so an untouched helper
+in a changed file grades `NONE`, not "changed". `language` is the source
+language (java, python, javascript, go, csharp, dart); by-name edges (`calls`,
+`tests`) resolve only within a language, so a multi-language PR never invents
+cross-language edges.
+
+*External stub Functions* `{ name, external: true, resolved: false, changeLevel: "NONE", origin?, definedIn? }`
+are markers created when a `calls`/`tests` edge targets a function by name that
+wasn't extracted (a library/JDK call, or a function in a file this PR didn't
+change). They keep the edge from vanishing and let blast-radius/centrality see
+the call; they lack `filePath`/`signature`/`visibility`. Filter them out with
+`.has("external", false)` — or, since real Functions have no `external` property,
+`.hasNot("external")` — when you only want materialized code.
+
+`classifyExternals` tags each stub with `origin`: `library` (a known JDK/accessor
+name — noise), `project` (a repo source declares a type with this name;
+`definedIn` records the file), or `unresolved` (unknown). Centrality drops
+`origin: library` calls from out-degree so ubiquitous accessor calls don't
+inflate hotspots.
+
+**Type** `{ name, kind, visibility, filePath, language, changeLevel }`
+A class, interface, struct, or enum. `kind` is one of: class, interface, struct,
+enum. `changeLevel` grades the type's declaration surface: a change to its
+kind/visibility/supertypes/member-set is `STRUCTURAL`; a change to method bodies
+in the declaration leaves it `BEHAVIORAL`/`FORMATTING`. `language` scopes
+`extends`/`implements` resolution so hierarchies never cross languages.
+
+*External stub Types* `{ name, external: true, resolved: false }` are markers
+created when an `extends`/`implements` edge names a supertype that wasn't
+extracted — typically a JDK/library class outside the worktree. In-repo
+supertypes are usually materialized by the extractor's hierarchy-neighborhood
+expansion (which pulls a changed type's ancestors and descendants in as context),
+so stubs mostly stand for third-party types. They lack `kind`/`filePath`; filter
+them with `.has("external", false)` or `.hasNot("external")`.
+
+#### Change levels
+
+`changeLevel` (on File, Function, Type) grades how much the PR moved a vertex,
+computed by diffing the base version of each changed file against PR-head. It
+replaces the old boolean `changed` — because that was stamped per file, it could
+not tell an untouched helper in a changed file from the code the PR rewrote.
+
+| Level | Meaning |
+|-------|---------|
+| `NONE` | byte-identical to base (untouched; also context / hierarchy-neighborhood files and external stubs) |
+| `FORMATTING` | only comments or whitespace moved; the tokens are identical |
+| `BEHAVIORAL` | the body changed for real, but the signature is stable |
+| `STRUCTURAL` | the signature/declaration changed, or the member/file was added or removed, or imports/exports changed |
+
+Query the two useful sets directly: **any real change** is
+`.has("changeLevel", within("FORMATTING","BEHAVIORAL","STRUCTURAL"))` (inclusion-
+oriented checks — orphans, cluster-analysis, architecture); **meaningful change**
+is `.has("changeLevel", within("BEHAVIORAL","STRUCTURAL"))` (risk checks —
+centrality, blast-radius, coverage-gaps, which discount NONE and FORMATTING by
+default). The vocabulary and predicate helpers live in
+`scripts/graph/change-levels.js`.
+
+*Analysis-written property* — `community: number` is stamped onto Function, Type,
+File and Test vertices by community detection (`communityDetection`, Louvain
+modularity over the code subgraph). Vertices sharing a value are one densely-tied
+theme; query a theme with `.has("community", n)`. Vertices with no in-subgraph code
+edge are left unstamped. This is distinct from `connectedComponent()`, which the
+`clusterAnalysis` guard runs on the `a` (OLAP) source without persisting a property.
+
+### TinkerPop domain
+
+**Step** `{ name, canonical_name }`
+A Gremlin traversal step as a concept (e.g., "addV", "has", "out"). Created during enrichment when functions are mapped to steps.
+
+**GrammarRule** `{ name, production }`
+An ANTLR production in Gremlin.g4.
+
+### Verification
+
+**Test** `{ name, type, filePath, language }`
+A test function. `type` is one of: unit, integration, suite. `language` scopes
+the `tests` edge to same-language functions.
+
+**Doc** `{ path, section }`
+A documentation file or section that references code.
+
+### Discussion
+
+**Discussion** `{ url, source, title, body }`
+Any discussion artifact. `source` is one of: devlist, jira, proposal, pr.
+The PR itself is a Discussion with `source: "pr"`.
+
+**Comment** `{ author, body, timestamp }`
+A comment on a Discussion.
+
+## Edges (16 implemented + 1 planned)
+
+One edge is marked ⚠️ *planned* below (`depends_on`) — documented but intentionally
+not populated.
+
+### Edge confidence (every edge)
+
+Every edge carries a `confidence` property recording how the relationship was
+established, so downstream analysis and the reviewer can separate observed fact
+from deduction:
+
+| Value | Meaning | Examples |
+|-------|---------|----------|
+| `EXTRACTED` | Explicitly present in source or the git diff | `defines`, `modifies`, `has_comment`, an `addresses` link stated in the PR body/diff (`found_in: pr`/`diff`) |
+| `INFERRED` | Reasonable deduction | `calls`/`tests` (resolved by name match), `proposed_in`, a cross-referenced `addresses` (`found_in: jira_body`/`devlist_body`), agent `implements_step`/`documents` mappings |
+| `AMBIGUOUS` | Uncertain; flagged for human review | keyword-search `addresses` (`found_in: search`), low-confidence agent guesses |
+
+Enrichment write commands (`mapStep`, `linkDiscussion`, `linkDoc`) accept an
+optional `--confidence` flag (default `INFERRED`). `auditConfidence` reports the
+distribution and lists every `AMBIGUOUS` edge; the review's structural appendix
+renders this as the **Signal Confidence** panel.
+
+### Code relationships
+
+| Edge | From | To | Meaning |
+|------|------|----|---------|
+| `calls` | Function | Function | Function invokes another function |
+| `defines` | File | Function or Type | File contains this definition |
+| `declares` | Type | Function | Type's body declares this method (the membership edge; both endpoints pinned to the same file). `EXTRACTED` |
+| `extends` | Type | Type | Subclass extends a superclass, or interface extends an interface. Supertype resolved by simple name; unresolved parents get an external Type stub. `INFERRED` |
+| `implements` | Type | Type | Class implements an interface. Same resolution/stub behavior as `extends`. (Java splits `extends`/`implements` precisely; other languages label all bases `extends`.) `INFERRED` |
+| `overrides` | Function | Function | A method overrides a same-named method declared by an ancestor type (transitive over `extends`/`implements`). Derived after population by `deriveOverrides`. `INFERRED` |
+| `depends_on` | File | File | ⚠️ *planned, not populated.* File imports/requires another file. Intentionally omitted — call/defines edges already carry file connectivity (see `populate.js`). |
+| `references` | File | File (deleted) | A surviving file still mentions a symbol from a file the PR deleted. Added during a removal review via `addReference`; carries `symbol` and `location` properties. |
+
+### Domain relationships
+
+| Edge | From | To | Meaning |
+|------|------|----|---------|
+| `implements_step` | Function | Step | This function is a GLV's implementation of a Gremlin step |
+| `has_rule` | Step | GrammarRule | This step is defined by this grammar production. Written by `linkRule` (after `addGrammarRule` creates the rule vertex). `INFERRED` |
+
+### Verification
+
+| Edge | From | To | Meaning |
+|------|------|----|---------|
+| `tests` | Test | Function | This test exercises this function |
+| `covers` | Test | Step | This test covers this step's behavior. Written by `mapCoverage`. The `new-step` playbook treats a missing `covers` as a coverage gap. `INFERRED` |
+| `documents` | Doc | Step, Function, or Type | This doc describes this entity |
+
+### Discussion
+
+| Edge | From | To | Meaning |
+|------|------|----|---------|
+| `has_comment` | Discussion | Comment | Discussion contains this comment |
+| `addresses` | Discussion | Discussion | One discussion references another (e.g., PR addresses a JIRA) |
+| `proposed_in` | Discussion(proposal) | Discussion(pr) | A `docs/src/dev/future` proposal that this PR appears to relate to. Confidence tracks how it was found (see properties below). |
+| `modifies` | Discussion(pr) | Function or File | The PR modifies this code |
+
+#### `addresses` edge properties
+
+| Property | Values | Meaning |
+|----------|--------|---------|
+| `found_in` | `pr`, `diff`, `search`, `jira_body`, `devlist_body` | Where the link was discovered |
+| `found_via` | JIRA ID or URL | Which discussion contained the reference (for secondary links) |
+
+#### `proposed_in` edge properties
+
+| Property | Values | Meaning |
+|----------|--------|---------|
+| `matched_in` | `reference`, `title`, `body` | How the proposal was linked: an explicit path reference in the PR (`EXTRACTED`), a keyword in the proposal's title/heading (`INFERRED`), or keywords in its body (`AMBIGUOUS`). |
+| `matched_keywords` | comma-separated terms | The keywords that matched, so the link is self-explanatory. |
+
diff --git a/.skills/tinker-review/scripts/discovery/discussions.js b/.skills/tinker-review/scripts/discovery/discussions.js
new file mode 100644
index 0000000000..eafa49263b
--- /dev/null
+++ b/.skills/tinker-review/scripts/discovery/discussions.js
@@ -0,0 +1,349 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { get } from "node:https";
+import { readdir, readFile } from "node:fs/promises";
+import { join, basename } from "node:path";
+
+const JIRA_BASE = "https://issues.apache.org/jira";
+const DEV_LIST_API = "https://lists.apache.org/api/stats.lua";
+const TINKERPOP_JIRA_PATTERN = /TINKERPOP-(\d+)/g;
+const DEV_LIST_LINK_PATTERN = /https?:\/\/lists\.apache\.org\/[^\s)\]>"[]*/g;
+const PROPOSAL_DIR = "docs/src/dev/future";
+
+function httpGet(url) {
+ return new Promise((resolve, reject) => {
+ get(url, (res) => {
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
+ return httpGet(res.headers.location).then(resolve, reject);
+ }
+ let data = "";
+ res.on("data", (chunk) => { data += chunk; });
+ res.on("end", () => {
+ if (res.statusCode >= 200 && res.statusCode < 300) {
+ resolve(data);
+ } else {
+ reject(new Error(`HTTP ${res.statusCode}: ${url}`));
+ }
+ });
+ }).on("error", reject);
+ });
+}
+
+async function fetchJira(ticketId) {
+ try {
+ const url = `${JIRA_BASE}/rest/api/2/issue/${ticketId}?fields=summary,description,status,issuetype,comment`;
+ const data = JSON.parse(await httpGet(url));
+ const comments = (data.fields?.comment?.comments || []).map((c) => ({
+ author: c.author?.displayName || c.author?.name || "unknown",
+ body: (c.body || "").slice(0, 1000),
+ timestamp: c.created,
+ }));
+ return {
+ id: ticketId,
+ url: `${JIRA_BASE}/browse/${ticketId}`,
+ source: "jira",
+ title: data.fields?.summary || ticketId,
+ body: (data.fields?.description || "").slice(0, 2000),
+ status: data.fields?.status?.name || "unknown",
+ type: data.fields?.issuetype?.name || "unknown",
+ comments,
+ };
+ } catch {
+ return null;
+ }
+}
+
+async function fetchPrComments(prNumber) {
+ try {
+ const url = `https://api.github.com/repos/apache/tinkerpop/issues/${prNumber}/comments?per_page=50`;
+ const data = JSON.parse(await httpGet(url));
+ if (!Array.isArray(data)) return [];
+ return data.map((c) => ({
+ author: c.user?.login || "unknown",
+ body: (c.body || "").slice(0, 1000),
+ timestamp: c.created_at,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+async function fetchPrReviewComments(prNumber) {
+ try {
+ const url = `https://api.github.com/repos/apache/tinkerpop/pulls/${prNumber}/comments?per_page=50`;
+ const data = JSON.parse(await httpGet(url));
+ if (!Array.isArray(data)) return [];
+ return data.map((c) => ({
+ author: c.user?.login || "unknown",
+ body: (c.body || "").slice(0, 1000),
+ path: c.path || "",
+ timestamp: c.created_at,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+async function searchDevList(keywords) {
+ try {
+ const query = encodeURIComponent(keywords.join(" "));
+ const url = `${DEV_LIST_API}?list=dev&domain=tinkerpop.apache.org&q=${query}&d=lte=1y`;
+ const data = JSON.parse(await httpGet(url));
+ if (!data.emails || data.emails.length === 0) return [];
+
+ return data.emails
+ // Drop replies and JIRA notifications ([jira] subject prefix): those
+ // mirror ticket activity already captured via JIRA discovery. Keep only
+ // content unique to the dev list.
+ .filter((e) => e.subject && !e.subject.startsWith("Re:") && !/\[jira\]/i.test(e.subject))
+ .slice(0, 5)
+ .map((e) => ({
+ url: `https://lists.apache.org/thread/${e.mid}`,
+ source: "devlist",
+ title: e.subject,
+ body: (e.body || "").slice(0, 1000),
+ date: new Date(e.epoch * 1000).toISOString().slice(0, 10),
+ }));
+ } catch {
+ return [];
+ }
+}
+
+// Whole-word, case-insensitive match for a keyword (so "krb5" doesn't hit inside
+// another token, and a keyword must stand on word boundaries).
+function keywordRegex(kw) {
+ const esc = kw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ return new RegExp(`(?:^|[^A-Za-z0-9])${esc}(?:[^A-Za-z0-9]|$)`, "i");
+}
+
+// Split an asciidoc proposal into { title, headings, body }, dropping the ASF
+// license preamble by starting at the first level-1 title (`= Title`). Without
+// this, keyword matching hits the license header ("...the NOTICE file...") that
+// every ASF-licensed doc carries.
+function splitProposal(raw) {
+ const lines = raw.split("\n");
+ const titleIdx = lines.findIndex((l) => /^=\s+\S/.test(l));
+ const content = titleIdx >= 0 ? lines.slice(titleIdx) : lines;
+ const title = titleIdx >= 0 ? content[0].replace(/^=\s+/, "").trim() : "";
+ const headings = content.filter((l) => /^=+\s+\S/.test(l)).join("\n");
+ return { title, headings, body: content.join("\n") };
+}
+
+// The proposals index (docs/src/dev/future/index.asciidoc) is a table of
+// contents, not a proposal — its headings name every topic, so it matches
+// keywords spuriously. Exclude it from proposal discovery.
+const isProposalIndex = (file) => /^index\.(asciidoc|adoc)$/i.test(basename(file));
+
+export async function findMatchingProposals(repoPath, keywords) {
+ const proposalDir = join(repoPath, PROPOSAL_DIR);
+ try {
+ const files = await readdir(proposalDir);
+ const proposals = [];
+
+ for (const file of files) {
+ if (!file.endsWith(".asciidoc") && !file.endsWith(".adoc")) continue;
+ if (isProposalIndex(file)) continue;
+ const { title, headings, body } = splitProposal(await readFile(join(proposalDir, file), "utf-8"));
+
+ const matches = (text) => keywords.filter((k) => keywordRegex(k).test(text));
+ const titleHits = new Set([...matches(title), ...matches(headings)]);
+ const bodyHits = new Set(matches(body));
+ // Keep a proposal only on real signal: a keyword in its title/heading, or
+ // at least two distinct keywords in the body. A lone body mention is noise.
+ const strong = titleHits.size > 0;
+ if (!strong && bodyHits.size < 2) continue;
+
+ proposals.push({
+ file,
+ path: `${PROPOSAL_DIR}/${file}`,
+ source: "proposal",
+ title: title || file,
+ matchedKeywords: [...new Set([...titleHits, ...bodyHits])],
+ matchedIn: strong ? "title" : "body",
+ found_in: "search",
+ score: titleHits.size * 2 + bodyHits.size,
+ snippet: body.slice(0, 500),
+ });
+ }
+
+ return proposals.sort((a, b) => b.score - a.score);
+ } catch {
+ return [];
+ }
+}
+
+// Turn explicit proposal paths referenced in the PR text/diff into proposal
+// records at EXTRACTED confidence — a named reference is a fact, not a guess.
+async function resolveExplicitProposals(repoPath, proposalPaths) {
+ const out = [];
+ for (const rel of new Set(proposalPaths.map((p) => p.replace(/[.,)\]]+$/, "")))) {
+ if (isProposalIndex(rel)) continue;
+ try {
+ const { title } = splitProposal(await readFile(join(repoPath, rel), "utf-8"));
+ out.push({
+ file: basename(rel),
+ path: rel,
+ source: "proposal",
+ title: title || rel,
+ matchedKeywords: [],
+ matchedIn: "reference",
+ found_in: "pr",
+ score: 100,
+ snippet: "",
+ });
+ } catch {
+ // Referenced path may not exist in this worktree — skip it.
+ }
+ }
+ return out;
+}
+
+function extractLinksFromText(text) {
+ const jiraRefs = [...new Set([...text.matchAll(TINKERPOP_JIRA_PATTERN)].map((m) => m[0]))];
+ const devListRefs = [...new Set([...text.matchAll(DEV_LIST_LINK_PATTERN)].map((m) => m[0]))];
+ return { jiraRefs, devListRefs };
+}
+
+async function followLinks(discussions) {
+ const secondary = [];
+
+ for (const disc of discussions) {
+ const commentBodies = (disc.comments || []).map((c) => c.body).join("\n");
+ const textToScan = [disc.body || "", disc.title || "", commentBodies].join("\n");
+ const { jiraRefs, devListRefs } = extractLinksFromText(textToScan);
+
+ for (const jiraId of jiraRefs) {
+ if (discussions.some((d) => d.id === jiraId)) continue;
+ const jira = await fetchJira(jiraId);
+ if (jira) {
+ secondary.push({
+ ...jira,
+ found_in: `${disc.source}_body`,
+ found_via: disc.id || disc.url,
+ });
+ }
+ }
+
+ for (const url of devListRefs) {
+ if (discussions.some((d) => d.url === url)) continue;
+ secondary.push({
+ url,
+ source: "devlist",
+ title: "(referenced thread)",
+ body: "",
+ found_in: `${disc.source}_body`,
+ found_via: disc.id || disc.url,
+ });
+ }
+ }
+
+ return secondary;
+}
+
+/**
+ * Discover discussions and proposals related to a PR.
+ *
+ * Strategy:
+ * - JIRA: scan all text for TINKERPOP-XXXX. Fetch if found. If absent, note missing.
+ * - Dev list: scan for explicit links. If none, search archives (max 1 year back).
+ * If search returns nothing, note missing.
+ * - Proposals: check docs/src/dev/future/ for documents matching PR keywords.
+ * If not referenced anywhere, still check by keyword match.
+ * - Cross-reference: follow one hop from each discovered discussion to find
+ * additional JIRAs and dev list threads referenced within them.
+ *
+ * @param {object} params
+ * @param {number} params.pr - PR number (for fetching comments from GitHub)
+ * @param {string} params.prTitle - PR title
+ * @param {string} params.prBody - PR body/description
+ * @param {string} params.diff - The full diff text
+ * @param {string[]} params.keywords - Keywords for search (class names, step names, etc.)
+ * @param {string} params.repoPath - Path to the repo (for proposal discovery)
+ * @returns {Promise<DiscoveryResult>}
+ */
+export async function discoverDiscussions(params) {
+ const { pr, prTitle = "", prBody = "", diff = "", keywords = [], repoPath = "" } = params;
+
+ // Fetch PR comments from GitHub (issue comments + inline review comments)
+ const issueComments = pr ? await fetchPrComments(pr) : [];
+ const reviewComments = pr ? await fetchPrReviewComments(pr) : [];
+ const prCommentBodies = [...issueComments, ...reviewComments].map((c) => c.body);
+
+ const allText = [prTitle, prBody, ...prCommentBodies, diff].join("\n");
+
+ // --- JIRA (direct) ---
+ const jiraMatches = [...new Set([...allText.matchAll(TINKERPOP_JIRA_PATTERN)].map((m) => m[0]))];
+ const jiras = (await Promise.all(jiraMatches.map(fetchJira))).filter(Boolean);
+ for (const j of jiras) { j.found_in = "pr"; }
+
+ // --- Dev list (direct) ---
+ const devListLinks = [...new Set([...allText.matchAll(DEV_LIST_LINK_PATTERN)].map((m) => m[0]))];
+ const explicitDevList = devListLinks.map((url) => ({
+ url,
+ source: "devlist",
+ title: "(linked thread)",
+ body: "",
+ found_in: "pr",
+ }));
+
+ let searchedDevList = [];
+ let devListSearchPerformed = false;
+ if (explicitDevList.length === 0 && keywords.length > 0) {
+ devListSearchPerformed = true;
+ searchedDevList = await searchDevList(keywords);
+ for (const d of searchedDevList) { d.found_in = "search"; }
+ }
+
+ // --- Cross-reference: follow one hop from direct discoveries ---
+ const directDiscussions = [...jiras, ...explicitDevList, ...searchedDevList];
+ const secondaryDiscussions = await followLinks(directDiscussions);
+
+ // --- Proposals ---
+ // Explicit references in the PR text/diff are EXTRACTED facts; keyword matches
+ // are the graded fuzzy fallback. Merge them, letting an explicit reference win
+ // over a keyword hit for the same proposal.
+ const proposalLinks = [...allText.matchAll(/docs\/src\/dev\/future\/[^\s)\]>"]+/g)].map((m) => m[0]);
+ let proposals = [];
+ if (repoPath) {
+ const explicit = await resolveExplicitProposals(repoPath, proposalLinks);
+ const explicitPaths = new Set(explicit.map((p) => p.path));
+ const keywordMatched = (await findMatchingProposals(repoPath, keywords))
+ .filter((p) => !explicitPaths.has(p.path));
+ proposals = [...explicit, ...keywordMatched];
+ }
+
+ return {
+ jiras,
+ jiraMissing: jiraMatches.length === 0,
+
+ devList: [...explicitDevList, ...searchedDevList],
+ devListMissing: explicitDevList.length === 0 && searchedDevList.length === 0,
+ devListSearchPerformed,
+ devListSearchKeywords: devListSearchPerformed ? keywords : [],
+
+ secondary: secondaryDiscussions,
+
+ prComments: { issue: issueComments, review: reviewComments },
+
+ proposals,
+ proposalLinked: proposalLinks.length > 0,
+ proposalMissing: proposalLinks.length === 0 && proposals.length === 0,
+ };
+}
diff --git a/.skills/tinker-review/scripts/enrichment/api.js b/.skills/tinker-review/scripts/enrichment/api.js
new file mode 100644
index 0000000000..3f21cdf042
--- /dev/null
+++ b/.skills/tinker-review/scripts/enrichment/api.js
@@ -0,0 +1,496 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import gremlin from "gremlin";
+import { CONFIDENCE, normalizeConfidence, isValidConfidence } from "../graph/confidence.js";
+import { changedAny, normalizeChangeLevel } from "../graph/change-levels.js";
+import { symbolFromPath, createReferenceEdge } from "../graph/references.js";
+
+const { process: { statics: __ } } = gremlin;
+
+let cachedSteps = null;
+
+// === Read operations ===
+
+/**
+ * List Function vertices, optionally filtered. The go-to orientation read:
+ * `--changeLevel STRUCTURAL` shows just the signature-level changes;
+ * `--changed true` (alias for "any level but NONE") shows everything the PR
+ * touched; `--visibility public` narrows to the API surface. Returns signature
+ * and line span so you can jump to source in the worktree.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} [filter] - { changeLevel?: string, changed?: boolean, visibility?: string, filePath?: string }
+ * @returns {Promise<{name, signature, filePath, visibility, changeLevel, changed, linesStart, linesEnd}[]>}
+ */
+export async function listFunctions(g, filter = {}) {
+ let t = g.V().hasLabel("Function");
+ if (filter.changeLevel) {
+ // Exact-grade filter.
+ t = t.has("changeLevel", normalizeChangeLevel(filter.changeLevel, filter.changeLevel));
+ } else if (filter.changed !== undefined) {
+ // Back-compat alias: changed=true → anything but NONE; changed=false → NONE.
+ t = filter.changed ? t.has("changeLevel", changedAny()) : t.has("changeLevel", "NONE");
+ }
+ if (filter.visibility) t = t.has("visibility", filter.visibility);
+ if (filter.filePath) t = t.has("filePath", filter.filePath);
+ const results = await t.elementMap().toList();
+ return results.map(m => {
+ const changeLevel = m.get("changeLevel");
+ return {
+ name: m.get("name"),
+ signature: m.get("signature"),
+ filePath: m.get("filePath"),
+ visibility: m.get("visibility"),
+ changeLevel,
+ changed: changeLevel !== undefined && changeLevel !== "NONE",
+ linesStart: m.get("lines_start"),
+ linesEnd: m.get("lines_end"),
+ };
+ });
+}
+
+/**
+ * List Type vertices (classes, interfaces, enums), optionally by `kind` or
+ * `filePath`. Use it to see the types the PR defines or touches before drilling
+ * into their functions.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} [filter] - { kind?: string, filePath?: string }
+ * @returns {Promise<{name, kind, visibility, filePath}[]>}
+ */
+export async function listTypes(g, filter = {}) {
+ let t = g.V().hasLabel("Type");
+ if (filter.kind) t = t.has("kind", filter.kind);
+ if (filter.filePath) t = t.has("filePath", filter.filePath);
+ const results = await t.elementMap().toList();
+ return results.map(m => ({
+ name: m.get("name"),
+ kind: m.get("kind"),
+ visibility: m.get("visibility"),
+ filePath: m.get("filePath"),
+ }));
+}
+
+/**
+ * The direct callees of one function — its outgoing `calls` edges. Use it to
+ * trace what a changed function depends on (e.g. does it still call a symbol the
+ * PR removed?). The function is keyed by name AND file because names repeat
+ * across the codebase.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} functionName - Caller's name
+ * @param {string} filePath - Caller's file (disambiguates same-named functions)
+ * @returns {Promise<{calleeName, filePath}[]>}
+ */
+export async function getCallsFrom(g, functionName, filePath) {
+ const results = await g.V().hasLabel("Function")
+ .has("name", functionName)
+ .has("filePath", filePath)
+ .out("calls")
+ .elementMap()
+ .toList();
+ return results.map(m => ({
+ calleeName: m.get("name"),
+ filePath: m.get("filePath"),
+ }));
+}
+
+/**
+ * The canonical Gremlin traversal-step vocabulary, parsed from `Gremlin.g4`
+ * (every `traversalMethod_<name>` rule). This is the authoritative set of step
+ * names you map GLV/host-language methods onto with `mapStep`. Reads the grammar
+ * file, not the graph, so it needs the repo path rather than `g`; result is
+ * cached for the process.
+ *
+ * @param {string} repoPath - Path to the checked-out worktree
+ * @returns {Promise<string[]>} sorted, de-duplicated canonical step names
+ */
+export async function getCanonicalSteps(repoPath) {
+ if (cachedSteps) return cachedSteps;
+ const g4Path = join(repoPath, "gremlin-language/src/main/antlr4/Gremlin.g4");
+ const g4 = await readFile(g4Path, "utf-8");
+ cachedSteps = [...g4.matchAll(/traversalMethod_(\w+)/g)].map(m => m[1]);
+ cachedSteps = [...new Set(cachedSteps)].sort();
+ return cachedSteps;
+}
+
+// === Removal-impact reads ===
+
+/**
+ * Files the PR deleted (stub Files marked deleted). Each entry pairs the path
+ * with the symbol name it likely defined, so the agent can grep the surviving
+ * tree for lingering references to removed code.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @returns {Promise<{path: string, symbol: string}[]>}
+ */
+export async function listDeleted(g) {
+ const paths = await g.V().hasLabel("File").has("deleted", true).values("path").toList();
+ return paths.map((path) => ({ path, symbol: symbolFromPath(path) }));
+}
+
+/**
+ * Unresolved external callees (external Function stubs) — names the changed code
+ * calls that weren't defined in the changed set. Includes each stub's `origin`
+ * (library/project/unresolved, once classifyExternals has run) and flags any
+ * whose name matches a deleted file's symbol: a changed file still calling a
+ * just-removed name is a dangling reference visible in the graph alone.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @returns {Promise<{name: string, origin: string, matchesDeletedSymbol: boolean}[]>}
+ */
+export async function listExternalRefs(g) {
+ const rows = await g.V().hasLabel("Function").has("external", true)
+ .project("name", "origin")
+ .by("name")
+ .by(__.coalesce(__.values("origin"), __.constant("unclassified")))
+ .toList();
+ const deletedPaths = await g.V().hasLabel("File").has("deleted", true).values("path").toList();
+ const deletedSymbols = new Set(deletedPaths.map(symbolFromPath));
+
+ const rank = { project: 0, unresolved: 1, unclassified: 2, library: 3 };
+ return rows
+ .map((r) => ({
+ name: r.get("name"),
+ origin: r.get("origin"),
+ matchesDeletedSymbol: deletedSymbols.has(r.get("name")),
+ }))
+ .sort((a, b) => {
+ if (a.matchesDeletedSymbol !== b.matchesDeletedSymbol) return a.matchesDeletedSymbol ? -1 : 1;
+ return (rank[a.origin] ?? 9) - (rank[b.origin] ?? 9);
+ });
+}
+
+// === Write operations ===
+
+/**
+ * Record that a GLV/host-language function implements a canonical Gremlin step,
+ * as an `implements_step` edge (creating the Step vertex if it's the first time
+ * that step is seen). The core enrichment move of the GLV playbook: map only
+ * real traversal-step methods, not language boilerplate. Validate the step name
+ * against `getCanonicalSteps` first.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} functionName - The implementing function's name
+ * @param {string} filePath - The implementing function's file
+ * @param {string} canonicalStepName - A name from getCanonicalSteps
+ * @param {string} [confidence] - default INFERRED (a name-based mapping)
+ * @returns {Promise<object>}
+ */
+export async function mapStep(g, functionName, filePath, canonicalStepName, confidence) {
+ const conf = normalizeConfidence(confidence, CONFIDENCE.INFERRED);
+ const stepExists = await g.V().hasLabel("Step").has("name", canonicalStepName).hasNext();
+ if (!stepExists) {
+ await g.addV("Step")
+ .property("name", canonicalStepName)
+ .property("canonical_name", canonicalStepName)
+ .next();
+ }
+
+ await g.V().hasLabel("Function")
+ .has("name", functionName)
+ .has("filePath", filePath)
+ .addE("implements_step")
+ .property("confidence", conf)
+ .to(__.V().hasLabel("Step").has("name", canonicalStepName))
+ .next();
+
+ return { mapped: `${functionName} -> ${canonicalStepName}`, confidence: conf };
+}
+
+/**
+ * Re-grade the confidence of existing edge(s) after the agent verifies them
+ * against source. Identifies edges by their source vertex (name, optionally
+ * pinned to a file) and relation, optionally narrowed to a named target —
+ * covering the edges agents actually verify (`calls`, `implements_step`).
+ * Promote a confirmed edge to EXTRACTED, or downgrade a wrong resolution to
+ * AMBIGUOUS so it surfaces in the report's review list.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} params
+ * @param {string} params.relation - Edge label (e.g. calls, implements_step)
+ * @param {string} params.fromName - Source vertex name
+ * @param {string} [params.fromFile] - Pin the source to this filePath
+ * @param {string} [params.toName] - Narrow to edges whose target has this name
+ * @param {string} [params.fromLabel] - Source vertex label (default Function)
+ * @param {string} params.confidence - EXTRACTED | INFERRED | AMBIGUOUS
+ * @returns {Promise<object>}
+ */
+export async function setEdgeConfidence(g, params = {}) {
+ const { relation, fromName, fromFile, toName, fromLabel = "Function", confidence } = params;
+ if (!isValidConfidence(confidence)) {
+ return { error: `invalid confidence "${confidence}" — use EXTRACTED, INFERRED, or AMBIGUOUS` };
+ }
+ if (!relation || !fromName) {
+ return { error: "relation and fromName are required" };
+ }
+
+ let t = g.V().hasLabel(fromLabel).has("name", fromName);
+ if (fromFile) t = t.has("filePath", fromFile);
+ t = t.outE(relation);
+ if (toName) t = t.where(__.inV().has("name", toName));
+
+ const updated = await t.property("confidence", confidence).toList();
+ return {
+ relation,
+ from: fromName,
+ to: toName || "*",
+ confidence,
+ updated: updated.length,
+ };
+}
+
+/**
+ * Manual escape hatch for recording a lingering reference to removed code that
+ * the Phase-1 removal-refs pass didn't catch — e.g. a config-string or
+ * non-code-symbol reference, which that pass deliberately skips. The automatic
+ * pass (patterns/removal-refs.js) handles code symbols; use this for the cases
+ * that need a human/agent to spot. Creates the same `references` edge.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} params
+ * @param {string} params.fromPath - Surviving file that references the removed symbol
+ * @param {string} params.toPath - Deleted file path (must be an existing deleted File)
+ * @param {string} [params.symbol] - The removed symbol found in fromPath
+ * @param {string} [params.location] - Where (e.g. "L42" or a line snippet)
+ * @param {string} [params.confidence] - default INFERRED (a textual match)
+ * @returns {Promise<object>}
+ */
+export async function addReference(g, params = {}) {
+ const { fromPath, toPath, symbol, location, confidence } = params;
+ const conf = normalizeConfidence(confidence, CONFIDENCE.INFERRED);
+ if (!fromPath || !toPath) {
+ return { error: "fromPath and toPath are required" };
+ }
+
+ const targetExists = await g.V().hasLabel("File").has("path", toPath).hasNext();
+ if (!targetExists) {
+ return { error: `no deleted File vertex for toPath "${toPath}" (use listDeleted for valid targets)` };
+ }
+
+ await createReferenceEdge(g, { fromPath, toPath, symbol, location, confidence: conf });
+ return { referenced: `${fromPath} -> ${toPath}`, symbol: symbol || "", confidence: conf };
+}
+
+/**
+ * Attach an external discussion you found (JIRA issue, dev-list thread, proposal
+ * doc) to the graph as a Discussion vertex, linked from the PR's own discussion
+ * via an `addresses` edge. Use it when enrichment turns up prior context the
+ * Phase-1 discovery pass missed, so the report can cite where the change was
+ * debated.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} url - Canonical link to the discussion
+ * @param {string} source - jira | devlist | proposal
+ * @param {string} title - Human-readable title
+ * @param {string} [body] - Optional excerpt/summary
+ * @param {string} [confidence] - default INFERRED
+ * @returns {Promise<object>}
+ */
+export async function linkDiscussion(g, url, source, title, body, confidence) {
+ const conf = normalizeConfidence(confidence, CONFIDENCE.INFERRED);
+ await g.addV("Discussion")
+ .property("url", url)
+ .property("source", source)
+ .property("title", title)
+ .property("body", body || "")
+ .next();
+
+ const prDiscussion = await g.V().hasLabel("Discussion").has("source", "pr").hasNext();
+ if (prDiscussion) {
+ await g.V().hasLabel("Discussion").has("source", "pr")
+ .addE("addresses")
+ .property("confidence", conf)
+ .to(__.V().hasLabel("Discussion").has("url", url))
+ .next();
+ }
+
+ return { linked: `${source}: ${title}`, confidence: conf };
+}
+
+/**
+ * Set an arbitrary property on a vertex identified by label + name. The
+ * general-purpose escape hatch for recording a fact the schema has no dedicated
+ * edge for (e.g. tagging a Function with a review note). Prefer a typed command
+ * when one fits; reach for this only when none does.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} label - Vertex label (e.g. Function, Step)
+ * @param {string} name - Vertex name
+ * @param {string} key - Property key to set
+ * @param {string} value - Property value
+ * @returns {Promise<object>}
+ */
+export async function annotate(g, label, name, key, value) {
+ await g.V().hasLabel(label).has("name", name)
+ .property(key, value)
+ .next();
+
+ return { annotated: `${label}:${name}.${key} = ${value}` };
+}
+
+/**
+ * Record that a documentation file documents a graph entity, as a `documents`
+ * edge from a Doc vertex (created on first use) to the named entity. Use it to
+ * connect a step/feature to the reference docs or recipe that covers it, so the
+ * report can flag a change whose docs weren't updated.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} entityLabel - Label of the documented entity (e.g. Step)
+ * @param {string} entityName - Name of the documented entity
+ * @param {string} docPath - Path to the doc file
+ * @param {string} [section] - Optional section/anchor within the doc
+ * @param {string} [confidence] - default INFERRED
+ * @returns {Promise<object>}
+ */
+export async function linkDoc(g, entityLabel, entityName, docPath, section, confidence) {
+ const conf = normalizeConfidence(confidence, CONFIDENCE.INFERRED);
+ const docExists = await g.V().hasLabel("Doc").has("path", docPath).hasNext();
+ if (!docExists) {
+ await g.addV("Doc")
+ .property("path", docPath)
+ .property("section", section || "")
+ .next();
+ }
+
+ await g.V().hasLabel("Doc").has("path", docPath)
+ .addE("documents")
+ .property("confidence", conf)
+ .to(__.V().hasLabel(entityLabel).has("name", entityName))
+ .next();
+
+ return { linked: `${docPath} documents ${entityLabel}:${entityName}`, confidence: conf };
+}
+
+/**
+ * Add a GrammarRule vertex for a rule the PR introduces to the grammar. Use it
+ * in the grammar playbook when a `*.g4` change adds a production the graph
+ * should track so later steps can link to it.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} name - Rule name
+ * @param {string} [production] - Optional production body
+ * @returns {Promise<object>}
+ */
+export async function addGrammarRule(g, name, production) {
+ await g.addV("GrammarRule")
+ .property("name", name)
+ .property("production", production || "")
+ .next();
+
+ return { added: `GrammarRule: ${name}` };
+}
+
+/**
+ * Link a Gremlin step to the grammar production that defines it, as a `has_rule`
+ * edge (Step -> GrammarRule). Closes the loop `addGrammarRule` opens: the rule
+ * vertex exists, this connects the step concept to it. The grammar playbook's
+ * `checks.completeness` on `has_rule` reports which steps still lack this link.
+ * Both vertices must already exist (`mapStep` creates the Step, `addGrammarRule`
+ * the rule).
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} stepName - Canonical step name (an existing Step vertex)
+ * @param {string} ruleName - Grammar rule name (an existing GrammarRule vertex)
+ * @param {string} [confidence] - default INFERRED
+ * @returns {Promise<object>}
+ */
+export async function linkRule(g, stepName, ruleName, confidence) {
+ const conf = normalizeConfidence(confidence, CONFIDENCE.INFERRED);
+ const stepExists = await g.V().hasLabel("Step").has("name", stepName).hasNext();
+ if (!stepExists) {
+ return { error: `no Step vertex named "${stepName}" (map it with mapStep first)` };
+ }
+ const ruleExists = await g.V().hasLabel("GrammarRule").has("name", ruleName).hasNext();
+ if (!ruleExists) {
+ return { error: `no GrammarRule vertex named "${ruleName}" (add it with addGrammarRule first)` };
+ }
+
+ await g.V().hasLabel("Step").has("name", stepName)
+ .addE("has_rule")
+ .property("confidence", conf)
+ .to(__.V().hasLabel("GrammarRule").has("name", ruleName))
+ .next();
+
+ return { linked: `${stepName} has_rule ${ruleName}`, confidence: conf };
+}
+
+/**
+ * Record that a test covers a Gremlin step's behavior, as a `covers` edge
+ * (Test -> Step). The `new-step` playbook treats a step with no `covers` as a
+ * coverage gap; this is how you record the coverage you find during enrichment.
+ * The test is keyed by name AND file because test names repeat across suites;
+ * the Step vertex must already exist (created via `mapStep`).
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} testName - The covering test's name
+ * @param {string} filePath - The test's file (disambiguates same-named tests)
+ * @param {string} stepName - Canonical step name (an existing Step vertex)
+ * @param {string} [confidence] - default INFERRED
+ * @returns {Promise<object>}
+ */
+export async function mapCoverage(g, testName, filePath, stepName, confidence) {
+ const conf = normalizeConfidence(confidence, CONFIDENCE.INFERRED);
+ const stepExists = await g.V().hasLabel("Step").has("name", stepName).hasNext();
+ if (!stepExists) {
+ return { error: `no Step vertex named "${stepName}" (map it with mapStep first)` };
+ }
+ const testExists = await g.V().hasLabel("Test")
+ .has("name", testName).has("filePath", filePath).hasNext();
+ if (!testExists) {
+ return { error: `no Test vertex "${testName}" in ${filePath}` };
+ }
+
+ await g.V().hasLabel("Test").has("name", testName).has("filePath", filePath)
+ .addE("covers")
+ .property("confidence", conf)
+ .to(__.V().hasLabel("Step").has("name", stepName))
+ .next();
+
+ return { covered: `${testName} covers ${stepName}`, confidence: conf };
+}
+
+/**
+ * INTERNAL (Phase 1). Create the root PR Discussion vertex that every other
+ * discussion links back to via `addresses`. review.js calls this once while
+ * building the graph; it's idempotent (a second call is a no-op). Exposed on the
+ * CLI only for manual re-runs — reviewers don't call it during enrichment.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {number|string} pr - PR number (forms the GitHub URL)
+ * @param {string} [title] - Defaults to "PR #<pr>"
+ * @param {string} [body] - Optional description
+ * @returns {Promise<{created: boolean, pr?}>}
+ */
+export async function createPrDiscussion(g, pr, title, body) {
+ const exists = await g.V().hasLabel("Discussion").has("source", "pr").hasNext();
+ if (exists) return { created: false };
+
+ await g.addV("Discussion")
+ .property("url", `https://github.com/apache/tinkerpop/pull/${pr}`)
+ .property("source", "pr")
+ .property("title", title || `PR #${pr}`)
+ .property("body", body || "")
+ .next();
+
+ return { created: true, pr };
+}
diff --git a/.skills/tinker-review/scripts/enrichment/cli.js b/.skills/tinker-review/scripts/enrichment/cli.js
new file mode 100644
index 0000000000..cac84dcc07
--- /dev/null
+++ b/.skills/tinker-review/scripts/enrichment/cli.js
@@ -0,0 +1,240 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import gremlin from "gremlin";
+import {
+ listFunctions, listTypes, getCallsFrom, getCanonicalSteps,
+ listDeleted, listExternalRefs, addReference,
+ mapStep, setEdgeConfidence, linkDiscussion, linkDoc, addGrammarRule, annotate,
+ linkRule, mapCoverage, createPrDiscussion,
+} from "./api.js";
+import { confidenceAudit, listInferred } from "../patterns/confidence-audit.js";
+import { classifyExternals } from "../patterns/classify-externals.js";
+
+// Every command carries `facing`: "agent" commands are the Phase-2 enrichment
+// tools a reviewer (human or agent) invokes and that SKILL.md documents;
+// "internal" commands are Phase-1 pipeline steps review.js runs itself, exposed
+// here only for manual re-runs. The --help text and the docs/consistency test
+// read `facing` from this registry, so this object is the single source of truth
+// for which commands exist and who they are for. See references/enrichment-cli.md
+// for what each one does.
+const COMMANDS = {
+ // Agent-facing (Phase 2 enrichment) — read
+ listFunctions: { fn: listFunctions, needsG: true, facing: "agent" },
+ listTypes: { fn: listTypes, needsG: true, facing: "agent" },
+ getCallsFrom: { fn: getCallsFrom, needsG: true, facing: "agent" },
+ getCanonicalSteps: { fn: getCanonicalSteps, needsG: false, facing: "agent" },
+ auditConfidence: { fn: confidenceAudit, needsG: true, facing: "agent" },
+ listInferred: { fn: listInferred, needsG: true, facing: "agent" },
+ listDeleted: { fn: listDeleted, needsG: true, facing: "agent" },
+ listExternalRefs: { fn: listExternalRefs, needsG: true, facing: "agent" },
+ // Agent-facing (Phase 2 enrichment) — write
+ addReference: { fn: addReference, needsG: true, facing: "agent" },
+ mapStep: { fn: mapStep, needsG: true, facing: "agent" },
+ setEdgeConfidence: { fn: setEdgeConfidence, needsG: true, facing: "agent" },
+ linkDiscussion: { fn: linkDiscussion, needsG: true, facing: "agent" },
+ linkDoc: { fn: linkDoc, needsG: true, facing: "agent" },
+ addGrammarRule: { fn: addGrammarRule, needsG: true, facing: "agent" },
+ linkRule: { fn: linkRule, needsG: true, facing: "agent" },
+ mapCoverage: { fn: mapCoverage, needsG: true, facing: "agent" },
+ annotate: { fn: annotate, needsG: true, facing: "agent" },
+ // Internal — run by review.js during Phase 1; exposed for manual re-runs only
+ classifyExternals: { fn: classifyExternals, needsG: true, facing: "internal" },
+ createPrDiscussion: { fn: createPrDiscussion, needsG: true, facing: "internal" },
+};
+
+function parseArgs(argv) {
+ const args = {};
+ for (let i = 0; i < argv.length; i++) {
+ if (argv[i].startsWith("--")) {
+ const key = argv[i].slice(2);
+ const val = argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : "true";
+ if (val === "true") args[key] = true;
+ else if (val === "false") args[key] = false;
+ else if (!isNaN(val)) args[key] = Number(val);
+ else args[key] = val;
+ if (val !== "true") i++;
+ }
+ }
+ return args;
+}
+
+async function loadSession(workDir) {
+ const sessionPath = join(workDir, "session.json");
+ const raw = await readFile(sessionPath, "utf-8");
+ return JSON.parse(raw);
+}
+
+async function main() {
+ const [command, ...rest] = process.argv.slice(2);
+
+ if (!command || command === "--help") {
+ console.log("Usage: node cli.js <command> [--key value ...]");
+ console.log(" node cli.js <command> --workDir /tmp/pr-review-3448 [--key value ...]");
+ console.log("");
+ console.log("Commands:");
+ console.log(" listFunctions [--changeLevel STRUCTURAL] [--changed true] [--visibility public]");
+ console.log(" listTypes [--kind class]");
+ console.log(" getCallsFrom --function <name> --file <path>");
+ console.log(" getCanonicalSteps");
+ console.log(" auditConfidence [--maxAmbiguous 50]");
+ console.log(" listInferred [--relation implements_step|calls|...] [--limit 100]");
+ console.log(" listDeleted");
+ console.log(" listExternalRefs");
+ console.log(" addReference --fromPath <path> --toPath <deletedPath> [--symbol <name>] [--location <L42>] [--confidence ...]");
+ console.log(" mapStep --function <name> --file <path> --step <canonicalName> [--confidence INFERRED|AMBIGUOUS|EXTRACTED]");
+ console.log(" setEdgeConfidence --relation <label> --fromName <name> [--fromFile <path>] [--toName <name>] --confidence <EXTRACTED|INFERRED|AMBIGUOUS>");
+ console.log(" linkDiscussion --url <url> --source <jira|devlist|proposal> --title <title> [--body <body>] [--confidence ...]");
+ console.log(" linkDoc --entity <label> --name <name> --doc <path> [--section <section>] [--confidence ...]");
+ console.log(" addGrammarRule --name <name> [--production <production>]");
+ console.log(" linkRule --step <canonicalName> --rule <ruleName> [--confidence ...]");
+ console.log(" mapCoverage --test <name> --file <path> --step <canonicalName> [--confidence ...]");
+ console.log(" annotate --label <label> --name <name> --key <key> --value <value>");
+ console.log("");
+ console.log("Internal (normally run by review.js during Phase 1; here for manual re-runs):");
+ console.log(" classifyExternals (tags external stubs origin=library|project|unresolved)");
+ console.log(" createPrDiscussion --pr <number> --title <title> [--body <body>]");
+ console.log("");
+ console.log("Full description of each command: references/enrichment-cli.md");
+ console.log("");
+ console.log("Options:");
+ console.log(" --workDir Work directory (default: env PR_REVIEW_WORKDIR or /tmp/pr-review-*)");
+ process.exit(0);
+ }
+
+ if (!COMMANDS[command]) {
+ console.error(`Unknown command: ${command}`);
+ console.error(`Available: ${Object.keys(COMMANDS).join(", ")}`);
+ process.exit(1);
+ }
+
+ const args = parseArgs(rest);
+ const workDir = args.workDir || process.env.PR_REVIEW_WORKDIR;
+
+ if (!workDir) {
+ console.error("Error: --workDir or PR_REVIEW_WORKDIR env var required");
+ process.exit(1);
+ }
+
+ const session = await loadSession(workDir);
+ const { fn, needsG } = COMMANDS[command];
+
+ let connection;
+ let g;
+ let result;
+
+ try {
+ if (needsG) {
+ connection = new gremlin.driver.DriverRemoteConnection(session.url);
+ g = gremlin.process.AnonymousTraversalSource.traversal().withRemote(connection);
+ }
+
+ switch (command) {
+ case "listFunctions":
+ result = await fn(g, { changeLevel: args.changeLevel, changed: args.changed, visibility: args.visibility, filePath: args.file });
+ break;
+ case "listTypes":
+ result = await fn(g, { kind: args.kind, filePath: args.file });
+ break;
+ case "getCallsFrom":
+ result = await fn(g, args.function, args.file);
+ break;
+ case "getCanonicalSteps":
+ result = await fn(session.worktreePath || session.repoPath);
+ break;
+ case "auditConfidence":
+ result = await fn(g, { maxAmbiguous: args.maxAmbiguous });
+ break;
+ case "listInferred":
+ result = await fn(g, { relation: args.relation, limit: args.limit });
+ break;
+ case "listDeleted":
+ result = await fn(g);
+ break;
+ case "listExternalRefs":
+ result = await fn(g);
+ break;
+ case "classifyExternals":
+ result = await fn(g, session.worktreePath || session.repoPath);
+ break;
+ case "addReference":
+ result = await fn(g, {
+ fromPath: args.fromPath,
+ toPath: args.toPath,
+ symbol: args.symbol,
+ location: args.location,
+ confidence: args.confidence,
+ });
+ break;
+ case "mapStep":
+ result = await fn(g, args.function, args.file, args.step, args.confidence);
+ break;
+ case "setEdgeConfidence":
+ result = await fn(g, {
+ relation: args.relation,
+ fromName: args.fromName,
+ fromFile: args.fromFile,
+ toName: args.toName,
+ fromLabel: args.fromLabel,
+ confidence: args.confidence,
+ });
+ break;
+ case "linkDiscussion":
+ result = await fn(g, args.url, args.source, args.title, args.body, args.confidence);
+ break;
+ case "linkDoc":
+ result = await fn(g, args.entity, args.name, args.doc, args.section, args.confidence);
+ break;
+ case "addGrammarRule":
+ result = await fn(g, args.name, args.production);
+ break;
+ case "linkRule":
+ result = await fn(g, args.step, args.rule, args.confidence);
+ break;
+ case "mapCoverage":
+ result = await fn(g, args.test, args.file, args.step, args.confidence);
+ break;
+ case "annotate":
+ result = await fn(g, args.label, args.name, args.key, args.value);
+ break;
+ case "createPrDiscussion":
+ result = await fn(g, args.pr, args.title, args.body);
+ break;
+ }
+
+ console.log(JSON.stringify(result, null, 2));
+ } finally {
+ if (connection) await connection.close().catch(() => {});
+ }
+}
+
+// Registry is exported so test/cli-docs.test.js can assert docs stay in sync.
+export { COMMANDS };
+
+// Only run when invoked directly (node cli.js ...), not when imported by a test.
+const invokedDirectly = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
+if (invokedDirectly) {
+ main().catch((err) => {
+ console.error(err.message || err);
+ process.exit(1);
+ });
+}
diff --git a/.skills/tinker-review/scripts/extraction/tree-sitter.js b/.skills/tinker-review/scripts/extraction/tree-sitter.js
new file mode 100644
index 0000000000..ba4dc9bd48
--- /dev/null
+++ b/.skills/tinker-review/scripts/extraction/tree-sitter.js
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { createRequire } from "node:module";
+const require = createRequire(import.meta.url);
+const TreeSitter = require("web-tree-sitter");
+import { readdir } from "node:fs/promises";
+import { readFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { join, relative } from "node:path";
+import { fileURLToPath } from "node:url";
+import { dirname } from "node:path";
+import { CHANGE_LEVEL, gradeMember, gradeFile } from "../graph/change-levels.js";
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+
+const LANGUAGE_EXTENSIONS = {
+ java: [".java"],
+ javascript: [".js", ".mjs", ".cjs"],
+ go: [".go"],
+ python: [".py"],
+ csharp: [".cs"],
+ dart: [".dart"],
+};
+
+const WASM_FILENAMES = {
+ java: "tree-sitter-java.wasm",
+ javascript: "tree-sitter-javascript.wasm",
+ go: "tree-sitter-go.wasm",
+ python: "tree-sitter-python.wasm",
+ csharp: "tree-sitter-c_sharp.wasm",
+ dart: "tree-sitter-dart.wasm",
+};
+
+const SKIP_DIRS = new Set([
+ "node_modules", "build", "target", ".git", ".gradle",
+ "dist", "out", "__pycache__", ".dart_tool", ".pub-cache",
+ "vendor", "bin", "obj",
+]);
+
+let initialized = false;
+
+async function ensureInit() {
+ if (!initialized) {
+ const wasmPath = join(__dirname, "..", "..", "node_modules", "web-tree-sitter", "tree-sitter.wasm");
+ await TreeSitter.init({ locateFile: () => wasmPath });
+ initialized = true;
+ }
+}
+
+async function loadLanguage(language) {
+ const wasmFile = WASM_FILENAMES[language];
+ if (!wasmFile) {
+ throw new Error(`Unsupported language: ${language}. Supported: ${Object.keys(WASM_FILENAMES).join(", ")}`);
+ }
+ const wasmPath = join(__dirname, "..", "..", "node_modules", "tree-sitter-wasms", "out", wasmFile);
+ return TreeSitter.Language.load(wasmPath);
+}
+
+async function walkDirectory(directory, extensions, changedSet) {
+ const files = [];
+
+ async function walk(dir) {
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) {
+ continue;
+ }
+ const fullPath = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ await walk(fullPath);
+ } else if (extensions.some((ext) => entry.name.endsWith(ext))) {
+ const relPath = relative(directory, fullPath);
+ files.push({
+ path: relPath,
+ fullPath,
+ changed: changedSet.has(relPath),
+ });
+ }
+ }
+ }
+
+ await walk(directory);
+ return files;
+}
+
+function isFunctionNode(node, language) {
+ const types = {
+ java: ["method_declaration", "constructor_declaration"],
+ go: ["function_declaration", "method_declaration"],
+ python: ["function_definition"],
+ javascript: ["function_declaration", "method_definition"],
+ csharp: ["method_declaration", "constructor_declaration"],
+ dart: ["method_signature", "function_signature"],
+ };
+ return (types[language] || []).includes(node.type);
+}
+
+function isTypeNode(node, language) {
+ const types = {
+ java: ["class_declaration", "interface_declaration", "enum_declaration"],
+ go: ["type_declaration"],
+ python: ["class_definition"],
+ javascript: ["class_declaration"],
+ csharp: ["class_declaration", "interface_declaration", "struct_declaration", "enum_declaration"],
+ dart: ["class_definition", "enum_declaration"],
+ };
+ return (types[language] || []).includes(node.type);
+}
+
+function isCallNode(node, language) {
+ const types = {
+ java: ["method_invocation"],
+ go: ["call_expression"],
+ python: ["call"],
+ javascript: ["call_expression"],
+ csharp: ["invocation_expression"],
+ dart: ["call_expression"],
+ };
+ return (types[language] || []).includes(node.type);
+}
+
+function isImportNode(node, language) {
+ const types = {
+ java: ["import_declaration"],
+ go: ["import_spec"],
+ python: ["import_statement", "import_from_statement"],
+ javascript: ["import_statement"],
+ csharp: ["using_directive"],
+ dart: ["import_or_export"],
+ };
+ return (types[language] || []).includes(node.type);
+}
+
+function childByType(node, type) {
+ for (let i = 0; i < node.childCount; i++) {
+ const child = node.child(i);
+ if (child.type === type) return child;
+ }
+ return null;
+}
+
+function childrenByType(node, type) {
+ const results = [];
+ for (let i = 0; i < node.childCount; i++) {
+ const child = node.child(i);
+ if (child.type === type) results.push(child);
+ }
+ return results;
+}
+
+function deepChildByType(node, type) {
+ if (node.type === type) return node;
+ for (let i = 0; i < node.childCount; i++) {
+ const result = deepChildByType(node.child(i), type);
+ if (result) return result;
+ }
+ return null;
+}
+
+function getVisibility(node, language) {
+ const modNode = childByType(node, "modifiers");
+ if (modNode) {
+ const text = modNode.text;
+ if (text.includes("private")) return "private";
+ if (text.includes("protected")) return "protected";
+ if (text.includes("internal")) return "internal";
+ return "public";
+ }
+
+ if (language === "go") {
+ const nameNode = childByType(node, "identifier") || childByType(node, "field_identifier") || childByType(node, "type_identifier");
+ if (nameNode) {
+ const name = nameNode.text;
+ return name[0] === name[0].toUpperCase() ? "public" : "private";
+ }
+ return "public";
+ }
+
+ if (language === "python") {
+ const nameNode = childByType(node, "identifier");
+ if (nameNode) {
+ const name = nameNode.text;
+ if (name.startsWith("__") && !name.endsWith("__")) return "private";
+ if (name.startsWith("_")) return "protected";
+ }
+ return "public";
+ }
+
+ return "public";
+}
+
+function extractFunctionName(node, language) {
+ if (language === "go" && node.type === "method_declaration") {
+ const fieldId = childByType(node, "field_identifier");
+ if (fieldId) return fieldId.text;
+ }
+
+ const nameNode = childByType(node, "identifier");
+ if (nameNode) return nameNode.text;
+
+ if (language === "javascript" && node.type === "method_definition") {
+ const propId = childByType(node, "property_identifier");
+ if (propId) return propId.text;
+ }
+
+ return null;
+}
+
+function extractSignature(node, language) {
+ const name = extractFunctionName(node, language);
+ if (!name) return null;
+
+ let params = "";
+ const paramNode = childByType(node, "formal_parameters")
+ || childByType(node, "parameter_list")
+ || childByType(node, "parameters")
+ || childByType(node, "formal_parameter_list");
+ if (paramNode) params = paramNode.text;
+
+ if (language === "go" && node.type === "method_declaration") {
+ const paramLists = childrenByType(node, "parameter_list");
+ const receiver = paramLists.length > 0 ? paramLists[0].text : "";
+ const funcParams = paramLists.length > 1 ? paramLists[1].text : "";
+ return `(${receiver}) ${name}${funcParams}`;
+ }
+
+ return `${name}${params}`;
+}
+
+function sha256(text) {
+ return createHash("sha256").update(text).digest("hex");
+}
+
+// Hash of a node's exact source text — distinguishes NONE (identical) from any
+// edit, including a pure reformat.
+function rawHash(node) {
+ return sha256(node.text);
+}
+
+// Hash of a node's leaf tokens with comment nodes skipped. tree-sitter does not
+// emit whitespace as tokens, so this is "code, minus formatting and comments":
+// two bodies with the same normHash differ only in whitespace/comments
+// (FORMATTING); differing normHash means the tokens themselves moved (BEHAVIORAL).
+function normHash(node) {
+ const tokens = [];
+ (function walk(n) {
+ if (n.type.includes("comment")) return;
+ if (n.childCount === 0) {
+ tokens.push(n.text);
+ return;
+ }
+ for (let i = 0; i < n.childCount; i++) walk(n.child(i));
+ })(node);
+ return sha256(tokens.join("\0"));
+}
+
+function extractFunctionsFromTree(tree, filePath, language) {
+ const functions = [];
+
+ function visit(node) {
+ if (isFunctionNode(node, language)) {
+ const name = extractFunctionName(node, language);
+ if (name) {
+ functions.push({
+ name,
+ signature: extractSignature(node, language) || name,
+ visibility: getVisibility(node, language),
+ filePath,
+ language,
+ linesStart: node.startPosition.row + 1,
+ linesEnd: node.endPosition.row + 1,
+ rawHash: rawHash(node),
+ normHash: normHash(node),
+ });
+ }
+ }
+ for (let i = 0; i < node.childCount; i++) {
+ visit(node.child(i));
+ }
+ }
+
+ visit(tree.rootNode);
+ return functions;
+}
+
+function inferTypeKind(node, language) {
+ const t = node.type;
+ if (t.includes("interface")) return "interface";
+ if (t.includes("struct")) return "struct";
+ if (t.includes("enum")) return "enum";
+ if (language === "go" && t === "type_declaration") {
+ const spec = childByType(node, "type_spec");
+ if (spec) {
+ for (let i = 0; i < spec.childCount; i++) {
+ const child = spec.child(i);
+ if (child.type === "interface_type") return "interface";
+ if (child.type === "struct_type") return "struct";
+ }
+ }
+ }
+ return "class";
+}
+
+function extractTypeName(node, language) {
+ if (language === "go" && node.type === "type_declaration") {
+ const spec = childByType(node, "type_spec");
+ if (spec) {
+ const typeId = childByType(spec, "type_identifier");
+ if (typeId) return typeId.text;
+ }
+ return null;
+ }
+ const nameNode = childByType(node, "identifier");
+ return nameNode ? nameNode.text : null;
+}
+
+// Reduce a type-reference node (possibly generic or dotted) to its simple name,
+// mirroring how calls resolve by simple name: `List<Foo>` -> "List",
+// `a.b.Bar` -> "Bar". Returns null for shapes we can't name.
+function baseTypeName(node) {
+ if (!node) return null;
+ if (node.type === "type_identifier" || node.type === "identifier") return node.text;
+ if (node.type === "scoped_type_identifier" || node.type === "qualified_name") {
+ let last = null;
+ for (let i = 0; i < node.childCount; i++) {
+ const c = node.child(i);
+ if (c.type === "type_identifier" || c.type === "identifier") last = c;
+ }
+ return last ? last.text : null;
+ }
+ if (node.type === "generic_type" || node.type === "generic_name") {
+ for (let i = 0; i < node.childCount; i++) {
+ const c = node.child(i);
+ const n = baseTypeName(c);
+ if (n) return n;
+ }
+ }
+ return null;
+}
+
+const TYPE_REF_NODES = new Set([
+ "type_identifier", "scoped_type_identifier", "generic_type",
+ "identifier", "qualified_name", "generic_name",
+]);
+
+// Collect the simple names of every type reference directly under a container
+// (e.g. a `super_interfaces`/`base_list`/`type_list` node).
+function typeNamesInContainer(container) {
+ if (!container) return [];
+ const list = childByType(container, "type_list") || container;
+ const names = [];
+ for (let i = 0; i < list.childCount; i++) {
+ const child = list.child(i);
+ if (TYPE_REF_NODES.has(child.type)) {
+ const n = baseTypeName(child);
+ if (n) names.push(n);
+ }
+ }
+ return names;
+}
+
+// Extract a type's declared supertypes as {name, relation} pairs, where relation
+// is "extends" (superclass / interface-extends-interface) or "implements"
+// (class-implements-interface). Java is split precisely; other languages emit a
+// best-effort "extends" for every base since their grammars don't cleanly
+// separate the two. Go has no inheritance, so it yields nothing.
+function extractSupertypes(node, language) {
+ const supers = [];
+ const push = (names, relation) => {
+ for (const name of names) supers.push({ name, relation });
+ };
+
+ if (language === "java") {
+ push(typeNamesInContainer(childByType(node, "superclass")), "extends");
+ push(typeNamesInContainer(childByType(node, "super_interfaces")), "implements");
+ // `interface A extends B` — an interface extending interfaces
+ push(typeNamesInContainer(childByType(node, "extends_interfaces")), "extends");
+ return supers;
+ }
+
+ if (language === "csharp") {
+ // `class C : Base, IFoo` — base_list mixes the superclass and interfaces
+ // with no grammatical distinction, so label them all "extends".
+ push(typeNamesInContainer(childByType(node, "base_list")), "extends");
+ return supers;
+ }
+
+ if (language === "javascript") {
+ const heritage = childByType(node, "class_heritage");
+ if (heritage) {
+ const id = deepChildByType(heritage, "identifier");
+ if (id) supers.push({ name: id.text, relation: "extends" });
+ }
+ return supers;
+ }
+
+ if (language === "python") {
+ const args = childByType(node, "argument_list");
+ if (args) push(typeNamesInContainer(args), "extends");
+ return supers;
+ }
+
+ if (language === "dart") {
+ const sup = childByType(node, "superclass");
+ if (sup) push(typeNamesInContainer(sup), "extends");
+ const interfaces = childByType(node, "interfaces");
+ if (interfaces) push(typeNamesInContainer(interfaces), "implements");
+ return supers;
+ }
+
+ return supers;
+}
+
+// The function names declared anywhere inside a type node. Used only to build a
+// type's structural signature, so over-inclusion (e.g. a nested type's methods)
+// is harmless as long as it is consistent between the base and head parse.
+function declaredMemberNames(typeNode, language) {
+ const names = [];
+ (function walk(n) {
+ if (isFunctionNode(n, language)) {
+ const fname = extractFunctionName(n, language);
+ if (fname) names.push(fname);
+ }
+ for (let i = 0; i < n.childCount; i++) walk(n.child(i));
+ })(typeNode);
+ return names;
+}
+
+// A type's structural signature: its declaration surface. A change here (kind,
+// visibility, supertypes, or the set of declared members) is STRUCTURAL; a
+// change to method bodies only leaves it stable and grades FORMATTING/BEHAVIORAL.
+function typeSignature(node, language, kind, visibility, supertypes) {
+ const supers = supertypes.map((s) => `${s.relation}:${s.name}`).sort().join(",");
+ const members = declaredMemberNames(node, language).sort().join(",");
+ return `${kind}|${visibility}|extends[${supers}]|members[${members}]`;
+}
+
+function extractTypesFromTree(tree, filePath, language) {
+ const types = [];
+
+ function visit(node) {
+ if (isTypeNode(node, language)) {
+ const name = extractTypeName(node, language);
+ if (name) {
+ const kind = inferTypeKind(node, language);
+ const visibility = getVisibility(node, language);
+ const supertypes = extractSupertypes(node, language);
+ types.push({
+ name,
+ kind,
+ visibility,
+ filePath,
+ language,
+ supertypes,
+ signature: typeSignature(node, language, kind, visibility, supertypes),
+ rawHash: rawHash(node),
+ normHash: normHash(node),
+ });
+ }
+ }
+ for (let i = 0; i < node.childCount; i++) {
+ visit(node.child(i));
+ }
+ }
+
+ visit(tree.rootNode);
+ return types;
+}
+
+// Which type declares each function, for `declares` (Type -> Function) edges.
+// Walks the tree carrying the innermost enclosing type so a method maps to the
+// class/interface whose body it sits in (both keyed within the same file).
+function extractDeclaresFromTree(tree, filePath, language) {
+ const declares = [];
+
+ function visit(node, enclosingType) {
+ let currentType = enclosingType;
+ if (isTypeNode(node, language)) {
+ currentType = extractTypeName(node, language) || enclosingType;
+ } else if (isFunctionNode(node, language) && enclosingType) {
+ const fname = extractFunctionName(node, language);
+ if (fname) declares.push({ typeName: enclosingType, functionName: fname, filePath });
+ }
+ for (let i = 0; i < node.childCount; i++) {
+ visit(node.child(i), currentType);
+ }
+ }
+
+ visit(tree.rootNode, null);
+ return declares;
+}
+
+function extractCalleeName(node, language) {
+ if (language === "java") {
+ const nameNode = childByType(node, "identifier");
+ return nameNode ? nameNode.text : null;
+ }
+
+ if (language === "go") {
+ const firstChild = node.child(0);
+ if (!firstChild) return null;
+ if (firstChild.type === "identifier") return firstChild.text;
+ if (firstChild.type === "selector_expression") {
+ const field = childByType(firstChild, "field_identifier");
+ return field ? field.text : null;
+ }
+ return null;
+ }
+
+ if (language === "python") {
+ const firstChild = node.child(0);
+ if (!firstChild) return null;
+ if (firstChild.type === "identifier") return firstChild.text;
+ if (firstChild.type === "attribute") {
+ const attr = childByType(firstChild, "identifier");
+ return attr ? attr.text : null;
+ }
+ return null;
+ }
+
+ if (language === "javascript" || language === "csharp" || language === "dart") {
+ const firstChild = node.child(0);
+ if (!firstChild) return null;
+ if (firstChild.type === "identifier") return firstChild.text;
+ if (firstChild.type === "member_expression" || firstChild.type === "member_access_expression") {
+ const prop = childByType(firstChild, "property_identifier") || childByType(firstChild, "identifier");
+ return prop ? prop.text : null;
+ }
+ const id = deepChildByType(firstChild, "identifier");
+ return id ? id.text : null;
+ }
+
+ return null;
+}
+
+function findEnclosingFunction(line, functionRanges) {
+ for (const fn of functionRanges) {
+ if (line >= fn.linesStart && line <= fn.linesEnd) {
+ return fn.name;
+ }
+ }
+ return null;
+}
+
+function extractCallsFromTree(tree, filePath, language, functionRanges) {
+ const calls = [];
+
+ function visit(node) {
+ if (isCallNode(node, language)) {
+ const calleeName = extractCalleeName(node, language);
+ if (calleeName) {
+ const line = node.startPosition.row + 1;
+ calls.push({
+ callerName: findEnclosingFunction(line, functionRanges) || "<module>",
+ callerFile: filePath,
+ calleeName,
+ language,
+ line,
+ });
+ }
+ }
+ for (let i = 0; i < node.childCount; i++) {
+ visit(node.child(i));
+ }
+ }
+
+ visit(tree.rootNode);
+ return calls;
+}
+
+function extractImportInfo(node, filePath, language) {
+ if (language === "java") {
+ const scopedId = childByType(node, "scoped_identifier");
+ if (!scopedId) return null;
+ const path = scopedId.text;
+ const parts = path.split(".");
+ return { filePath, importedPath: path, importedName: parts[parts.length - 1] };
+ }
+
+ if (language === "go") {
+ const pathNode = childByType(node, "interpreted_string_literal");
+ if (!pathNode) return null;
+ const path = pathNode.text.replace(/"/g, "");
+ const parts = path.split("/");
+ return { filePath, importedPath: path, importedName: parts[parts.length - 1] };
+ }
+
+ if (language === "python") {
+ if (node.type === "import_from_statement") {
+ const dotted = childByType(node, "dotted_name");
+ if (!dotted) return null;
+ return { filePath, importedPath: dotted.text, importedName: "*" };
+ }
+ const dotted = childByType(node, "dotted_name");
+ if (!dotted) return null;
+ return { filePath, importedPath: dotted.text, importedName: dotted.text };
+ }
+
+ if (language === "javascript") {
+ const srcNode = childByType(node, "string");
+ if (!srcNode) return null;
+ const path = srcNode.text.replace(/['"]/g, "");
+ return { filePath, importedPath: path, importedName: "*" };
+ }
+
+ if (language === "csharp") {
+ const qName = childByType(node, "qualified_name") || childByType(node, "identifier");
+ if (!qName) return null;
+ const path = qName.text;
+ const parts = path.split(".");
+ return { filePath, importedPath: path, importedName: parts[parts.length - 1] };
+ }
+
+ if (language === "dart") {
+ const strLit = deepChildByType(node, "string_literal");
+ if (!strLit) return null;
+ const path = strLit.text.replace(/['"]/g, "");
+ const parts = path.split("/");
+ const name = parts[parts.length - 1].replace(".dart", "");
+ return { filePath, importedPath: path, importedName: name };
+ }
+
+ return null;
+}
+
+function extractImportsFromTree(tree, filePath, language) {
+ const imports = [];
+
+ function visit(node) {
+ if (isImportNode(node, language)) {
+ const info = extractImportInfo(node, filePath, language);
+ if (info) imports.push(info);
+ }
+ for (let i = 0; i < node.childCount; i++) {
+ visit(node.child(i));
+ }
+ }
+
+ visit(tree.rootNode);
+ return imports;
+}
+
+function isTestFile(filePath, language) {
+ switch (language) {
+ case "java":
+ return filePath.includes("src/test/") || filePath.endsWith("Test.java");
+ case "go":
+ return filePath.endsWith("_test.go");
+ case "python":
+ return /(?:^|\/|\\)test_[^/\\]*\.py$/.test(filePath);
+ case "dart":
+ return filePath.includes("_test.dart") || filePath.includes("/test/");
+ case "javascript":
+ return filePath.includes(".test.") || filePath.includes(".spec.") || filePath.includes("/test/");
+ case "csharp":
+ return filePath.includes("Test") && filePath.includes("/Tests/");
+ default:
+ return false;
+ }
+}
+
+function classifyTestType(filePath, language) {
+ if (language === "java" && filePath.includes("src/test/")) {
+ if (filePath.toLowerCase().includes("integration")) return "integration";
+ return "unit";
+ }
+ return "unit";
+}
+
+// A canonical key for a file's import set, so a change to what it imports (a
+// dependency-surface move) can be detected between base and head.
+function importSetKey(imports) {
+ return imports
+ .map((i) => `${i.importedPath || ""}::${i.importedName || ""}`)
+ .sort()
+ .join("|");
+}
+
+// Grade each head member against the base version, matching by name and
+// disambiguating overloads by signature. Returns levels aligned to `headMembers`.
+function gradeMembersAgainstBase(headMembers, baseMembers) {
+ const baseByName = new Map();
+ for (const b of baseMembers) {
+ if (!baseByName.has(b.name)) baseByName.set(b.name, []);
+ baseByName.get(b.name).push(b);
+ }
+ return headMembers.map((h) => {
+ const candidates = baseByName.get(h.name);
+ if (!candidates || candidates.length === 0) return CHANGE_LEVEL.STRUCTURAL;
+ // Prefer an exact-signature match; if the name is unique fall back to it so a
+ // signature change grades STRUCTURAL rather than "added". An ambiguous
+ // overload with no signature match means the overload set moved — STRUCTURAL.
+ let base = candidates.find((b) => b.signature === h.signature);
+ if (!base) base = candidates.length === 1 ? candidates[0] : null;
+ if (!base) return CHANGE_LEVEL.STRUCTURAL;
+ return gradeMember(base, h);
+ });
+}
+
+// Parse one source file and append everything it yields to `result`, stamping a
+// `changeLevel` on the file and each member. Shared by the changed-file pass and
+// the hierarchy-neighborhood pass; context files (`file.changed === false`) are
+// unchanged by the PR and grade NONE. A changed file is graded against its base
+// version from `baseContents`; a changed file with no base entry was added by
+// the PR and grades STRUCTURAL.
+function parseSourceFile(parser, file, language, result, baseContents = {}) {
+ let content;
+ try {
+ content = readFileSync(file.fullPath, "utf-8");
+ } catch (err) {
+ // A file in the PR's changed set that isn't on disk was deleted by the PR —
+ // there's no source to extract, so skip it rather than crash.
+ if (err.code === "ENOENT") return;
+ throw err;
+ }
+ const tree = parser.parse(content);
+ if (!tree) return;
+
+ const fileFunctions = extractFunctionsFromTree(tree, file.path, language);
+ const fileTypes = extractTypesFromTree(tree, file.path, language);
+ const fileImports = extractImportsFromTree(tree, file.path, language);
+
+ let fileLevel;
+ if (!file.changed) {
+ fileLevel = CHANGE_LEVEL.NONE;
+ for (const fn of fileFunctions) fn.changeLevel = CHANGE_LEVEL.NONE;
+ for (const t of fileTypes) t.changeLevel = CHANGE_LEVEL.NONE;
+ } else if (Object.prototype.hasOwnProperty.call(baseContents, file.path)) {
+ const baseContent = baseContents[file.path];
+ const baseTree = parser.parse(baseContent);
+ const baseFunctions = baseTree ? extractFunctionsFromTree(baseTree, file.path, language) : [];
+ const baseTypes = baseTree ? extractTypesFromTree(baseTree, file.path, language) : [];
+ const baseImports = baseTree ? extractImportsFromTree(baseTree, file.path, language) : [];
+ if (baseTree) baseTree.delete();
+
+ const fnLevels = gradeMembersAgainstBase(fileFunctions, baseFunctions);
+ fileFunctions.forEach((fn, i) => { fn.changeLevel = fnLevels[i]; });
+ const typeLevels = gradeMembersAgainstBase(fileTypes, baseTypes);
+ fileTypes.forEach((t, i) => { t.changeLevel = typeLevels[i]; });
+
+ fileLevel = gradeFile({
+ memberLevels: [...fnLevels, ...typeLevels],
+ importExportChanged: importSetKey(fileImports) !== importSetKey(baseImports),
+ rawFileChanged: sha256(content) !== sha256(baseContent),
+ });
+ } else {
+ fileLevel = CHANGE_LEVEL.STRUCTURAL;
+ for (const fn of fileFunctions) fn.changeLevel = CHANGE_LEVEL.STRUCTURAL;
+ for (const t of fileTypes) t.changeLevel = CHANGE_LEVEL.STRUCTURAL;
+ }
+
+ result.files.push({ path: file.path, language, changeLevel: fileLevel });
+ result.functions.push(...fileFunctions);
+ result.types.push(...fileTypes);
+ result.declares.push(...extractDeclaresFromTree(tree, file.path, language));
+
+ const fileCalls = extractCallsFromTree(tree, file.path, language, fileFunctions);
+ result.calls.push(...fileCalls);
+ result.imports.push(...fileImports);
+
+ if (isTestFile(file.path, language)) {
+ for (const fn of fileFunctions) {
+ result.tests.push({
+ name: fn.name,
+ type: classifyTestType(file.path, language),
+ filePath: file.path,
+ language,
+ calledFunctions: fileCalls.filter((c) => c.callerName === fn.name).map((c) => c.calleeName),
+ });
+ }
+ }
+
+ tree.delete();
+}
+
+// Approximate, regex-based scan of one file's text for type declarations and the
+// type names they reference in a supertype position. Deliberately NOT tree-sitter:
+// this only SELECTS which files the neighborhood pass should accurately parse, so
+// over- or under-inclusion costs at most a few extra/missing parses — never a
+// wrong edge. Go is skipped (no inheritance).
+function scanTypeHeaders(text, language) {
+ const decls = [];
+ const refs = [];
+ if (language === "go") return { decls, refs };
+
+ const declRe = /\b(?:class|interface|enum|struct|trait|record)\s+([A-Za-z_]\w*)/g;
+ let m;
+ while ((m = declRe.exec(text)) !== null) {
+ decls.push(m[1]);
+ // Header = from the declared name to the body opener (`{`), bounded so a
+ // brace-less declaration (Python) can't swallow the whole file.
+ const rest = text.slice(m.index + m[0].length);
+ const brace = rest.indexOf("{");
+ const nl = rest.indexOf("\n");
+ let end = brace === -1 ? rest.length : brace;
+ if (language === "python" && nl !== -1) end = Math.min(end, nl);
+ end = Math.min(end, 300);
+ for (const r of rest.slice(0, end).match(/\b[A-Z]\w*/g) || []) {
+ if (r !== m[1]) refs.push(r);
+ }
+ }
+ return { decls, refs };
+}
+
+/**
+ * Find the type-hierarchy neighborhood of the changed types on disk: files that
+ * must also be parsed so override/hierarchy edges don't undercount. Two bounded
+ * BFS walks over a cheap regex index of the worktree:
+ *
+ * - Downward: files declaring a type that extends/implements a changed type
+ * (transitively) — the overriders an interface change actually affects.
+ * - Upward: files declaring a changed type's supertypes, to the root — so a
+ * changed subclass resolves its overrides against real ancestor methods
+ * instead of empty external stubs.
+ *
+ * Returns relative paths to parse as context (changed:false), capped so a change
+ * to a very central type can't drag in the whole module.
+ */
+async function hierarchyNeighborhood(directory, extensions, language, changedTypes, changedPaths, opts = {}) {
+ const maxDepth = opts.maxDepth ?? 6;
+ const maxFiles = opts.maxFiles ?? 250;
+
+ const all = await walkDirectory(directory, extensions, new Set());
+ const index = [];
+ for (const f of all) {
+ if (changedPaths.has(f.path)) continue;
+ let text;
+ try { text = readFileSync(f.fullPath, "utf-8"); } catch { continue; }
+ const { decls, refs } = scanTypeHeaders(text, language);
+ if (decls.length === 0) continue;
+ index.push({ path: f.path, fullPath: f.fullPath, decls: new Set(decls), refs: new Set(refs) });
+ }
+
+ const included = new Set();
+ const include = (entry) => {
+ included.add(entry.path);
+ return included.size >= maxFiles;
+ };
+
+ // Downward: who subtypes a frontier type.
+ let downFrontier = new Set(changedTypes.map((t) => t.name));
+ const downSeen = new Set(downFrontier);
+ for (let d = 0; d < maxDepth && downFrontier.size; d++) {
+ const next = new Set();
+ for (const entry of index) {
+ if (included.has(entry.path)) continue;
+ let hit = false;
+ for (const r of entry.refs) if (downFrontier.has(r)) { hit = true; break; }
+ if (!hit) continue;
+ if (include(entry)) return { files: [...included], truncated: true };
+ for (const dn of entry.decls) if (!downSeen.has(dn)) { downSeen.add(dn); next.add(dn); }
+ }
+ downFrontier = next;
+ }
+
+ // Upward: declarers of a frontier supertype, following their own supertypes up.
+ let upFrontier = new Set();
+ for (const t of changedTypes) for (const s of (t.supertypes || [])) upFrontier.add(s.name);
+ const upSeen = new Set(upFrontier);
+ for (let d = 0; d < maxDepth && upFrontier.size; d++) {
+ const next = new Set();
+ for (const entry of index) {
+ if (included.has(entry.path)) continue;
+ let hit = false;
+ for (const dn of entry.decls) if (upFrontier.has(dn)) { hit = true; break; }
+ if (!hit) continue;
+ if (include(entry)) return { files: [...included], truncated: true };
+ for (const r of entry.refs) if (!upSeen.has(r)) { upSeen.add(r); next.add(r); }
+ }
+ upFrontier = next;
+ }
+
+ return { files: [...included], truncated: false };
+}
+
+/**
+ * Parse source files in a directory using Tree-sitter.
+ * Returns structured extraction data for graph population.
+ *
+ * @param {string} directory - Absolute path to the PR worktree
+ * @param {string} language - Primary language to parse (e.g., "dart")
+ * @param {object} options
+ * @param {string[]} [options.changedFiles] - List of files changed in PR (relative paths)
+ * @param {boolean} [options.expandHierarchy] - Pull in the type-hierarchy
+ * neighborhood of changed types so override/hierarchy edges don't undercount
+ * (default: true, only applies in changed-files mode)
+ * @returns {Promise<ExtractionResult>}
+ */
+export async function extract(directory, language, options = {}) {
+ const changedFiles = options.changedFiles || [];
+ const changedSet = new Set(changedFiles);
+ const baseContents = options.baseContents || {};
+
+ const extensions = LANGUAGE_EXTENSIONS[language];
+ if (!extensions) {
+ throw new Error(`Unsupported language: ${language}. Supported: ${Object.keys(LANGUAGE_EXTENSIONS).join(", ")}`);
+ }
+
+ await ensureInit();
+ const lang = await loadLanguage(language);
+ const parser = new TreeSitter();
+ parser.setLanguage(lang);
+
+ let sourceFiles;
+ if (changedFiles.length > 0) {
+ sourceFiles = changedFiles
+ .filter(f => extensions.some(ext => f.endsWith(ext)))
+ .map(f => ({ path: f, fullPath: join(directory, f), changed: true }));
+ } else {
+ sourceFiles = await walkDirectory(directory, extensions, changedSet);
+ }
+
+ const result = {
+ language,
+ files: [],
+ functions: [],
+ types: [],
+ calls: [],
+ imports: [],
+ tests: [],
+ declares: [],
+ };
+
+ for (const file of sourceFiles) {
+ parseSourceFile(parser, file, language, result, baseContents);
+ }
+
+ // Hierarchy-neighborhood expansion: in changed-files mode the graph only holds
+ // PR-touched files, so a changed interface's overriders (and a changed
+ // subclass's ancestors) live in unparsed files — override/hierarchy edges
+ // would undercount. Pull those neighborhood files in as context (changed:false)
+ // so the edges resolve against real vertices instead of empty external stubs.
+ const expandHierarchy = options.expandHierarchy !== false;
+ if (expandHierarchy && changedFiles.length > 0 && result.types.length > 0) {
+ const changedPaths = new Set(sourceFiles.map((f) => f.path));
+ const changedTypes = result.types.slice();
+ const { files: extraPaths, truncated } = await hierarchyNeighborhood(
+ directory, extensions, language, changedTypes, changedPaths,
+ );
+ for (const relPath of extraPaths) {
+ parseSourceFile(parser, { path: relPath, fullPath: join(directory, relPath), changed: false }, language, result);
+ }
+ result.hierarchyNeighborhood = { files: extraPaths.length, truncated };
+ }
+
+ parser.delete();
+ return result;
+}
+
+/**
+ * Extract every language a PR touches into one merged result. Each language is
+ * parsed independently (own parser, own hierarchy-neighborhood pass) and the
+ * records — already stamped with `language` — are concatenated. This is what
+ * makes the graph multi-language; population then keeps by-name edges scoped to
+ * a single language so no spurious cross-language edges are invented.
+ *
+ * @param {string} directory - Absolute path to the PR worktree
+ * @param {string[]} languages - Languages to parse (e.g., ["java", "python"])
+ * @param {object} [options] - Passed through to `extract` (e.g., changedFiles)
+ * @returns {Promise<ExtractionResult>} merged result; `languages` lists what was parsed
+ */
+export async function extractMulti(directory, languages, options = {}) {
+ const merged = {
+ languages: [],
+ files: [], functions: [], types: [], calls: [], imports: [], tests: [], declares: [],
+ hierarchyNeighborhood: { files: 0, truncated: false },
+ };
+
+ for (const language of languages) {
+ if (!LANGUAGE_EXTENSIONS[language]) continue;
+ const one = await extract(directory, language, options);
+ merged.languages.push(language);
+ for (const key of ["files", "functions", "types", "calls", "imports", "tests", "declares"]) {
+ merged[key].push(...one[key]);
+ }
+ if (one.hierarchyNeighborhood) {
+ merged.hierarchyNeighborhood.files += one.hierarchyNeighborhood.files;
+ merged.hierarchyNeighborhood.truncated ||= one.hierarchyNeighborhood.truncated;
+ }
+ }
+
+ return merged;
+}
diff --git a/.skills/tinker-review/scripts/functional/cli.js b/.skills/tinker-review/scripts/functional/cli.js
new file mode 100644
index 0000000000..7d8006418c
--- /dev/null
+++ b/.skills/tinker-review/scripts/functional/cli.js
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Thin CLI over functional/setup.js so SKILL.md step 4 can drive the mechanical
+// build+start from one command, the way enrichment/cli.js drives the graph.
+// Reads session.json from --workDir for the pr/repo, prints the server handle as
+// JSON, and persists it to functional.json so `stop` can find it later.
+//
+// node scripts/functional/cli.js start --workDir /tmp/pr-review-<pr>
+// node scripts/functional/cli.js stop --workDir /tmp/pr-review-<pr>
+
+import { readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { buildAndStart, stop } from "./setup.js";
+
+function parseArgs(argv) {
+ // A leading `--flag` means no subcommand was given (e.g. `--help`).
+ const command = argv[0] && !argv[0].startsWith("--") ? argv[0] : undefined;
+ const opts = {};
+ for (let i = command ? 1 : 0; i < argv.length; i++) {
+ if (argv[i].startsWith("--")) {
+ const key = argv[i].slice(2);
+ const val = argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[++i] : true;
+ opts[key] = val;
+ }
+ }
+ return { command, opts };
+}
+
+async function readSession(workDir) {
+ return JSON.parse(await readFile(join(workDir, "session.json"), "utf-8"));
+}
+
+async function main() {
+ const { command, opts } = parseArgs(process.argv.slice(2));
+ const workDir = opts.workDir;
+
+ if (!command || opts.help) {
+ process.stdout.write(
+ "Usage:\n" +
+ " cli.js start --workDir <dir> [--port <n>] build the PR and start the functional server\n" +
+ " cli.js stop --workDir <dir> stop it and remove the build worktree\n",
+ );
+ return;
+ }
+ if (!workDir) throw new Error("--workDir is required");
+
+ const session = await readSession(workDir);
+ const handlePath = join(workDir, "functional.json");
+
+ if (command === "start") {
+ const handle = await buildAndStart(workDir, {
+ pr: session.pr,
+ repoPath: session.repoPath,
+ port: opts.port ? Number(opts.port) : undefined,
+ });
+ await writeFile(handlePath, JSON.stringify(handle, null, 2));
+ process.stdout.write(JSON.stringify(handle, null, 2) + "\n");
+ return;
+ }
+
+ if (command === "stop") {
+ const handle = JSON.parse(await readFile(handlePath, "utf-8").catch(() => "null"));
+ if (handle) await stop(handle, { repoPath: session.repoPath });
+ process.stdout.write(JSON.stringify({ stopped: Boolean(handle) }) + "\n");
+ return;
+ }
+
+ throw new Error(`Unknown command: ${command}`);
+}
+
+main().catch((err) => {
+ process.stderr.write(`${err.message}\n`);
+ process.exit(1);
+});
diff --git a/.skills/tinker-review/scripts/functional/setup.js b/.skills/tinker-review/scripts/functional/setup.js
new file mode 100644
index 0000000000..33a633856b
--- /dev/null
+++ b/.skills/tinker-review/scripts/functional/setup.js
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Mechanical setup for Phase-2 functional testing: build the PR from source and
+// stand up a Gremlin Server from the freshly built assembly, so a blind subagent
+// can exercise the change as a user would. This is the reproducible half of
+// step 4 — the judgment (what to test) lives in the playbooks' Verify sections.
+//
+// Distinct from infrastructure/docker.js, which runs the STOCK published image
+// for the Phase-1 knowledge graph. Functional testing must run the PR's OWN
+// compiled code, so it builds and launches natively from `target/`.
+//
+// The build worktree is separate from the enrichment worktree (`<workDir>/src`)
+// so Maven's `target/` output never pollutes the tree the agent reads during
+// enrichment.
+
+import { execFile, spawn } from "node:child_process";
+import { promisify } from "node:util";
+import { mkdir, writeFile, readdir } from "node:fs/promises";
+import { join } from "node:path";
+import { existsSync } from "node:fs";
+import { createWriteStream } from "node:fs";
+
+import { findAvailablePort, waitForHttp } from "../infrastructure/net.js";
+
+const exec = promisify(execFile);
+
+const DEFAULT_BUILD_TIMEOUT_MS = 30 * 60 * 1000; // full reactor build is slow
+const DEFAULT_READY_TIMEOUT_MS = 60 * 1000; // native JVM start + graph load
+
+// TinkerGraph config for the functional server. Mirrors the stock empty graph.
+const GRAPH_PROPERTIES = `gremlin.graph=org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph
+gremlin.tinkergraph.vertexIdManager=LONG
+`;
+
+// Init script binding the two traversal sources the reviewer may need — kept in
+// lockstep with docker.js's INIT_GROOVY so both servers expose the same surface:
+// 'g' — standard traversal
+// 'a' — withComputer() for OLAP steps like connectedComponent()
+const INIT_GROOVY = `def globals = [:]
+globals << [g : traversal().withEmbedded(graph)]
+globals << [a : traversal().withEmbedded(graph).withComputer()]
+`;
+
+/**
+ * Build a self-contained server yaml for the functional test. Based on the
+ * project's shipped default (HttpChannelizer + GraphSON V4 / GraphBinary V4)
+ * with host/port pinned and the g/a bindings wired via an init script. Written
+ * fresh rather than parsed from the assembly so there is no YAML dependency and
+ * no textual patching of the shipped file.
+ */
+function serverYaml(port) {
+ return `host: localhost
+port: ${port}
+timeoutMillis: 30000
+channelizer: org.apache.tinkerpop.gremlin.server.channel.HttpChannelizer
+graphs: {
+ graph: conf/tinkergraph-review.properties}
+scriptEngines: {
+ gremlin-lang: {},
+ gremlin-groovy: {
+ plugins: { org.apache.tinkerpop.gremlin.server.jsr223.GremlinServerGremlinPlugin: {},
+ org.apache.tinkerpop.gremlin.jsr223.ImportGremlinPlugin: {classImports: [java.lang.Math], methodImports: [java.lang.Math#*]},
+ org.apache.tinkerpop.gremlin.jsr223.ScriptFileGremlinPlugin: {files: [scripts/review-init.groovy]}}}}
+serializers:
+ - { className: org.apache.tinkerpop.gremlin.util.ser.GraphSONMessageSerializerV4, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3] }}
+ - { className: org.apache.tinkerpop.gremlin.util.ser.GraphBinaryMessageSerializerV4 }
+ - { className: org.apache.tinkerpop.gremlin.util.ser.GraphBinaryMessageSerializerV4, config: { serializeResultToString: true }}
+metrics: {
+ slf4jReporter: {enabled: true, interval: 180000}}
+strictTransactionManagement: false
+`;
+}
+
+/**
+ * Locate the built standalone server assembly under the build worktree. The
+ * assembly directory carries the project version in its name, so it is globbed
+ * rather than hard-coded.
+ *
+ * @param {string} buildWorktree
+ * @returns {Promise<string>} absolute path to the *-standalone directory
+ */
+async function findAssembly(buildWorktree) {
+ const targetDir = join(buildWorktree, "gremlin-server", "target");
+ if (!existsSync(targetDir)) {
+ throw new Error(`No gremlin-server/target under ${buildWorktree} — did the build succeed?`);
+ }
+ const entries = await readdir(targetDir);
+ const match = entries.find(
+ (e) => e.startsWith("apache-tinkerpop-gremlin-server-") && e.endsWith("-standalone"),
+ );
+ if (!match) {
+ throw new Error(`No *-standalone assembly in ${targetDir} (found: ${entries.join(", ") || "nothing"})`);
+ }
+ return join(targetDir, match);
+}
+
+/**
+ * @typedef {object} FunctionalHandle
+ * @property {number} port - localhost port the server listens on
+ * @property {string} url - base HTTP endpoint (`http://localhost:<port>/gremlin`)
+ * @property {number} pid - PID of the server JVM (for teardown)
+ * @property {string} buildWorktree - the `<workDir>/build` worktree to remove on teardown
+ * @property {string} assemblyDir - the built `*-standalone` directory
+ * @property {string} logFile - server stdout/stderr log for diagnosis
+ */
+
+/**
+ * Build the PR and start a Gremlin Server from the built artifacts.
+ *
+ * Steps: add a `build` worktree on the PR branch → `mvn clean install
+ * -DskipTests` over the full reactor → locate the server assembly → write the
+ * TinkerGraph config + init script + yaml → launch `bin/gremlin-server.sh`
+ * natively on a free port → poll until ready.
+ *
+ * The caller (SKILL.md step 4) decides whether to run this at all, per the
+ * playbooks' Verify gate. Skipped changes never pay the build cost.
+ *
+ * @param {string} workDir - the review work dir, e.g. `/tmp/pr-review-<pr>`
+ * @param {object} opts
+ * @param {number} opts.pr - PR number (the branch is `pr-review/<pr>`)
+ * @param {string} opts.repoPath - the git repo the worktree is added against
+ * @param {number} [opts.port] - fixed port (default: an OS-assigned free port)
+ * @param {number} [opts.buildTimeoutMs]
+ * @param {number} [opts.readyTimeoutMs]
+ * @returns {Promise<FunctionalHandle>}
+ */
+export async function buildAndStart(workDir, opts) {
+ const { pr, repoPath } = opts;
+ if (!pr) throw new Error("buildAndStart requires opts.pr");
+ if (!repoPath) throw new Error("buildAndStart requires opts.repoPath");
+
+ const prBranch = `pr-review/${pr}`;
+ const buildWorktree = join(workDir, "build");
+
+ // Add the build worktree (idempotent — remove a stale one first).
+ if (existsSync(buildWorktree)) {
+ await exec("git", ["worktree", "remove", "--force", buildWorktree], { cwd: repoPath }).catch(() => {});
+ }
+ await exec("git", ["worktree", "prune"], { cwd: repoPath }).catch(() => {});
+ await exec("git", ["worktree", "add", buildWorktree, prBranch], { cwd: repoPath });
+
+ // Full-reactor build without tests, so every module reflects the PR.
+ await exec(
+ "mvn",
+ ["-f", join(buildWorktree, "pom.xml"), "clean", "install", "-DskipTests"],
+ { cwd: buildWorktree, timeout: opts.buildTimeoutMs || DEFAULT_BUILD_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 },
+ );
+
+ const assemblyDir = await findAssembly(buildWorktree);
+ const port = opts.port || await findAvailablePort();
+
+ // Write config into the assembly's conf/scripts dirs.
+ await mkdir(join(assemblyDir, "conf"), { recursive: true });
+ await mkdir(join(assemblyDir, "scripts"), { recursive: true });
+ await writeFile(join(assemblyDir, "conf", "tinkergraph-review.properties"), GRAPH_PROPERTIES);
+ await writeFile(join(assemblyDir, "scripts", "review-init.groovy"), INIT_GROOVY);
+ const yamlPath = join(assemblyDir, "conf", "gremlin-server-review.yaml");
+ await writeFile(yamlPath, serverYaml(port));
+
+ // Launch natively in the foreground ("console" mode reads the yaml arg via the
+ // catch-all case) and detach, capturing output to a log for diagnosis.
+ const logFile = join(workDir, "functional-server.log");
+ const out = createWriteStream(logFile);
+ await new Promise((resolve) => out.once("open", resolve));
+
+ const child = spawn(
+ join(assemblyDir, "bin", "gremlin-server.sh"),
+ [yamlPath],
+ { cwd: assemblyDir, stdio: ["ignore", out, out], detached: true },
+ );
+ child.unref();
+
+ const handle = { port, url: `http://localhost:${port}/gremlin`, pid: child.pid, buildWorktree, assemblyDir, logFile };
+
+ try {
+ await waitForHttp(port, opts.readyTimeoutMs || DEFAULT_READY_TIMEOUT_MS);
+ } catch (err) {
+ await stop(handle).catch(() => {});
+ throw new Error(`${err.message} — see ${logFile}`);
+ }
+
+ return handle;
+}
+
+/**
+ * Stop the functional server and remove its build worktree.
+ *
+ * @param {FunctionalHandle} handle
+ * @param {object} [opts]
+ * @param {string} [opts.repoPath] - repo to prune the worktree against (defaults to none)
+ * @returns {Promise<void>}
+ */
+export async function stop(handle, opts = {}) {
+ if (handle?.pid) {
+ try { process.kill(handle.pid, "SIGTERM"); } catch { /* already gone */ }
+ }
+ if (handle?.buildWorktree && opts.repoPath) {
+ await exec("git", ["worktree", "remove", "--force", handle.buildWorktree], { cwd: opts.repoPath }).catch(() => {});
+ await exec("git", ["worktree", "prune"], { cwd: opts.repoPath }).catch(() => {});
+ }
+}
diff --git a/.skills/tinker-review/scripts/graph/change-levels.js b/.skills/tinker-review/scripts/graph/change-levels.js
new file mode 100644
index 0000000000..97116f40b6
--- /dev/null
+++ b/.skills/tinker-review/scripts/graph/change-levels.js
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Change-level vocabulary. Every File, Function and Type vertex carries a
+ * `changeLevel` recording how much the PR moved it, computed by diffing the base
+ * version of each changed file against the PR-head version. It replaces the old
+ * boolean `changed` flag, which — being stamped per file — could not tell an
+ * untouched helper in a changed file from the code the PR actually rewrote.
+ *
+ * NONE — byte-identical to the base (untouched; also context /
+ * hierarchy-neighborhood files and external stubs).
+ * FORMATTING — only comments or whitespace moved; the tokens are identical.
+ * BEHAVIORAL — the body changed for real, but the signature is stable.
+ * STRUCTURAL — the signature/declaration changed, or the member/file was
+ * added or removed, or imports/exports changed.
+ *
+ * Risk checks (centrality, blast-radius, coverage-gaps) default to the two
+ * meaningful tiers (BEHAVIORAL, STRUCTURAL); inclusion-oriented checks (orphans,
+ * cluster-analysis, architecture) count anything that is not NONE.
+ */
+
+import gremlin from "gremlin";
+
+const { process: { P } } = gremlin;
+
+export const CHANGE_LEVEL = Object.freeze({
+ NONE: "NONE",
+ FORMATTING: "FORMATTING",
+ BEHAVIORAL: "BEHAVIORAL",
+ STRUCTURAL: "STRUCTURAL",
+});
+
+// Ascending severity. Index in this array is the rank used to combine levels.
+export const ORDER = Object.freeze([
+ CHANGE_LEVEL.NONE,
+ CHANGE_LEVEL.FORMATTING,
+ CHANGE_LEVEL.BEHAVIORAL,
+ CHANGE_LEVEL.STRUCTURAL,
+]);
+
+const RANK = new Map(ORDER.map((level, i) => [level, i]));
+
+const VALID = new Set(ORDER);
+
+export function isValidChangeLevel(value) {
+ return VALID.has(value);
+}
+
+/**
+ * Normalize a caller-supplied change level (e.g. a `--changeLevel` flag),
+ * upper-casing and falling back when missing or invalid.
+ *
+ * @param {string|undefined} value
+ * @param {string|null} [fallback=null]
+ * @returns {string|null}
+ */
+export function normalizeChangeLevel(value, fallback = null) {
+ if (typeof value === "string") {
+ const upper = value.toUpperCase();
+ if (VALID.has(upper)) return upper;
+ }
+ return fallback;
+}
+
+/**
+ * The most severe of the given levels (NONE if none supplied). Used to roll a
+ * file's members up into a single File.changeLevel.
+ *
+ * @param {...string} levels
+ * @returns {string}
+ */
+export function maxLevel(...levels) {
+ let best = CHANGE_LEVEL.NONE;
+ for (const level of levels) {
+ if (!VALID.has(level)) continue;
+ if (RANK.get(level) > RANK.get(best)) best = level;
+ }
+ return best;
+}
+
+/**
+ * True if `level` is at least as severe as `floor`.
+ *
+ * @param {string} level
+ * @param {string} floor
+ * @returns {boolean}
+ */
+export function atLeast(level, floor) {
+ return VALID.has(level) && VALID.has(floor) && RANK.get(level) >= RANK.get(floor);
+}
+
+/**
+ * @typedef {Object} MemberFingerprint
+ * @property {string} signature the member's signature (name+params for a
+ * function; kind+visibility+supertypes+member-set
+ * for a type)
+ * @property {string} rawHash hash of the member's exact source text
+ * @property {string} normHash hash of the member's leaf tokens, comments removed
+ */
+
+/**
+ * Grade one head member against its matched base member. A missing base member
+ * (no match by name/signature) is a new member — STRUCTURAL.
+ *
+ * @param {MemberFingerprint|null|undefined} base
+ * @param {MemberFingerprint} head
+ * @returns {string} a CHANGE_LEVEL value
+ */
+export function gradeMember(base, head) {
+ if (!base) return CHANGE_LEVEL.STRUCTURAL; // added member
+ if (base.rawHash === head.rawHash) return CHANGE_LEVEL.NONE;
+ if (base.signature !== head.signature) return CHANGE_LEVEL.STRUCTURAL;
+ if (base.normHash === head.normHash) return CHANGE_LEVEL.FORMATTING;
+ return CHANGE_LEVEL.BEHAVIORAL;
+}
+
+/**
+ * Roll a file's members and its import/export delta into a single File level.
+ * An import/export set change is STRUCTURAL (a dependency-surface change). If the
+ * raw file bytes differ but every member is NONE and imports are stable, the
+ * change is top-level trivia outside any member — a FORMATTING floor.
+ *
+ * @param {object} params
+ * @param {string[]} params.memberLevels changeLevel of every Function/Type in the file
+ * @param {boolean} params.importExportChanged whether the import/export set moved
+ * @param {boolean} params.rawFileChanged whether the file's raw bytes differ from base
+ * @returns {string} a CHANGE_LEVEL value
+ */
+export function gradeFile({ memberLevels = [], importExportChanged = false, rawFileChanged = false }) {
+ let level = maxLevel(...memberLevels);
+ if (importExportChanged) level = maxLevel(level, CHANGE_LEVEL.STRUCTURAL);
+ if (level === CHANGE_LEVEL.NONE && rawFileChanged) return CHANGE_LEVEL.FORMATTING;
+ return level;
+}
+
+// === Gremlin predicate helpers ===
+// Keep the "what counts as changed" definition here so every check filters the
+// same way rather than open-coding `within(...)`.
+
+/** Any real change — everything but NONE. Inclusion-oriented checks use this. */
+export function changedAny() {
+ return P.within(CHANGE_LEVEL.FORMATTING, CHANGE_LEVEL.BEHAVIORAL, CHANGE_LEVEL.STRUCTURAL);
+}
+
+/** Meaningful change — BEHAVIORAL or STRUCTURAL. Risk checks default to this. */
+export function changedMeaningful() {
+ return P.within(CHANGE_LEVEL.BEHAVIORAL, CHANGE_LEVEL.STRUCTURAL);
+}
+
+/**
+ * A predicate matching every level at least as severe as `floor`. Backs the
+ * `minChangeLevel` opt-in on centrality/blast-radius.
+ *
+ * @param {string} floor - a CHANGE_LEVEL value
+ * @returns {object} a gremlin P predicate
+ */
+export function atLeastP(floor) {
+ const from = RANK.has(floor) ? RANK.get(floor) : 1;
+ return P.within(...ORDER.slice(from));
+}
diff --git a/.skills/tinker-review/scripts/graph/confidence.js b/.skills/tinker-review/scripts/graph/confidence.js
new file mode 100644
index 0000000000..bb3076ceac
--- /dev/null
+++ b/.skills/tinker-review/scripts/graph/confidence.js
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Edge confidence vocabulary. Every edge written into the knowledge graph
+ * carries a `confidence` property so downstream analysis (and the human
+ * reviewer) can tell what was observed directly from source versus what was
+ * deduced or guessed.
+ *
+ * EXTRACTED — explicitly present in the source: an AST definition, a git
+ * diff fact, a discussion link stated in the PR body/diff, a
+ * comment returned by the issue API for its parent thread.
+ * INFERRED — a reasonable deduction: a call/test edge resolved by name
+ * match, a cross-referenced discussion, an agent's step or doc
+ * mapping backed by evidence.
+ * AMBIGUOUS — uncertain; surfaced for human review. Keyword-search matches
+ * and low-confidence agent guesses land here.
+ */
+export const CONFIDENCE = Object.freeze({
+ EXTRACTED: "EXTRACTED",
+ INFERRED: "INFERRED",
+ AMBIGUOUS: "AMBIGUOUS",
+});
+
+const VALID = new Set(Object.values(CONFIDENCE));
+
+export function isValidConfidence(value) {
+ return VALID.has(value);
+}
+
+/**
+ * Normalize a caller-supplied confidence value, falling back to a default when
+ * missing or invalid. Enrichment write commands use this so a bad `--confidence`
+ * flag degrades to a sane default rather than poisoning the graph.
+ *
+ * @param {string|undefined} value
+ * @param {string} [fallback=CONFIDENCE.INFERRED]
+ * @returns {string}
+ */
+export function normalizeConfidence(value, fallback = CONFIDENCE.INFERRED) {
+ if (typeof value === "string") {
+ const upper = value.toUpperCase();
+ if (VALID.has(upper)) return upper;
+ }
+ return fallback;
+}
+
+/**
+ * Map a discussion-link `found_in` provenance to a confidence level.
+ * A link stated in the PR body or diff is EXTRACTED; a cross-reference found in
+ * another discussion's body is INFERRED; a keyword-search hit is AMBIGUOUS.
+ *
+ * @param {string|undefined} foundIn
+ * @returns {string}
+ */
+export function confidenceForFoundIn(foundIn) {
+ switch (foundIn) {
+ case "pr":
+ case "diff":
+ return CONFIDENCE.EXTRACTED;
+ case "search":
+ return CONFIDENCE.AMBIGUOUS;
+ case "jira_body":
+ case "devlist_body":
+ return CONFIDENCE.INFERRED;
+ default:
+ return CONFIDENCE.INFERRED;
+ }
+}
diff --git a/.skills/tinker-review/scripts/graph/externals.js b/.skills/tinker-review/scripts/graph/externals.js
new file mode 100644
index 0000000000..01c6080e7c
--- /dev/null
+++ b/.skills/tinker-review/scripts/graph/externals.js
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Names that, when they show up as unresolved callees (external Function stubs),
+ * are almost certainly JDK / standard-library / ubiquitous-accessor calls rather
+ * than project functions. Classifying these as `library` lets structural checks
+ * (centrality, blast radius) drop the noise they'd otherwise inflate.
+ *
+ * Deliberately conservative: it lists object/collection/string/IO/logging/stream
+ * staples and common getX/isX accessors, and avoids ambiguous verbs (build,
+ * create, start, run, call…) that are just as likely to name a real project
+ * method. A false "library" on a genuinely ubiquitous name like `get` is
+ * acceptable; a false "library" on a distinctive project method is not.
+ */
+export const COMMON_LIBRARY_NAMES = new Set([
+ // java.lang.Object
+ "equals", "hashCode", "toString", "clone", "finalize", "getClass",
+ "wait", "notify", "notifyAll",
+ // Comparable / iterator
+ "compareTo", "iterator", "hasNext", "next", "remove",
+ // Collection / Map / List
+ "size", "isEmpty", "contains", "containsKey", "containsValue",
+ "add", "addAll", "get", "set", "put", "putAll", "clear", "remove",
+ "keySet", "values", "entrySet", "toArray", "stream", "getKey", "getValue",
+ // String / CharSequence
+ "length", "charAt", "substring", "trim", "split", "replace", "indexOf",
+ "startsWith", "endsWith", "matches", "toLowerCase", "toUpperCase",
+ "getBytes", "valueOf", "format",
+ // common accessors
+ "getName", "getId", "getType", "getMessage", "getValue", "getStatusCode",
+ "getCause", "getClassName", "name", "ordinal",
+ // IO / lifecycle
+ "close", "flush", "read", "write", "open",
+ // logging
+ "log", "info", "debug", "warn", "error", "trace", "printStackTrace",
+ "print", "println",
+ // Optional / functional / stream
+ "of", "empty", "orElse", "orElseGet", "orElseThrow", "ifPresent", "isPresent",
+ "forEach", "map", "filter", "collect", "count", "findFirst", "anyMatch",
+ "allMatch", "noneMatch", "apply", "accept", "test",
+]);
+
+/**
+ * @param {string} name
+ * @returns {boolean} true if the name is a well-known library/JDK/accessor call
+ */
+export function isLibraryName(name) {
+ return COMMON_LIBRARY_NAMES.has(name);
+}
+
+/**
+ * Origin classification for an external stub, given whether a project type with
+ * this name was found in the repo.
+ *
+ * library — a known JDK/standard-library/accessor name (noise)
+ * project — a project source file declares a type with this name (signal)
+ * unresolved — neither; unknown, treat with caution
+ *
+ * Method-name project detection isn't attempted (name-only grep can't tell a
+ * definition from a use reliably); that's the domain of precise resolution.
+ *
+ * @param {string} name
+ * @param {boolean} definedAsProjectType
+ * @returns {"library"|"project"|"unresolved"}
+ */
+export function classifyExternalName(name, definedAsProjectType) {
+ if (isLibraryName(name)) return "library";
+ if (definedAsProjectType) return "project";
+ return "unresolved";
+}
diff --git a/.skills/tinker-review/scripts/graph/populate-discussions.js b/.skills/tinker-review/scripts/graph/populate-discussions.js
new file mode 100644
index 0000000000..3dea9da566
--- /dev/null
+++ b/.skills/tinker-review/scripts/graph/populate-discussions.js
@@ -0,0 +1,305 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import gremlin from "gremlin";
+import { CONFIDENCE, confidenceForFoundIn } from "./confidence.js";
+
+const { process: { statics: __ } } = gremlin;
+
+const BATCH_SIZE = 50;
+
+async function submitBatch(batch) {
+ await Promise.allSettled(batch.map((t) => t.next()));
+}
+
+/**
+ * Populate TinkerGraph with discussion data from discoverDiscussions().
+ * Creates Discussion and Comment vertices plus has_comment, addresses,
+ * proposed_in, and modifies edges per the PR knowledge graph schema.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} discussions - Output from discoverDiscussions()
+ * @param {object} context
+ * @param {number} context.pr - PR number
+ * @param {string} context.prTitle - PR title
+ * @param {string[]} context.changedFiles - Files modified in the PR
+ * @returns {Promise<{vertices: number, edges: number, breakdown: object}>}
+ */
+export async function populateDiscussions(g, discussions, context) {
+ const counts = {
+ vertices: 0,
+ edges: 0,
+ breakdown: { discussions: 0, comments: 0, hasComment: 0, addresses: 0, proposedIn: 0, modifies: 0 },
+ };
+
+ const prUrl = `https://github.com/apache/tinkerpop/pull/${context.pr}`;
+
+ // Create the PR itself as a Discussion vertex. Idempotent: review.js may have
+ // already created it via createPrDiscussion(). A duplicate PR vertex would make
+ // `.V().has("url", prUrl)` match two start vertices and double every PR-sourced
+ // edge (modifies, addresses, has_comment).
+ const prExists = await g.V().hasLabel("Discussion").has("url", prUrl).hasNext();
+ if (!prExists) {
+ await g.addV("Discussion")
+ .property("url", prUrl)
+ .property("source", "pr")
+ .property("title", context.prTitle || `PR #${context.pr}`)
+ .property("body", "")
+ .next();
+ counts.vertices++;
+ counts.breakdown.discussions++;
+ }
+
+ // Create Discussion vertices for JIRAs
+ for (const jira of discussions.jiras) {
+ await g.addV("Discussion")
+ .property("url", jira.url)
+ .property("source", "jira")
+ .property("title", jira.title)
+ .property("body", (jira.body || "").slice(0, 2000))
+ .next();
+ counts.vertices++;
+ counts.breakdown.discussions++;
+
+ // Create Comment vertices for JIRA comments
+ for (const comment of (jira.comments || [])) {
+ await g.addV("Comment")
+ .property("author", comment.author)
+ .property("body", comment.body)
+ .property("timestamp", comment.timestamp || "")
+ .next();
+ counts.vertices++;
+ counts.breakdown.comments++;
+ }
+ }
+
+ // Create Discussion vertices for dev list threads
+ for (const thread of discussions.devList) {
+ await g.addV("Discussion")
+ .property("url", thread.url)
+ .property("source", "devlist")
+ .property("title", thread.title)
+ .property("body", (thread.body || "").slice(0, 2000))
+ .next();
+ counts.vertices++;
+ counts.breakdown.discussions++;
+ }
+
+ // Create Discussion vertices for secondary (cross-referenced) discussions
+ for (const sec of (discussions.secondary || [])) {
+ await g.addV("Discussion")
+ .property("url", sec.url)
+ .property("source", sec.source)
+ .property("title", sec.title || "")
+ .property("body", (sec.body || "").slice(0, 2000))
+ .next();
+ counts.vertices++;
+ counts.breakdown.discussions++;
+
+ for (const comment of (sec.comments || [])) {
+ await g.addV("Comment")
+ .property("author", comment.author)
+ .property("body", comment.body)
+ .property("timestamp", comment.timestamp || "")
+ .next();
+ counts.vertices++;
+ counts.breakdown.comments++;
+ }
+ }
+
+ // Create Comment vertices for PR issue comments
+ for (const comment of (discussions.prComments?.issue || [])) {
+ await g.addV("Comment")
+ .property("author", comment.author)
+ .property("body", comment.body)
+ .property("timestamp", comment.timestamp || "")
+ .next();
+ counts.vertices++;
+ counts.breakdown.comments++;
+ }
+
+ // Create Comment vertices for PR review comments
+ for (const comment of (discussions.prComments?.review || [])) {
+ await g.addV("Comment")
+ .property("author", comment.author)
+ .property("body", comment.body)
+ .property("timestamp", comment.timestamp || "")
+ .next();
+ counts.vertices++;
+ counts.breakdown.comments++;
+ }
+
+ // Create Discussion vertices for proposals
+ for (const proposal of (discussions.proposals || [])) {
+ await g.addV("Discussion")
+ .property("url", proposal.path || "")
+ .property("source", "proposal")
+ .property("title", proposal.title)
+ .property("body", (proposal.snippet || "").slice(0, 2000))
+ .next();
+ counts.vertices++;
+ counts.breakdown.discussions++;
+ }
+
+ // --- Edges (batched) ---
+ let batch = [];
+
+ // has_comment: PR Discussion -> PR comments
+ for (const comment of (discussions.prComments?.issue || [])) {
+ batch.push(
+ g.V().hasLabel("Discussion").has("url", prUrl)
+ .addE("has_comment")
+ .property("confidence", CONFIDENCE.EXTRACTED)
+ .to(__.V().hasLabel("Comment").has("author", comment.author).has("timestamp", comment.timestamp || ""))
+ );
+ counts.edges++;
+ counts.breakdown.hasComment++;
+ if (batch.length >= BATCH_SIZE) { await submitBatch(batch); batch = []; }
+ }
+
+ for (const comment of (discussions.prComments?.review || [])) {
+ batch.push(
+ g.V().hasLabel("Discussion").has("url", prUrl)
+ .addE("has_comment")
+ .property("confidence", CONFIDENCE.EXTRACTED)
+ .to(__.V().hasLabel("Comment").has("author", comment.author).has("timestamp", comment.timestamp || ""))
+ );
+ counts.edges++;
+ counts.breakdown.hasComment++;
+ if (batch.length >= BATCH_SIZE) { await submitBatch(batch); batch = []; }
+ }
+
+ // has_comment: JIRA Discussion -> JIRA comments
+ for (const jira of discussions.jiras) {
+ for (const comment of (jira.comments || [])) {
+ batch.push(
+ g.V().hasLabel("Discussion").has("url", jira.url)
+ .addE("has_comment")
+ .property("confidence", CONFIDENCE.EXTRACTED)
+ .to(__.V().hasLabel("Comment").has("author", comment.author).has("timestamp", comment.timestamp || ""))
+ );
+ counts.edges++;
+ counts.breakdown.hasComment++;
+ if (batch.length >= BATCH_SIZE) { await submitBatch(batch); batch = []; }
+ }
+ }
+
+ // has_comment: Secondary Discussion -> their comments
+ for (const sec of (discussions.secondary || [])) {
+ for (const comment of (sec.comments || [])) {
+ batch.push(
+ g.V().hasLabel("Discussion").has("url", sec.url)
+ .addE("has_comment")
+ .property("confidence", CONFIDENCE.EXTRACTED)
+ .to(__.V().hasLabel("Comment").has("author", comment.author).has("timestamp", comment.timestamp || ""))
+ );
+ counts.edges++;
+ counts.breakdown.hasComment++;
+ if (batch.length >= BATCH_SIZE) { await submitBatch(batch); batch = []; }
+ }
+ }
+
+ // addresses: PR Discussion -> JIRA discussions
+ for (const jira of discussions.jiras) {
+ batch.push(
+ g.V().hasLabel("Discussion").has("url", prUrl)
+ .addE("addresses")
+ .property("found_in", jira.found_in || "pr")
+ .property("confidence", confidenceForFoundIn(jira.found_in || "pr"))
+ .to(__.V().hasLabel("Discussion").has("url", jira.url))
+ );
+ counts.edges++;
+ counts.breakdown.addresses++;
+ if (batch.length >= BATCH_SIZE) { await submitBatch(batch); batch = []; }
+ }
+
+ // addresses: PR Discussion -> dev list threads
+ for (const thread of discussions.devList) {
+ batch.push(
+ g.V().hasLabel("Discussion").has("url", prUrl)
+ .addE("addresses")
+ .property("found_in", thread.found_in || "pr")
+ .property("confidence", confidenceForFoundIn(thread.found_in || "pr"))
+ .to(__.V().hasLabel("Discussion").has("url", thread.url))
+ );
+ counts.edges++;
+ counts.breakdown.addresses++;
+ if (batch.length >= BATCH_SIZE) { await submitBatch(batch); batch = []; }
+ }
+
+ // addresses: source Discussion -> secondary discussions (cross-references)
+ for (const sec of (discussions.secondary || [])) {
+ const sourceUrl = sec.found_via
+ ? (discussions.jiras.find((j) => j.id === sec.found_via)?.url || sec.found_via)
+ : prUrl;
+ batch.push(
+ g.V().hasLabel("Discussion").has("url", sourceUrl)
+ .addE("addresses")
+ .property("found_in", sec.found_in || "")
+ .property("found_via", sec.found_via || "")
+ .property("confidence", confidenceForFoundIn(sec.found_in))
+ .to(__.V().hasLabel("Discussion").has("url", sec.url))
+ );
+ counts.edges++;
+ counts.breakdown.addresses++;
+ if (batch.length >= BATCH_SIZE) { await submitBatch(batch); batch = []; }
+ }
+
+ // proposed_in: link proposals to the PR Discussion. Confidence tracks how the
+ // link was found: an explicit reference is EXTRACTED, a title/heading keyword
+ // match is INFERRED, a body-only match is AMBIGUOUS (so it surfaces for human
+ // review). The matched terms and location ride on the edge so the link is
+ // self-explanatory — mirroring `addresses`' found_in/found_via.
+ const confForMatch = (matchedIn) =>
+ matchedIn === "reference" ? CONFIDENCE.EXTRACTED
+ : matchedIn === "title" ? CONFIDENCE.INFERRED
+ : CONFIDENCE.AMBIGUOUS;
+ for (const proposal of (discussions.proposals || [])) {
+ batch.push(
+ g.V().hasLabel("Discussion").has("source", "proposal").has("title", proposal.title)
+ .addE("proposed_in")
+ .property("confidence", confForMatch(proposal.matchedIn))
+ .property("matched_in", proposal.matchedIn || "search")
+ .property("matched_keywords", (proposal.matchedKeywords || []).join(", "))
+ .to(__.V().hasLabel("Discussion").has("url", prUrl))
+ );
+ counts.edges++;
+ counts.breakdown.proposedIn++;
+ if (batch.length >= BATCH_SIZE) { await submitBatch(batch); batch = []; }
+ }
+
+ // modifies: PR Discussion -> changed Files
+ for (const filePath of (context.changedFiles || [])) {
+ batch.push(
+ g.V().hasLabel("Discussion").has("url", prUrl)
+ .addE("modifies")
+ .property("confidence", CONFIDENCE.EXTRACTED)
+ .to(__.V().hasLabel("File").has("path", filePath))
+ );
+ counts.edges++;
+ counts.breakdown.modifies++;
+ if (batch.length >= BATCH_SIZE) { await submitBatch(batch); batch = []; }
+ }
+
+ if (batch.length > 0) {
+ await submitBatch(batch);
+ }
+
+ return counts;
+}
diff --git a/.skills/tinker-review/scripts/graph/populate.js b/.skills/tinker-review/scripts/graph/populate.js
new file mode 100644
index 0000000000..b0b17b1bda
--- /dev/null
+++ b/.skills/tinker-review/scripts/graph/populate.js
@@ -0,0 +1,389 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+import gremlin from "gremlin";
+import { CONFIDENCE } from "./confidence.js";
+
+const { process: { statics: __, P } } = gremlin;
+
+const BATCH_SIZE = 50;
+
+async function submitBatch(batch) {
+ const results = await Promise.allSettled(batch.map((t) => t.next()));
+ return results.filter((r) => r.status === "fulfilled").length;
+}
+
+/**
+ * Derive `overrides` edges (Function -> Function) from the type hierarchy.
+ *
+ * For each real Function `f` declared by some Type, walk that type's transitive
+ * supertypes (extends/implements) and, for every ancestor method sharing `f`'s
+ * name, add `f -overrides-> ancestorMethod`. This is what lets blast radius see
+ * impact flowing through interface/abstract hierarchies: change an interface
+ * method and every override is reachable via `in("overrides")`.
+ *
+ * Requires the `extends`/`implements` and `declares` edges to already be in the
+ * graph, so it runs as a final pass after population. INFERRED — the match is by
+ * method name (arity isn't reliably captured across languages).
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @returns {Promise<number>} count of overrides edges created
+ */
+export async function deriveOverrides(g) {
+ // Only functions that have a declaring type can override anything.
+ const fnIds = await g.V().hasLabel("Function").hasNot("external")
+ .where(__.in_("declares")).id().toList();
+
+ let created = 0;
+ for (const fid of fnIds) {
+ // One scoped walk per function: a global dedup() here would dedup ancestor
+ // types ACROSS seeds, so a shared ancestor (e.g. a common interface) would
+ // be walked only once total and most overrides would be lost. Per-seed keeps
+ // each walk independent.
+ const result = await g.V(fid).as("f")
+ .in_("declares")
+ .repeat(__.out("extends", "implements")).emit().times(6)
+ .dedup()
+ .out("declares").hasNot("external")
+ .where(P.eq("f")).by("name")
+ .where(P.neq("f"))
+ .dedup()
+ .addE("overrides").from_("f")
+ .property("confidence", CONFIDENCE.INFERRED)
+ .count().next();
+ created += Number(result.value);
+ }
+ return created;
+}
+
+/**
+ * Populate TinkerGraph with extraction data.
+ * Creates vertices and edges matching the PR knowledge graph schema.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {ExtractionResult} extraction - Output from tree-sitter module
+ * @param {object} [options]
+ * @param {string[]} [options.changedFiles] - Full changed-file list for the PR
+ * (used to mark files the PR touched but the extractor didn't parse)
+ * @param {string} [options.worktreePath] - PR-head worktree, to tell a deleted
+ * file (absent on disk) from an unparsed one (present but not a parsed language)
+ * @returns {Promise<PopulationSummary>}
+ */
+export async function populate(g, extraction, options = {}) {
+ const { changedFiles = [], worktreePath = "" } = options;
+ const counts = {
+ vertices: 0,
+ edges: 0,
+ breakdown: { files: 0, functions: 0, types: 0, tests: 0, calls: 0, defines: 0, testsEdges: 0, externalFunctions: 0, stubFiles: 0, externalTypes: 0, extendsEdges: 0, implementsEdges: 0, declares: 0, overrides: 0 },
+ };
+
+ for (const file of extraction.files) {
+ await g.addV("File")
+ .property("path", file.path)
+ .property("language", file.language)
+ .property("changeLevel", file.changeLevel)
+ .next();
+ counts.vertices++;
+ counts.breakdown.files++;
+ }
+
+ // Mark changed files the extractor didn't parse. The PR's `modifies` edges
+ // target every changed file by path, but only parsed files (right language,
+ // present on disk) get a File vertex above — so a deleted or non-code file
+ // would have no vertex to land on and its `modifies` edge would vanish. Create
+ // a stub File as a marker (keyed by unique path, so it's race-free). A file
+ // absent from the PR-head worktree was deleted by the PR; one still on disk was
+ // simply not parsed (unsupported language). These markers are especially
+ // meaningful on removal PRs — they record exactly what the PR took out.
+ // Unparsed, so no fingerprint is possible — graded STRUCTURAL conservatively.
+ const extractedPaths = new Set(extraction.files.map((f) => f.path));
+ for (const filePath of changedFiles) {
+ if (extractedPaths.has(filePath)) continue;
+ const onDisk = worktreePath ? existsSync(join(worktreePath, filePath)) : true;
+ const ext = filePath.includes(".") ? filePath.split(".").pop() : "";
+ await g.addV("File")
+ .property("path", filePath)
+ .property("language", ext)
+ .property("changeLevel", "STRUCTURAL")
+ .property("parsed", false)
+ .property("deleted", !onDisk)
+ .next();
+ counts.vertices++;
+ counts.breakdown.stubFiles++;
+ }
+
+ for (const fn of extraction.functions) {
+ await g.addV("Function")
+ .property("name", fn.name)
+ .property("signature", fn.signature)
+ .property("visibility", fn.visibility)
+ .property("filePath", fn.filePath)
+ .property("language", fn.language || "")
+ .property("lines_start", fn.linesStart)
+ .property("lines_end", fn.linesEnd)
+ .property("changeLevel", fn.changeLevel)
+ .next();
+ counts.vertices++;
+ counts.breakdown.functions++;
+ }
+
+ for (const type of extraction.types) {
+ await g.addV("Type")
+ .property("name", type.name)
+ .property("kind", type.kind)
+ .property("visibility", type.visibility)
+ .property("filePath", type.filePath)
+ .property("language", type.language || "")
+ .property("changeLevel", type.changeLevel || "NONE")
+ .next();
+ counts.vertices++;
+ counts.breakdown.types++;
+ }
+
+ const tests = extraction.tests || [];
+ for (const test of tests) {
+ await g.addV("Test")
+ .property("name", test.name)
+ .property("type", test.type)
+ .property("filePath", test.filePath)
+ .property("language", test.language || "")
+ .next();
+ counts.vertices++;
+ counts.breakdown.tests++;
+ }
+
+ let batch = [];
+
+ // Resolve-or-mark callee vertices. Call/test edges target a function by name;
+ // when the callee isn't among the extracted functions (a library/JDK call, or
+ // a function in a file this PR didn't change) there is no vertex to land on
+ // and the edge would silently vanish. Materialize a lightweight "external"
+ // stub as a marker so the edge survives and downstream analysis (blast radius,
+ // centrality) can see the call. Stubs are keyed by (name, language) — the same
+ // name in two languages is two distinct stubs, so cross-language edges are
+ // never invented — and created up front so this is idempotent and race-free
+ // under batched inserts. MUST be flushed before the calls/tests edges below.
+ const langKey = (name, language) => `${language || ""}\u0000${name}`;
+ const extractedFunctionKeys = new Set(extraction.functions.map((f) => langKey(f.name, f.language)));
+ const unresolvedCallees = new Map();
+ const markUnresolved = (name, language) => {
+ const key = langKey(name, language);
+ if (!extractedFunctionKeys.has(key)) unresolvedCallees.set(key, { name, language: language || "" });
+ };
+ for (const call of extraction.calls) markUnresolved(call.calleeName, call.language);
+ for (const test of tests) {
+ for (const calledFn of (test.calledFunctions || [])) markUnresolved(calledFn, test.language);
+ }
+
+ for (const { name, language } of unresolvedCallees.values()) {
+ batch.push(
+ g.addV("Function")
+ .property("name", name)
+ .property("language", language)
+ .property("external", true)
+ .property("resolved", false)
+ .property("changeLevel", "NONE")
+ );
+ counts.vertices++;
+ counts.breakdown.externalFunctions++;
+
+ if (batch.length >= BATCH_SIZE) {
+ await submitBatch(batch);
+ batch = [];
+ }
+ }
+ if (batch.length > 0) {
+ await submitBatch(batch);
+ batch = [];
+ }
+
+ for (const fn of extraction.functions) {
+ batch.push(
+ g.V().hasLabel("File").has("path", fn.filePath)
+ .addE("defines")
+ .property("confidence", CONFIDENCE.EXTRACTED)
+ .to(__.V().hasLabel("Function").has("name", fn.name).has("filePath", fn.filePath))
+ );
+ counts.edges++;
+ counts.breakdown.defines++;
+
+ if (batch.length >= BATCH_SIZE) {
+ await submitBatch(batch);
+ batch = [];
+ }
+ }
+
+ for (const type of extraction.types) {
+ batch.push(
+ g.V().hasLabel("File").has("path", type.filePath)
+ .addE("defines")
+ .property("confidence", CONFIDENCE.EXTRACTED)
+ .to(__.V().hasLabel("Type").has("name", type.name).has("filePath", type.filePath))
+ );
+ counts.edges++;
+ counts.breakdown.defines++;
+
+ if (batch.length >= BATCH_SIZE) {
+ await submitBatch(batch);
+ batch = [];
+ }
+ }
+
+ for (const call of extraction.calls) {
+ // INFERRED: the call site is real, but the callee is resolved by name alone
+ // (it matches any Function with that name, across files/overloads), so the
+ // edge target is a deduction rather than a directly observed fact. Scoped to
+ // the caller's language so a name that also exists in another language can't
+ // pull a spurious cross-language edge.
+ batch.push(
+ g.V().hasLabel("Function")
+ .has("name", call.callerName)
+ .has("filePath", call.callerFile)
+ .addE("calls")
+ .property("confidence", CONFIDENCE.INFERRED)
+ .to(__.V().hasLabel("Function").has("name", call.calleeName).has("language", call.language || ""))
+ );
+ counts.edges++;
+ counts.breakdown.calls++;
+
+ if (batch.length >= BATCH_SIZE) {
+ await submitBatch(batch);
+ batch = [];
+ }
+ }
+
+ for (const test of tests) {
+ for (const calledFn of test.calledFunctions) {
+ // INFERRED: a test is linked to a function by name match on the callee,
+ // scoped to the test's language (a Java test can't land on a Python fn).
+ batch.push(
+ g.V().hasLabel("Test").has("name", test.name).has("filePath", test.filePath)
+ .addE("tests")
+ .property("confidence", CONFIDENCE.INFERRED)
+ .to(__.V().hasLabel("Function").has("name", calledFn).has("language", test.language || ""))
+ );
+ counts.edges++;
+ counts.breakdown.testsEdges++;
+
+ if (batch.length >= BATCH_SIZE) {
+ await submitBatch(batch);
+ batch = [];
+ }
+ }
+ }
+
+ // Resolve-or-mark supertypes. Like callees, a supertype is named in the source
+ // but its declaration is often outside the changed set (a JDK class, or a base
+ // type in a file this PR didn't touch). Materialize an external Type stub for
+ // any supertype name not among the extracted types so the extends/implements
+ // edge has a vertex to land on. Keyed by (name, language) like Function stubs.
+ // Flushed before the edges below reference them.
+ const extractedTypeKeys = new Set(extraction.types.map((t) => langKey(t.name, t.language)));
+ const unresolvedSupertypes = new Map();
+ for (const type of extraction.types) {
+ for (const s of (type.supertypes || [])) {
+ const key = langKey(s.name, type.language);
+ if (!extractedTypeKeys.has(key)) unresolvedSupertypes.set(key, { name: s.name, language: type.language || "" });
+ }
+ }
+ for (const { name, language } of unresolvedSupertypes.values()) {
+ batch.push(
+ g.addV("Type")
+ .property("name", name)
+ .property("language", language)
+ .property("external", true)
+ .property("resolved", false)
+ );
+ counts.breakdown.externalTypes++;
+ if (batch.length >= BATCH_SIZE) {
+ await submitBatch(batch);
+ batch = [];
+ }
+ }
+ if (batch.length > 0) {
+ await submitBatch(batch);
+ batch = [];
+ }
+
+ // Type hierarchy edges (Type -> Type). INFERRED: the supertype is resolved by
+ // simple name, so the target is a deduction (like `calls`). Scoped to the
+ // subtype's language so hierarchies never cross language families. `relation`
+ // is "extends" or "implements" as the source declared it.
+ for (const type of extraction.types) {
+ for (const s of (type.supertypes || [])) {
+ batch.push(
+ g.V().hasLabel("Type").has("name", type.name).has("filePath", type.filePath)
+ .addE(s.relation)
+ .property("confidence", CONFIDENCE.INFERRED)
+ .to(__.V().hasLabel("Type").has("name", s.name).has("language", type.language || ""))
+ );
+ if (s.relation === "extends") counts.breakdown.extendsEdges++;
+ else counts.breakdown.implementsEdges++;
+ if (batch.length >= BATCH_SIZE) {
+ await submitBatch(batch);
+ batch = [];
+ }
+ }
+ }
+
+ // Membership edges (Type -> Function). EXTRACTED: the method sits directly in
+ // the type's body — a directly observed fact, and both endpoints are pinned to
+ // the same file so the resolution is exact.
+ for (const decl of (extraction.declares || [])) {
+ batch.push(
+ g.V().hasLabel("Type").has("name", decl.typeName).has("filePath", decl.filePath)
+ .addE("declares")
+ .property("confidence", CONFIDENCE.EXTRACTED)
+ .to(__.V().hasLabel("Function").has("name", decl.functionName).has("filePath", decl.filePath))
+ );
+ counts.breakdown.declares++;
+ if (batch.length >= BATCH_SIZE) {
+ await submitBatch(batch);
+ batch = [];
+ }
+ }
+
+ // Import resolution (depends_on edges) is intentionally not implemented.
+ // File-to-file connectivity is already captured through the calls/defines edges
+ // (File A defines Function X which calls Function Y defined in File B). The
+ // depends_on edge would only add value for type-only references (imports used
+ // for signatures/fields but not method calls) which are less relevant for
+ // review purposes. Revisit if cluster analysis produces false disconnections.
+
+ if (batch.length > 0) {
+ await submitBatch(batch);
+ batch = [];
+ }
+
+ // Derive `overrides` edges now that the hierarchy and membership edges exist.
+ counts.breakdown.overrides = await deriveOverrides(g);
+
+ // Report the true graph size. The per-type breakdown above counts attempted
+ // inserts; query the graph itself for the authoritative vertex/edge totals so
+ // the summary can't drift from reality (e.g. an edge whose endpoints matched
+ // multiple vertices, or a vertex insert that failed).
+ const realV = await g.V().count().next();
+ const realE = await g.E().count().next();
+ counts.vertices = Number(realV.value);
+ counts.edges = Number(realE.value);
+
+ return counts;
+}
diff --git a/.skills/tinker-review/scripts/graph/references.js b/.skills/tinker-review/scripts/graph/references.js
new file mode 100644
index 0000000000..5494e6195e
--- /dev/null
+++ b/.skills/tinker-review/scripts/graph/references.js
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Shared helpers for symbols and `references` edges. Used by both the Phase-1
+// removal-refs pass (patterns/removal-refs.js) and the manual addReference
+// escape hatch (enrichment/api.js), so the edge shape lives in one place.
+
+import gremlin from "gremlin";
+import { CONFIDENCE } from "./confidence.js";
+
+const { process: { statics: __ } } = gremlin;
+
+const CODE_EXTENSIONS = new Set([
+ "java", "py", "js", "ts", "jsx", "tsx", "mjs", "go", "cs", "groovy",
+ "kt", "scala", "rb", "rs", "c", "cpp", "h", "hpp",
+]);
+
+// The likely symbol a source file defined — its basename without extension
+// (Krb5Authenticator.java -> Krb5Authenticator).
+export function symbolFromPath(path) {
+ const base = path.split("/").pop() || path;
+ const dot = base.indexOf(".");
+ return dot > 0 ? base.slice(0, dot) : base;
+}
+
+export function extOf(path) {
+ return path.includes(".") ? path.split(".").pop() : "";
+}
+
+export function isCodeFile(path) {
+ return CODE_EXTENSIONS.has(extOf(path));
+}
+
+/**
+ * Create a `references` edge: a surviving file (fromPath) still mentions a symbol
+ * from a deleted file (toPath). The source file is often outside the changed set
+ * and has no vertex yet, so it is find-or-created as an unparsed marker. Assumes
+ * the target (deleted) File vertex already exists.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} params
+ * @param {string} params.fromPath
+ * @param {string} params.toPath
+ * @param {string} [params.symbol]
+ * @param {string} [params.location]
+ * @param {string} [params.confidence] - default INFERRED
+ */
+export async function createReferenceEdge(g, params) {
+ const { fromPath, toPath, symbol, location, confidence = CONFIDENCE.INFERRED } = params;
+
+ const srcExists = await g.V().hasLabel("File").has("path", fromPath).hasNext();
+ if (!srcExists) {
+ await g.addV("File")
+ .property("path", fromPath)
+ .property("language", extOf(fromPath))
+ .property("changeLevel", "NONE")
+ .property("parsed", false)
+ .property("deleted", false)
+ .next();
+ }
+
+ await g.V().hasLabel("File").has("path", fromPath)
+ .addE("references")
+ .property("confidence", confidence)
+ .property("symbol", symbol || "")
+ .property("location", location || "")
+ .to(__.V().hasLabel("File").has("path", toPath))
+ .next();
+}
diff --git a/.skills/tinker-review/scripts/infrastructure/docker.js b/.skills/tinker-review/scripts/infrastructure/docker.js
new file mode 100644
index 0000000000..a1e6023a18
--- /dev/null
+++ b/.skills/tinker-review/scripts/infrastructure/docker.js
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { findAvailablePort, waitForHttp } from "./net.js";
+
+const exec = promisify(execFile);
+
+const DEFAULT_IMAGE = "tinkerpop/gremlin-server:3.8.1";
+const DEFAULT_TIMEOUT_MS = 30000;
+
+const INIT_GROOVY = `def globals = [:]
+globals << [g : traversal().withEmbedded(graph)]
+globals << [a : traversal().withEmbedded(graph).withComputer()]
+`;
+
+/**
+ * Start a Gremlin Server Docker container with TinkerGraph.
+ * Configures two traversal sources:
+ * 'g' — standard traversal
+ * 'a' — withComputer() for OLAP steps like connectedComponent()
+ *
+ * Uses the stock 3.8.1 image and config. Only overrides the init script
+ * to add the 'a' binding.
+ *
+ * @param {object} options
+ * @param {string} [options.image] - Docker image (default: "tinkerpop/gremlin-server:3.8.1")
+ * @param {number} [options.timeoutMs] - Max wait for readiness (default: 30000)
+ * @returns {Promise<ServerHandle>}
+ */
+export async function startServer(options = {}) {
+ const image = options.image || DEFAULT_IMAGE;
+ const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
+
+ // A fixed port lets a review be regenerated on the same endpoint; otherwise an
+ // OS-assigned free port is used.
+ const port = options.port || await findAvailablePort();
+ const configDir = `/tmp/gremlin-review-${port}`;
+
+ await mkdir(join(configDir, "scripts"), { recursive: true });
+ await writeFile(join(configDir, "scripts", "init.groovy"), INIT_GROOVY);
+
+ const { stdout } = await exec("docker", [
+ "run", "-d",
+ "--name", `pr-review-graph-${port}`,
+ "-p", `${port}:8182`,
+ "-v", `${configDir}/scripts/init.groovy:/opt/gremlin-server/scripts/empty-sample.groovy`,
+ image,
+ ]);
+
+ const containerId = stdout.trim();
+ const url = `ws://localhost:${port}/gremlin`;
+
+ const handle = { port, containerId, url, configDir };
+
+ try {
+ await waitForHttp(port, timeoutMs);
+ } catch (err) {
+ await stopServer(handle).catch(() => {});
+ throw err;
+ }
+
+ return handle;
+}
+
+/**
+ * Stop and remove the Gremlin Server container.
+ *
+ * @param {ServerHandle} handle - Handle returned by startServer
+ * @returns {Promise<void>}
+ */
+export async function stopServer(handle) {
+ await exec("docker", ["stop", handle.containerId]).catch(() => {});
+ await exec("docker", ["rm", handle.containerId]).catch(() => {});
+}
diff --git a/.skills/tinker-review/scripts/infrastructure/net.js b/.skills/tinker-review/scripts/infrastructure/net.js
new file mode 100644
index 0000000000..ead214e4a2
--- /dev/null
+++ b/.skills/tinker-review/scripts/infrastructure/net.js
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Shared networking helpers for the two Gremlin Servers a review stands up: the
+// Phase-1 knowledge-graph server (docker.js) and the Phase-2 functional-test
+// server built from PR source (functional/setup.js). Both pick a free port and
+// poll the same HTTP readiness endpoint, so that logic lives here once.
+
+import { createServer } from "node:net";
+import { get } from "node:http";
+
+const POLL_INTERVAL_MS = 500;
+
+/**
+ * Ask the OS for a free TCP port by binding to 0 and reading it back.
+ * @returns {Promise<number>}
+ */
+export function findAvailablePort() {
+ return new Promise((resolve, reject) => {
+ const srv = createServer();
+ srv.listen(0, () => {
+ const { port } = srv.address();
+ srv.close(() => resolve(port));
+ });
+ srv.on("error", reject);
+ });
+}
+
+/**
+ * Poll an HTTP endpoint until it responds or the timeout elapses. Gremlin
+ * Server answers a plain GET on `/gremlin` once its WebSocket listener is up,
+ * so a successful response of any status means "ready".
+ *
+ * @param {number} port - localhost port to poll
+ * @param {number} timeoutMs - max wait before rejecting
+ * @param {object} [options]
+ * @param {string} [options.path] - request path (default "/gremlin")
+ * @returns {Promise<void>}
+ */
+export function waitForHttp(port, timeoutMs, options = {}) {
+ const path = options.path || "/gremlin";
+ const deadline = Date.now() + timeoutMs;
+
+ return new Promise((resolve, reject) => {
+ function poll() {
+ if (Date.now() > deadline) {
+ reject(new Error(`Server on port ${port} did not become ready within ${timeoutMs}ms`));
+ return;
+ }
+
+ const req = get(`http://localhost:${port}${path}`, (res) => {
+ res.resume();
+ resolve();
+ });
+ req.on("error", () => {
+ setTimeout(poll, POLL_INTERVAL_MS);
+ });
+ }
+
+ poll();
+ });
+}
diff --git a/.skills/tinker-review/scripts/patterns/architecture.js b/.skills/tinker-review/scripts/patterns/architecture.js
new file mode 100644
index 0000000000..d4ee27a061
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/architecture.js
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import gremlin from "gremlin";
+import { changedAny } from "../graph/change-levels.js";
+
+const { process: { t } } = gremlin;
+
+/**
+ * Generate architecture SVG input from the graph's cluster analysis.
+ *
+ * Queries File vertices and depends_on edges from the populated graph,
+ * groups files into clusters by directory path, and returns the node/edge
+ * structure expected by the renderer's generateClusterSvg().
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} params
+ * @param {object} [params.clusterResult] - Output from clusterAnalysis() (connectedComponent clusters)
+ * @param {boolean} [params.changedOnly] - Only include changed files — any level
+ * but NONE (default: false)
+ * @param {number} [params.maxNodes] - Cap on nodes to render (default: 40)
+ * @returns {Promise<ArchitectureResult>}
+ */
+
+/**
+ * @typedef {Object} ArchitectureNode
+ * @property {string} id
+ * @property {string} label
+ * @property {string} cluster the cluster/community the node belongs to
+ * @property {boolean} changed whether the PR modified it (changeLevel !== NONE)
+ * @property {string} changeLevel how the PR moved it (NONE | FORMATTING | BEHAVIORAL | STRUCTURAL)
+ *
+ * @typedef {Object} ArchitectureResult
+ * @property {ArchitectureNode[]} nodes
+ * @property {{from: string, to: string}[]} edges directed dependency edges between nodes
+ */
+export async function architecture(g, params = {}) {
+ const { clusterResult, changedOnly = false, maxNodes = 40 } = params;
+
+ let traversal = g.V().hasLabel("File");
+ if (changedOnly) {
+ traversal = traversal.has("changeLevel", changedAny());
+ }
+
+ const fileVertices = await traversal.elementMap().toList();
+
+ if (fileVertices.length === 0) {
+ return { nodes: [], edges: [] };
+ }
+
+ const clusterAssignment = buildClusterAssignment(fileVertices, clusterResult);
+
+ let nodes = fileVertices.map((fileMap) => {
+ const path = fileMap.get("path");
+ const changeLevel = fileMap.get("changeLevel") || "NONE";
+ const changed = changeLevel !== "NONE";
+ const id = path;
+ const label = shortLabel(path);
+ const cluster = clusterAssignment.get(path) || dirCluster(path);
+
+ return { id, label, cluster, changed, changeLevel };
+ });
+
+ if (nodes.length > maxNodes) {
+ nodes = prioritizeNodes(nodes, maxNodes);
+ }
+
+ const nodeIds = new Set(nodes.map((n) => n.id));
+
+ // Find cross-file function calls: File A defines Function X which calls Function Y defined in File B
+ const edgeResults = await g.V().hasLabel("Function")
+ .as("caller")
+ .out("calls")
+ .as("callee")
+ .select("caller", "callee")
+ .by("filePath")
+ .toList();
+
+ const edgeSet = new Set();
+ const edges = [];
+ for (const row of edgeResults) {
+ const from = row.get("caller");
+ const to = row.get("callee");
+ if (from && to && from !== to && nodeIds.has(from) && nodeIds.has(to)) {
+ const key = `${from}|${to}`;
+ if (!edgeSet.has(key)) {
+ edgeSet.add(key);
+ edges.push({ from, to });
+ }
+ }
+ }
+
+ return { nodes, edges };
+}
+
+function buildClusterAssignment(fileVertices, clusterResult) {
+ const assignment = new Map();
+
+ if (clusterResult && clusterResult.clusters) {
+ for (const cluster of clusterResult.clusters) {
+ const clusterLabel = deriveClusterLabel(cluster.files);
+ for (const filePath of cluster.files) {
+ assignment.set(filePath, clusterLabel);
+ }
+ }
+ } else {
+ for (const fileMap of fileVertices) {
+ const path = fileMap.get("path");
+ assignment.set(path, dirCluster(path));
+ }
+ }
+
+ return assignment;
+}
+
+function deriveClusterLabel(files) {
+ if (files.length === 0) return "other";
+ if (files.length === 1) return dirCluster(files[0]);
+
+ const segments = files.map((f) => f.split("/").slice(0, -1));
+ const minLen = Math.min(...segments.map((s) => s.length));
+
+ let common = 0;
+ for (let i = 0; i < minLen; i++) {
+ const seg = segments[0][i];
+ if (segments.every((s) => s[i] === seg)) {
+ common = i + 1;
+ } else {
+ break;
+ }
+ }
+
+ if (common > 0) {
+ return segments[0].slice(0, common).join("/");
+ }
+
+ return dirCluster(files[0]);
+}
+
+function dirCluster(filePath) {
+ const parts = filePath.split("/");
+ if (parts.length <= 1) return "/";
+ if (parts.length <= 3) return parts.slice(0, -1).join("/");
+ return parts.slice(0, 2).join("/");
+}
+
+function shortLabel(filePath) {
+ const parts = filePath.split("/");
+ return parts[parts.length - 1];
+}
+
+function prioritizeNodes(nodes, maxNodes) {
+ const changed = nodes.filter((n) => n.changed);
+ const unchanged = nodes.filter((n) => !n.changed);
+
+ if (changed.length >= maxNodes) {
+ return changed.slice(0, maxNodes);
+ }
+
+ return [...changed, ...unchanged.slice(0, maxNodes - changed.length)];
+}
diff --git a/.skills/tinker-review/scripts/patterns/blast-radius.js b/.skills/tinker-review/scripts/patterns/blast-radius.js
new file mode 100644
index 0000000000..319de22b3a
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/blast-radius.js
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import gremlin from "gremlin";
+
+import { changedMeaningful, atLeastP, atLeast } from "../graph/change-levels.js";
+
+const INHERENTLY_CENTRAL = new Set([
+ "equals", "hashCode", "toString", "clone", "close", "compareTo",
+ "iterator", "hasNext", "next", "get", "set", "size", "isEmpty",
+ "contains", "add", "remove", "clear", "values", "entrySet", "keySet",
+ "finalize", "notify", "notifyAll", "wait",
+]);
+
+const { statics: __, t: T } = gremlin.process;
+
+/**
+ * Calculate blast radius — how far a change ripples. Two seeds:
+ *
+ * - Function-seeded: from each changed function, count what's reachable
+ * upstream via `calls` AND `overrides`. The `overrides` hop is what makes
+ * this see impact flowing through interface/abstract hierarchies — change an
+ * interface method and every override counts, which a call-only walk misses.
+ * - Type-seeded (hierarchy bucket): from each changed Type (typically an
+ * interface), count the functions declared by everything that implements or
+ * extends it. Reported separately so call/override impact and pure
+ * type-hierarchy impact stay legible rather than summed into one number.
+ *
+ * Methods that are inherently central (equals, toString, etc.) are filtered
+ * out UNLESS they were modified in this PR.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource
+ * @param {object} params
+ * @param {number} [params.depth] - Max hops to traverse (default: 3)
+ * @param {boolean} [params.changedOnly] - Start from changed functions only (default: true).
+ * Function seed defaults to the meaningful tiers (BEHAVIORAL, STRUCTURAL); the
+ * type seed is STRUCTURAL-only.
+ * @param {string} [params.minChangeLevel] - Narrow the function seed to this
+ * level and above (e.g. "STRUCTURAL")
+ * @returns {Promise<BlastRadiusResult>}
+ */
+
+/**
+ * @typedef {Object} BlastRadiusFn
+ * @property {string} name
+ * @property {string} filePath
+ * @property {string} signature
+ * @property {number} linesStart
+ * @property {number} linesEnd
+ * @property {string} changeLevel how the PR moved this function (NONE | FORMATTING | BEHAVIORAL | STRUCTURAL)
+ * @property {number} reachableCount callers + overriders reachable within `depth` hops upstream;
+ * high = the change ripples widely (for driver/server this is expected)
+ * @property {number} depth hop limit used for this row
+ *
+ * @typedef {Object} BlastRadiusType
+ * @property {string} name
+ * @property {string} filePath
+ * @property {string} kind class | interface | struct | enum
+ * @property {number} implementerCount functions declared by types that implement/extend this one
+ * @property {number} depth
+ *
+ * @typedef {Object} BlastRadiusResult
+ * @property {BlastRadiusFn[]} functions changed functions and how far each one's change reaches
+ * @property {BlastRadiusType[]} types changed types and how many implementers' functions they reach
+ * @property {number} maxReachable largest reachableCount across changed functions
+ * @property {number} totalWithCallers changed functions that have any upstream callers/overriders
+ * @property {number} depth hop limit applied
+ */
+export async function blastRadius(g, params = {}) {
+ const depth = params.depth || 3;
+ const changedOnly = params.changedOnly !== false;
+ // Function seed uses the meaningful tiers; `minChangeLevel` can narrow further.
+ const changePredicate = params.minChangeLevel
+ ? atLeastP(params.minChangeLevel)
+ : changedMeaningful();
+
+ let traversal = g.V().hasLabel("Function").hasNot("external");
+ if (changedOnly) {
+ traversal = traversal.has("changeLevel", changePredicate);
+ }
+
+ const functions = await traversal.elementMap().toList();
+ const results = [];
+
+ for (const fnMap of functions) {
+ const vertexId = fnMap.get(T.id);
+ const name = fnMap.get("name");
+ const changeLevel = fnMap.get("changeLevel");
+
+ if (INHERENTLY_CENTRAL.has(name) && !atLeast(changeLevel || "NONE", "BEHAVIORAL")) continue;
+
+ const reachable = await g.V(vertexId)
+ .repeat(__.union(__.in_("calls"), __.in_("overrides")).dedup())
+ .times(depth)
+ .emit()
+ .dedup()
+ .count()
+ .next();
+
+ const count = reachable.value;
+ if (count > 0) {
+ results.push({
+ name,
+ filePath: fnMap.get("filePath"),
+ signature: fnMap.get("signature"),
+ linesStart: fnMap.get("lines_start"),
+ linesEnd: fnMap.get("lines_end"),
+ changeLevel,
+ reachableCount: count,
+ depth,
+ });
+ }
+ }
+
+ results.sort((a, b) => b.reachableCount - a.reachableCount);
+
+ // Type-seeded hierarchy impact: functions declared by everything that
+ // implements/extends a changed type, walked in the implementer->supertype
+ // direction (`in`) up to `depth` levels of the hierarchy.
+ // Type seed is STRUCTURAL-only: a hierarchy ripples through implementers only
+ // when the type's contract (kind/supertypes/member set) moved — a body-only
+ // (BEHAVIORAL) or formatting change to the declaring file does not.
+ let typeTraversal = g.V().hasLabel("Type").hasNot("external");
+ if (changedOnly) {
+ typeTraversal = typeTraversal.has("changeLevel", "STRUCTURAL");
+ }
+ const changedTypes = await typeTraversal.elementMap().toList();
+ const typeResults = [];
+
+ for (const typeMap of changedTypes) {
+ const vertexId = typeMap.get(T.id);
+ const implementerCount = await g.V(vertexId)
+ .repeat(__.in_("implements", "extends").dedup())
+ .times(depth)
+ .emit()
+ .dedup()
+ .out("declares")
+ .hasNot("external")
+ .dedup()
+ .count()
+ .next();
+
+ const count = Number(implementerCount.value);
+ if (count > 0) {
+ typeResults.push({
+ name: typeMap.get("name"),
+ filePath: typeMap.get("filePath"),
+ kind: typeMap.get("kind"),
+ implementerCount: count,
+ depth,
+ });
+ }
+ }
+
+ typeResults.sort((a, b) => b.implementerCount - a.implementerCount);
+
+ return {
+ functions: results,
+ types: typeResults,
+ maxReachable: results.length > 0 ? results[0].reachableCount : 0,
+ totalWithCallers: results.length,
+ depth,
+ };
+}
diff --git a/.skills/tinker-review/scripts/patterns/centrality.js b/.skills/tinker-review/scripts/patterns/centrality.js
new file mode 100644
index 0000000000..ff0379a25c
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/centrality.js
@@ -0,0 +1,146 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import gremlin from "gremlin";
+import { changedMeaningful, atLeastP, atLeast } from "../graph/change-levels.js";
+
+const { process: { statics: __ } } = gremlin;
+
+const INHERENTLY_CENTRAL = new Set([
+ "equals", "hashCode", "toString", "clone", "close", "compareTo",
+ "iterator", "hasNext", "next", "get", "set", "size", "isEmpty",
+ "contains", "add", "remove", "clear", "values", "entrySet", "keySet",
+ "finalize", "notify", "notifyAll", "wait",
+]);
+
+/**
+ * Identify high-centrality functions — those with many incoming and outgoing
+ * call edges. These are structural hotspots where changes propagate widely.
+ *
+ * Methods that are inherently central by nature (equals, toString, hashCode, etc.)
+ * are filtered out UNLESS they were modified in this PR — in which case they're
+ * highly relevant because many callers depend on their behavior.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource
+ * @param {object} params
+ * @param {boolean} [params.changedOnly] - Only check changed functions (default: true).
+ * "Changed" defaults to the meaningful tiers (BEHAVIORAL, STRUCTURAL); NONE and
+ * FORMATTING are excluded.
+ * @param {string} [params.minChangeLevel] - Narrow the changed filter to this
+ * level and above (e.g. "STRUCTURAL" for signature churn only)
+ * @param {number} [params.topN] - Return top N results (default: 10)
+ * @param {number} [params.minDegree] - Minimum combined in+out degree to include (default: 3)
+ * @param {boolean} [params.excludeLibrary] - Drop calls to library-origin external
+ * stubs from out-degree so JDK/accessor noise doesn't inflate hotspots (default: true).
+ * Only takes effect once classifyExternals has tagged `origin`.
+ * @returns {Promise<CentralityResult>}
+ */
+
+/**
+ * @typedef {Object} Hotspot
+ * @property {string} name
+ * @property {string} filePath
+ * @property {string} signature
+ * @property {number} linesStart
+ * @property {number} linesEnd
+ * @property {string} changeLevel how the PR moved this function (NONE | FORMATTING | BEHAVIORAL | STRUCTURAL)
+ * @property {number} inDegree incoming call edges (how many functions call it)
+ * @property {number} outDegree outgoing call edges, excluding origin:library targets
+ * @property {number} totalDegree inDegree + outDegree — the centrality score
+ * @property {boolean} inherentlyCentral a boilerplate method (equals/toString/…) central by
+ * nature; surfaced only when the PR modified it
+ *
+ * @typedef {Object} CentralityResult
+ * @property {Hotspot[]} hotspots top functions by totalDegree (>= minDegree)
+ * @property {number} totalAnalyzed functions considered
+ * @property {number} aboveThreshold how many cleared minDegree
+ * @property {number} filteredAsBoilerplate inherently-central, unchanged functions dropped
+ */
+export async function highCentrality(g, params = {}) {
+ const changedOnly = params.changedOnly !== false;
+ const topN = params.topN || 10;
+ const minDegree = params.minDegree || 3;
+ const excludeLibrary = params.excludeLibrary !== false;
+ // Default risk lens: BEHAVIORAL + STRUCTURAL. `minChangeLevel` can narrow to
+ // STRUCTURAL-only (signature churn) when a reviewer wants just the API surface.
+ const changePredicate = params.minChangeLevel
+ ? atLeastP(params.minChangeLevel)
+ : changedMeaningful();
+
+ let traversal = g.V().hasLabel("Function");
+ if (changedOnly) {
+ traversal = traversal.has("changeLevel", changePredicate);
+ }
+
+ const functions = await traversal.elementMap().toList();
+ const results = [];
+ const filtered = [];
+
+ for (const fnMap of functions) {
+ const vertexId = fnMap.get(gremlin.process.t.id);
+ const name = fnMap.get("name");
+ const changeLevel = fnMap.get("changeLevel");
+ // A boilerplate method (equals/toString/…) is surfaced only when the PR
+ // changed it meaningfully — a formatting-only touch is not enough.
+ const meaningfullyChanged = atLeast(changeLevel || "NONE", "BEHAVIORAL");
+
+ const inDegree = await g.V(vertexId).inE("calls").count().next();
+ // Out-degree optionally skips calls to library-origin externals (getName,
+ // toString, …) so ubiquitous JDK/accessor calls don't inflate the hotspot.
+ let outTraversal = g.V(vertexId).outE("calls");
+ if (excludeLibrary) {
+ outTraversal = outTraversal.where(__.inV().not(__.has("origin", "library")));
+ }
+ const outDegree = await outTraversal.count().next();
+
+ const inCount = inDegree.value;
+ const outCount = outDegree.value;
+ const totalDegree = inCount + outCount;
+
+ if (totalDegree < minDegree) continue;
+
+ const entry = {
+ name,
+ filePath: fnMap.get("filePath"),
+ signature: fnMap.get("signature"),
+ linesStart: fnMap.get("lines_start"),
+ linesEnd: fnMap.get("lines_end"),
+ changeLevel,
+ inDegree: inCount,
+ outDegree: outCount,
+ totalDegree,
+ inherentlyCentral: INHERENTLY_CENTRAL.has(name),
+ };
+
+ if (INHERENTLY_CENTRAL.has(name) && !meaningfullyChanged) {
+ filtered.push(entry);
+ } else {
+ results.push(entry);
+ }
+ }
+
+ results.sort((a, b) => b.totalDegree - a.totalDegree);
+
+ return {
+ hotspots: results.slice(0, topN),
+ totalAnalyzed: functions.length,
+ aboveThreshold: results.length,
+ filteredAsBoilerplate: filtered.length,
+ };
+}
diff --git a/.skills/tinker-review/scripts/patterns/classify-externals.js b/.skills/tinker-review/scripts/patterns/classify-externals.js
new file mode 100644
index 0000000000..e242d3f753
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/classify-externals.js
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { classifyExternalName } from "../graph/externals.js";
+
+const exec = promisify(execFile);
+
+// A precise, low-false-positive check: does a Java type declaration with this
+// exact name exist anywhere in the repo? Uses `git grep` in the worktree (fast,
+// respects the tree). Returns the first defining file, or null.
+async function definedAsProjectType(name, repoPath) {
+ if (!repoPath || !/^\w+$/.test(name)) return null;
+ try {
+ const { stdout } = await exec(
+ "git",
+ ["grep", "-lE", `(class|interface|enum|@interface)[[:space:]]+${name}\\b`],
+ { cwd: repoPath },
+ );
+ const files = stdout.split("\n").filter(Boolean);
+ return files[0] || null;
+ } catch {
+ // git grep exits non-zero when there is no match — treat as "not found".
+ return null;
+ }
+}
+
+/**
+ * Classify every external Function stub as library / project / unresolved and
+ * annotate the vertex with `origin` (and `definedIn` for project types). This
+ * lets structural checks drop library noise. Run it after populate and BEFORE
+ * centrality so the metric can exclude `origin: library`.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} repoPath - a git worktree to grep for project type definitions
+ * @returns {Promise<ExternalsResult>}
+ */
+
+/**
+ * @typedef {Object} ExternalsResult
+ * @property {number} total external-callee stubs classified
+ * @property {string[]} library names judged JDK/accessor noise (dropped from centrality out-degree)
+ * @property {{name: string, definedIn: string}[]} project names a repo type declares, with the file
+ * @property {string[]} unresolved neither a known library name nor a project type — unknown
+ */
+export async function classifyExternals(g, repoPath) {
+ const names = await g.V().hasLabel("Function").has("external", true).values("name").toList();
+
+ const classified = await Promise.all(names.map(async (name) => {
+ const definedIn = await definedAsProjectType(name, repoPath);
+ return { name, origin: classifyExternalName(name, Boolean(definedIn)), definedIn };
+ }));
+
+ const summary = { total: names.length, library: [], project: [], unresolved: [] };
+ for (const { name, origin, definedIn } of classified) {
+ let t = g.V().hasLabel("Function").has("external", true).has("name", name)
+ .property("origin", origin);
+ if (origin === "project" && definedIn) t = t.property("definedIn", definedIn);
+ await t.iterate();
+
+ if (origin === "project") summary.project.push({ name, definedIn });
+ else summary[origin].push(name);
+ }
+
+ return summary;
+}
diff --git a/.skills/tinker-review/scripts/patterns/cluster-analysis.js b/.skills/tinker-review/scripts/patterns/cluster-analysis.js
new file mode 100644
index 0000000000..6c7737c868
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/cluster-analysis.js
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { changedAny } from "../graph/change-levels.js";
+
+/**
+ * Determine whether a PR's changed files form one coherent change or multiple
+ * disconnected clusters. Uses connectedComponent() via the OLAP traversal source.
+ *
+ * A single cluster means the PR is one logical change. Multiple clusters suggest
+ * the PR bundles unrelated changes or has hidden dependencies the graph didn't capture.
+ *
+ * @param {object} a - gremlin-js GraphTraversalSource bound with withComputer() (the 'a' source)
+ * @param {object} params
+ * @param {boolean} [params.changedOnly] - Only analyze changed files (default: true)
+ * @returns {Promise<ClusterResult>}
+ */
+
+/**
+ * @typedef {Object} Cluster
+ * @property {number} id 1-based cluster index (largest first)
+ * @property {string[]} files file paths in this connected component
+ * @property {number} size files.length
+ *
+ * @typedef {Object} ClusterResult
+ * @property {number} clusterCount disconnected components among changed files
+ * @property {boolean} coherent true when the change is one logical unit (<= 1 cluster)
+ * @property {Cluster[]} clusters components, largest first
+ * @property {number} totalFiles changed files placed into clusters
+ */
+export async function clusterAnalysis(a, params = {}) {
+ const changedOnly = params.changedOnly !== false;
+
+ let traversal = a.V().hasLabel("File");
+ if (changedOnly) {
+ traversal = traversal.has("changeLevel", changedAny());
+ }
+
+ const results = await traversal
+ .connectedComponent()
+ .project("path", "component")
+ .by("path")
+ .by("gremlin.connectedComponentVertexProgram.component")
+ .toList();
+
+ const clusterMap = new Map();
+ for (const r of results) {
+ const path = r.get("path");
+ const component = r.get("component");
+ if (!clusterMap.has(component)) {
+ clusterMap.set(component, []);
+ }
+ clusterMap.get(component).push(path);
+ }
+
+ const clusters = [...clusterMap.values()]
+ .sort((a, b) => b.length - a.length)
+ .map((files, i) => ({
+ id: i + 1,
+ files,
+ size: files.length,
+ }));
+
+ return {
+ clusterCount: clusters.length,
+ coherent: clusters.length <= 1,
+ clusters,
+ totalFiles: results.length,
+ };
+}
diff --git a/.skills/tinker-review/scripts/patterns/community-detection.js b/.skills/tinker-review/scripts/patterns/community-detection.js
new file mode 100644
index 0000000000..51bc9d8d02
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/community-detection.js
@@ -0,0 +1,411 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import Graph from "graphology";
+import louvain from "graphology-communities-louvain";
+import { atLeast } from "../graph/change-levels.js";
+
+/**
+ * Louvain modularity community detection over the PR's *code* subgraph.
+ *
+ * Complements `clusterAnalysis` (connected components), which stays as the coarse
+ * "disjoint islands" guard. Connected components asks "is any changed file totally
+ * unreachable from the rest?"; that signal saturates at one component in a
+ * well-connected codebase. Community detection asks the finer question — "how many
+ * densely-tied themes does this change actually contain?" — and keeps giving signal
+ * even when everything is technically reachable.
+ *
+ * We run over Function/Type/File/Test vertices tied by code edges only. Discussion,
+ * Step, Doc and GrammarRule vertices are excluded on purpose: the PR vertex's
+ * `modifies` star and the `implements_step` hub would connect everything through a
+ * single node and collapse the modularity structure we are trying to surface.
+ *
+ * Louvain can occasionally emit an internally-disconnected community; a
+ * well-connectedness post-pass splits any such community back into its connected
+ * pieces (the one guarantee Leiden would give us natively, recovered cheaply at
+ * PR scale).
+ *
+ * Communities are detected at Function/Type grain and rolled up to the files they
+ * touch for reporting. Each vertex is stamped with a `community` property so a
+ * reviewer can query the partition directly (`g.V().has("community", n)`).
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (standard OLTP source)
+ * @param {object} params
+ * @param {number} [params.resolution] Louvain resolution (default: 1)
+ * @param {boolean} [params.writeBack] Stamp `community` onto vertices (default: true)
+ * @param {number} [params.minCommunitySize] Report communities at or above this size (default: 2)
+ * @param {object} [params.churn] Per-file `{ [path]: { added, removed, deleted } }`
+ * (from the diff) so communities can be described by *how* they changed — reduction
+ * vs. expansion — and the report can note that deleted code is absent from the graph.
+ * @returns {Promise<CommunityResult>}
+ */
+
+/** Confidence → edge weight. Stronger evidence pulls harder. */
+const WEIGHT = { EXTRACTED: 3, INFERRED: 2, AMBIGUOUS: 1 };
+
+const NODE_LABELS = ["Function", "Type", "File", "Test"];
+const EDGE_LABELS = ["calls", "defines", "declares", "extends", "implements", "overrides", "tests"];
+
+/**
+ * @typedef {Object} Community
+ * @property {number} id 0-based community index (largest first)
+ * @property {number} size member vertex count
+ * @property {string[]} files files this community touches (rolled up), largest share first
+ * @property {string} dominantFile the file contributing the most members
+ * @property {Object} labelCounts member count per vertex label (Function/Type/File/Test)
+ * @property {number} changedCount members meaningfully changed (BEHAVIORAL or STRUCTURAL)
+ * @property {string} dominantLabel most common vertex label
+ * @property {number} testShare fraction of members living in test files — drives the role
+ * @property {?Object} churn `{ added, removed, mode }` for the community's files, when churn is supplied
+ * @property {string} role human descriptor, e.g. "test scaffolding, reduced (−240/+12), spanning 3 files"
+ *
+ * @typedef {Object} CommunityResult
+ * @property {number} communityCount communities with size >= minCommunitySize
+ * @property {number} isolatedCount vertices with no in-subgraph code edge
+ * @property {number} modularity Louvain modularity of the partition (0..1)
+ * @property {number} splitCount communities split by the well-connectedness pass
+ * @property {?Object} churn `{ added, removed, deletedFiles }` across all changed files, when supplied
+ * @property {Community[]} communities communities >= minCommunitySize, largest first
+ * @property {number} totalNodes vertices fed to Louvain
+ * @property {number} totalEdges undirected edges after weight-merging
+ */
+export async function communityDetection(g, params = {}) {
+ const { nodes, edges } = await extractCodeSubgraph(g);
+ const result = detectCommunities(nodes, edges, params);
+
+ if (params.writeBack !== false && result.assignments) {
+ await writeBackCommunities(g, result.assignments);
+ }
+ delete result.assignments;
+ return result;
+}
+
+/**
+ * Pull the code subgraph out as flat node/edge lists via `elementMap`. Edge
+ * `elementMap` carries the incident vertices (IN/OUT) and the edge's `confidence`
+ * in one step, so no `by()` projection is needed. A separate vertex query captures
+ * nodes with no in-subgraph edge (meaningful singletons) that the edge query alone
+ * would never surface.
+ */
+async function extractCodeSubgraph(g) {
+ const vRaw = await g.V().hasLabel(...NODE_LABELS).hasNot("external").hasNot("parsed").elementMap().toList();
+ const eRaw = await g.E().hasLabel(...EDGE_LABELS).elementMap().toList();
+
+ const nodes = vRaw.map((m) => {
+ const o = mapToObj(m);
+ // "changed" here means a meaningful change (BEHAVIORAL/STRUCTURAL); the
+ // changed-share reading distinguishes real change from context, and a
+ // formatting-only touch is context for that purpose.
+ return { id: String(o.id), label: o.label, name: o.name, filePath: o.filePath || o.path, changed: atLeast(o.changeLevel || "NONE", "BEHAVIORAL") };
+ });
+
+ const edges = eRaw.map((m) => {
+ const o = mapToObj(m);
+ return { from: String(o.OUT.id), to: String(o.IN.id), conf: o.confidence };
+ });
+
+ return { nodes, edges };
+}
+
+/**
+ * Pure community detection over plain node/edge lists — no graph I/O, so it is
+ * unit-testable without a server.
+ *
+ * @param {Array<{id,label,name,filePath}>} nodes
+ * @param {Array<{from,to,conf}>} edges
+ * @param {object} params - see communityDetection; `params.churn` is an optional
+ * per-file `{ [path]: { added, removed, deleted } }` map (all changed files, not
+ * just clustered ones) that lets each community be described by *how* it changed.
+ * @returns {CommunityResult & { assignments: Map<string, number> }}
+ */
+export function detectCommunities(nodes, edges, params = {}) {
+ const resolution = params.resolution || 1;
+ const minSize = params.minCommunitySize || 2;
+ const churn = params.churn || null;
+
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
+ const graph = new Graph({ type: "undirected", multi: false, allowSelfLoops: false });
+ for (const n of nodes) graph.addNode(n.id);
+
+ for (const e of edges) {
+ if (e.from === e.to) continue;
+ if (!graph.hasNode(e.from) || !graph.hasNode(e.to)) continue; // endpoint was filtered out
+ const w = WEIGHT[e.conf] || 1;
+ if (graph.hasEdge(e.from, e.to)) {
+ graph.updateEdgeAttribute(e.from, e.to, "weight", (x) => (x || 0) + w);
+ } else {
+ graph.addEdge(e.from, e.to, { weight: w });
+ }
+ }
+
+ let communities = {};
+ let modularity = 0;
+ if (graph.size > 0) {
+ const detailed = louvain.detailed(graph, { getEdgeWeight: "weight", resolution });
+ communities = detailed.communities;
+ modularity = detailed.modularity;
+ } else {
+ // No edges: every node is its own community.
+ graph.forEachNode((n, _attr) => { communities[n] = graph.nodes().indexOf(n); });
+ }
+
+ const { assignments, splitCount } = splitDisconnected(graph, communities);
+
+ // Group members by final community id.
+ const members = new Map();
+ for (const [id, comm] of assignments) {
+ if (!members.has(comm)) members.set(comm, []);
+ members.get(comm).push(id);
+ }
+
+ const built = [...members.entries()]
+ .map(([, ids]) => rollUp(ids, nodeById, churn))
+ .sort((a, b) => b.size - a.size);
+
+ const communityList = built.filter((c) => c.size >= minSize).map((c, i) => ({ ...c, id: i }));
+ const isolatedCount = built.filter((c) => c.size < minSize).length;
+
+ return {
+ communityCount: communityList.length,
+ isolatedCount,
+ modularity: Number(modularity.toFixed(4)),
+ splitCount,
+ communities: communityList,
+ churn: globalChurn(churn),
+ interpretation: interpret(communityList, modularity, churn),
+ totalNodes: graph.order,
+ totalEdges: graph.size,
+ assignments,
+ };
+}
+
+/** Sum churn across all changed files, and count how many were deleted outright. */
+function globalChurn(churn) {
+ if (!churn) return null;
+ let added = 0, removed = 0, deletedFiles = 0;
+ for (const c of Object.values(churn)) {
+ added += c.added || 0;
+ removed += c.removed || 0;
+ if (c.deleted) deletedFiles++;
+ }
+ return { added, removed, deletedFiles };
+}
+
+/**
+ * Turn the raw partition into a reading a human can act on, deterministically.
+ * The headline grades separation by modularity; the bullets call out what the
+ * dense structure is *made of* (e.g. all test scaffolding — a real signal for a
+ * removal PR, where deleted production code leaves nothing to cluster) and how
+ * much of it the PR actually changed versus context pulled in for shape.
+ */
+function interpret(communities, modularity, churn) {
+ if (communities.length === 0) {
+ return { headline: "No thematic structure: the change has no densely-connected group of two or more code vertices.", reading: [] };
+ }
+
+ const headline = modularity < 0.3
+ ? `Diffuse (modularity ${modularity.toFixed(2)}): the change reads as one loosely-connected mass rather than separable themes.`
+ : modularity > 0.7
+ ? `Sharply themed (modularity ${modularity.toFixed(2)}): ${communities.length} clearly separated communities.`
+ : `Moderately themed (modularity ${modularity.toFixed(2)}): ${communities.length} distinguishable communities with some cross-talk.`;
+
+ const reading = [];
+ const testDom = communities.filter((c) => (c.testShare ?? 0) >= 0.8).length;
+ if (testDom === communities.length) {
+ reading.push("Every community is test infrastructure. The production code this change touches has too few internal call edges to cluster — typical when code is removed or thinned — so the densest remaining structure is the test scaffolding around it. Read these as the test areas the change disturbs, not new functional groupings.");
+ } else if (testDom > communities.length / 2) {
+ reading.push(`${testDom} of ${communities.length} communities are test infrastructure, so the change's dense structure sits more in tests than in production code.`);
+ }
+
+ const g = globalChurn(churn);
+ if (g && (g.added > 0 || g.removed > 0)) {
+ const net = g.added - g.removed;
+ const direction = net < 0 ? "net-deletion" : net > 0 ? "net-addition" : "balanced";
+ reading.push(`This change is ${direction} overall (−${g.removed}/+${g.added} lines). ${net < 0 ? "The communities describe surviving structure being trimmed, not new structure being built." : "The communities describe structure being grown or reworked."}`);
+ if (g.deletedFiles > 0) {
+ reading.push(`${g.deletedFiles} file(s) were deleted outright. Deleted code has no vertices, so it is absent from every community — these themes show only the surviving structure the removal reached into. See Removal References for what was actually removed.`);
+ }
+ } else {
+ const total = communities.reduce((s, c) => s + c.size, 0);
+ const changed = communities.reduce((s, c) => s + c.changedCount, 0);
+ const share = total ? Math.round((changed / total) * 100) : 0;
+ reading.push(`${share}% of clustered vertices are actually changed by this PR; the rest is surrounding context pulled in to give the change structural shape.`);
+ }
+
+ return { headline, reading };
+}
+
+/**
+ * Describe what a community is: its kind (test scaffolding / call cluster / …),
+ * how it changed, and its file span. When churn is known it drives the change
+ * clause (real line counts beat the changed/unchanged vertex-share heuristic);
+ * otherwise we fall back to that share.
+ */
+function describeRole(label, changedShare, fileCount, testShare, churnSummary) {
+ const kind = testShare >= 0.6 ? "test scaffolding"
+ : label === "Type" ? "type hierarchy"
+ : label === "File" ? "file group"
+ : "call cluster";
+ const change = churnSummary
+ ? `${churnSummary.mode} (−${churnSummary.removed}/+${churnSummary.added})`
+ : changedShare >= 0.6 ? "mostly changed"
+ : changedShare <= 0.2 ? "mostly context"
+ : "mixed changed/context";
+ const span = fileCount > 1 ? `spanning ${fileCount} files` : "within one file";
+ return `${kind}, ${change}, ${span}`;
+}
+
+/**
+ * Well-connectedness pass: within each Louvain community, find connected pieces
+ * (using the code subgraph's own edges) and give each piece its own community id.
+ * A community that is already internally connected passes through unchanged; a
+ * disconnected one is split. This recovers Leiden's connectedness guarantee.
+ */
+function splitDisconnected(graph, communities) {
+ const byComm = new Map();
+ for (const [node, c] of Object.entries(communities)) {
+ if (!byComm.has(c)) byComm.set(c, []);
+ byComm.get(c).push(node);
+ }
+
+ const assignments = new Map();
+ let nextId = 0;
+ let splitCount = 0;
+
+ for (const memberNodes of byComm.values()) {
+ const memberSet = new Set(memberNodes);
+ const seen = new Set();
+ let pieces = 0;
+ for (const start of memberNodes) {
+ if (seen.has(start)) continue;
+ pieces++;
+ const id = nextId++;
+ const queue = [start];
+ seen.add(start);
+ while (queue.length) {
+ const u = queue.pop();
+ assignments.set(u, id);
+ graph.forEachNeighbor(u, (nb) => {
+ if (memberSet.has(nb) && !seen.has(nb)) { seen.add(nb); queue.push(nb); }
+ });
+ }
+ }
+ if (pieces > 1) splitCount++;
+ }
+
+ return { assignments, splitCount };
+}
+
+/** Roll a community's member vertices up to files, label mix, churn, and a role descriptor. */
+function rollUp(ids, nodeById, churn) {
+ const fileCounts = new Map();
+ const labelCounts = {};
+ let changedCount = 0;
+ for (const id of ids) {
+ const n = nodeById.get(id);
+ if (!n) continue;
+ if (n.filePath) fileCounts.set(n.filePath, (fileCounts.get(n.filePath) || 0) + 1);
+ labelCounts[n.label] = (labelCounts[n.label] || 0) + 1;
+ if (n.changed) changedCount++;
+ }
+ let testCount = 0;
+ for (const id of ids) {
+ const n = nodeById.get(id);
+ if (n && isTestFile(n.filePath)) testCount++;
+ }
+ const files = [...fileCounts.entries()].sort((a, b) => b[1] - a[1]).map(([f]) => f);
+ const dominantLabel = Object.entries(labelCounts).sort((a, b) => b[1] - a[1])[0]?.[0] || "Function";
+ const testShare = ids.length ? testCount / ids.length : 0;
+
+ // Roll churn up over the community's *distinct* files (a file counts once even
+ // when several member functions live in it).
+ let churnSummary = null;
+ if (churn) {
+ let added = 0, removed = 0, withChurn = 0;
+ for (const f of files) {
+ if (churn[f]) { added += churn[f].added || 0; removed += churn[f].removed || 0; withChurn++; }
+ }
+ if (withChurn > 0) churnSummary = { added, removed, mode: churnMode(added, removed) };
+ }
+
+ return {
+ size: ids.length,
+ files,
+ dominantFile: files[0] || null,
+ labelCounts,
+ changedCount,
+ dominantLabel,
+ testShare,
+ churn: churnSummary,
+ role: describeRole(dominantLabel, ids.length ? changedCount / ids.length : 0, files.length, testShare, churnSummary),
+ };
+}
+
+/** Classify a community's net churn: dominated by removals, additions, or balanced. */
+function churnMode(added, removed) {
+ if (added === 0 && removed > 0) return "purely reduced";
+ if (removed > added * 2) return "reduced";
+ if (added > removed * 2) return "expanded";
+ return "reworked";
+}
+
+/**
+ * Is this a test file? Test methods extract as Function vertices, so the vertex
+ * label alone under-counts test-ness; the file path is the reliable tell.
+ */
+function isTestFile(p) {
+ if (!p) return false;
+ if (/(^|\/)(test|tests)\//i.test(p)) return true;
+ const base = p.split("/").pop() || "";
+ return /(Test|Tests|IT|ITCase|TestCase)\.\w+$/.test(base) || /(^test_|_test)\.\w+$/.test(base) || /\.test\.\w+$/.test(base);
+}
+
+/**
+ * Stamp each vertex with its final `community` id. One traversal per community
+ * (`V(...ids).property(...)`) keeps this to a handful of round trips.
+ */
+async function writeBackCommunities(g, assignments) {
+ const byComm = new Map();
+ for (const [id, comm] of assignments) {
+ if (!byComm.has(comm)) byComm.set(comm, []);
+ byComm.get(comm).push(coerceId(id));
+ }
+ for (const [comm, ids] of byComm) {
+ await g.V(...ids).property("community", comm).iterate();
+ }
+}
+
+/** TinkerGraph ids are numeric; ids arrive as strings from our node keys. */
+function coerceId(id) {
+ const n = Number(id);
+ return Number.isNaN(n) ? id : n;
+}
+
+/**
+ * Convert a gremlin `elementMap` Map into a plain object, keying by the enum's
+ * element name so `t.id`/`t.label` become `id`/`label` and the edge adjacency
+ * `Direction.IN`/`Direction.OUT` become `IN`/`OUT`. Nested vertex maps (on edges)
+ * are converted recursively. Avoids depending on driver enum singleton identity.
+ */
+function mapToObj(m) {
+ if (!(m instanceof Map)) return m;
+ const o = {};
+ for (const [k, v] of m) o[String(k)] = v instanceof Map ? mapToObj(v) : v;
+ return o;
+}
diff --git a/.skills/tinker-review/scripts/patterns/completeness.js b/.skills/tinker-review/scripts/patterns/completeness.js
new file mode 100644
index 0000000000..a4630edaed
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/completeness.js
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import gremlin from "gremlin";
+
+/**
+ * Check that a vertex has all expected outgoing/incoming edge labels.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource
+ * @param {object} params
+ * @param {string} params.vertexLabel - Label of vertex to check (e.g., "Step")
+ * @param {string} [params.vertexName] - Name property to filter by
+ * @param {string[]} params.expectedEdges - Edge labels that should exist
+ * Prefix with "in:" or "out:" for direction (default: "out:")
+ * e.g., ["out:has_rule", "in:implements_step", "in:covers", "in:documents"]
+ * @returns {Promise<CompletenessResult[]>}
+ */
+
+/**
+ * @typedef {Object} CompletenessResult
+ * @property {string} node the vertex checked (name or identifier)
+ * @property {string[]} present expected edge specs that exist (e.g. "out:defines")
+ * @property {string[]} missing expected edge specs that are absent — the gaps to weigh
+ * @property {number} score present / (present + missing), 0..1
+ */
+export async function completeness(g, params) {
+ const { vertexLabel, vertexName, expectedEdges } = params;
+
+ let traversal = g.V().hasLabel(vertexLabel);
+ if (vertexName) {
+ traversal = traversal.has("name", vertexName);
+ }
+
+ const vertices = await traversal.elementMap().toList();
+
+ const results = [];
+
+ for (const vertexMap of vertices) {
+ const vertexId = vertexMap.get(gremlin.process.t.id);
+ const name = vertexMap.get("name") || String(vertexId);
+
+ const present = [];
+ const missing = [];
+
+ for (const edgeSpec of expectedEdges) {
+ const { direction, label } = parseEdgeSpec(edgeSpec);
+ const exists = await edgeExists(g, vertexId, direction, label);
+
+ if (exists) {
+ present.push(edgeSpec);
+ } else {
+ missing.push(edgeSpec);
+ }
+ }
+
+ const total = present.length + missing.length;
+ const score = total > 0 ? present.length / total : 1;
+
+ results.push({ node: name, present, missing, score });
+ }
+
+ return results;
+}
+
+function parseEdgeSpec(spec) {
+ if (spec.startsWith("in:")) {
+ return { direction: "in", label: spec.slice(3) };
+ }
+ if (spec.startsWith("out:")) {
+ return { direction: "out", label: spec.slice(4) };
+ }
+ return { direction: "out", label: spec };
+}
+
+async function edgeExists(g, vertexId, direction, label) {
+ let traversal;
+ if (direction === "in") {
+ traversal = g.V(vertexId).inE(label);
+ } else {
+ traversal = g.V(vertexId).outE(label);
+ }
+
+ const edges = await traversal.limit(1).toList();
+ return edges.length > 0;
+}
diff --git a/.skills/tinker-review/scripts/patterns/confidence-audit.js b/.skills/tinker-review/scripts/patterns/confidence-audit.js
new file mode 100644
index 0000000000..29d6cb326f
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/confidence-audit.js
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import gremlin from "gremlin";
+import { CONFIDENCE } from "../graph/confidence.js";
+
+const { process: { statics: __ } } = gremlin;
+
+// Pick a human-readable label for a vertex from whichever identifying property
+// it carries. Different labels key on different properties (Function/Type/Step
+// use name, File uses path, Discussion uses url/title).
+function describeVertex(elementMap) {
+ if (!elementMap) return "?";
+ const get = (k) => {
+ const v = elementMap.get ? elementMap.get(k) : elementMap[k];
+ return v == null ? undefined : String(v);
+ };
+ const labelKey = gremlin.process.t.label;
+ const label = (elementMap.get ? elementMap.get(labelKey) : elementMap["label"]) || "";
+ const name = get("name") || get("title") || get("path") || get("url") || "?";
+ return label ? `${label}(${name})` : name;
+}
+
+/**
+ * Audit the knowledge graph by edge confidence. Returns the distribution across
+ * EXTRACTED / INFERRED / AMBIGUOUS (plus UNTAGGED for any edge missing the
+ * property) and the full list of AMBIGUOUS edges — the ones flagged for human
+ * review. Since it reads the live graph it reflects enrichment edges too when
+ * run after Phase 2.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} [params]
+ * @param {number} [params.maxAmbiguous] - Cap the AMBIGUOUS edge list (default 50)
+ * @returns {Promise<ConfidenceResult>}
+ */
+
+/**
+ * @typedef {Object} EdgeConfidenceRow
+ * @property {string} relation edge label (calls, implements_step, addresses, …)
+ * @property {string} [confidence] the edge's confidence value
+ * @property {string} from described source vertex, e.g. "Function(foo)"
+ * @property {string} to described target vertex
+ * @property {string} [foundIn] provenance for discussion links (pr, search, …)
+ * @property {string} [foundVia]
+ *
+ * @typedef {Object} ConfidenceResult
+ * @property {{EXTRACTED:number, INFERRED:number, AMBIGUOUS:number, UNTAGGED:number}} distribution edge counts by confidence
+ * @property {number} total count of all edges
+ * @property {EdgeConfidenceRow[]} ambiguous AMBIGUOUS edges — flagged for human review
+ */
+export async function confidenceAudit(g, params = {}) {
+ const maxAmbiguous = params.maxAmbiguous || 50;
+
+ // Distribution over every edge; edges predating this feature (or any we missed)
+ // fall into UNTAGGED so the audit stays honest about coverage.
+ const grouped = await g.E()
+ .groupCount()
+ .by(__.coalesce(__.values("confidence"), __.constant("UNTAGGED")))
+ .next();
+
+ const distribution = { EXTRACTED: 0, INFERRED: 0, AMBIGUOUS: 0, UNTAGGED: 0 };
+ let total = 0;
+ const gm = grouped.value;
+ if (gm) {
+ const entries = gm instanceof Map ? gm.entries() : Object.entries(gm);
+ for (const [key, count] of entries) {
+ const n = Number(count);
+ distribution[key] = (distribution[key] || 0) + n;
+ total += n;
+ }
+ }
+
+ const ambiguous = await listEdgesByConfidence(g, {
+ confidence: CONFIDENCE.AMBIGUOUS,
+ limit: maxAmbiguous,
+ });
+
+ return { distribution, total, ambiguous };
+}
+
+/**
+ * List edges at a given confidence, optionally narrowed to one relation, with
+ * both endpoints described. The building block behind confidenceAudit's
+ * AMBIGUOUS list and the agent-facing listInferred worklist.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} [opts]
+ * @param {string} [opts.confidence] - Filter to this confidence value
+ * @param {string} [opts.relation] - Filter to this edge label (e.g. implements_step)
+ * @param {number} [opts.limit] - Cap the result count (default 100)
+ * @returns {Promise<EdgeConfidenceRow[]>}
+ */
+export async function listEdgesByConfidence(g, opts = {}) {
+ const { confidence, relation, limit = 100 } = opts;
+ let t = g.E();
+ if (relation) t = t.hasLabel(relation);
+ if (confidence) t = t.has("confidence", confidence);
+
+ const rows = await t
+ .limit(limit)
+ .project("relation", "confidence", "found_in", "found_via", "from", "to")
+ .by(__.label())
+ .by(__.coalesce(__.values("confidence"), __.constant("")))
+ .by(__.coalesce(__.values("found_in"), __.constant("")))
+ .by(__.coalesce(__.values("found_via"), __.constant("")))
+ .by(__.outV().elementMap())
+ .by(__.inV().elementMap())
+ .toList();
+
+ return rows.map((row) => ({
+ relation: row.get("relation"),
+ confidence: row.get("confidence") || undefined,
+ from: describeVertex(row.get("from")),
+ to: describeVertex(row.get("to")),
+ foundIn: row.get("found_in") || undefined,
+ foundVia: row.get("found_via") || undefined,
+ }));
+}
+
+/**
+ * Agent verification worklist: the INFERRED edges (name-resolved calls, agent
+ * step/doc mappings) that warrant a source check. After verifying, the agent
+ * uses setEdgeConfidence to promote a confirmed edge to EXTRACTED or downgrade a
+ * wrong one to AMBIGUOUS.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {object} [params]
+ * @param {string} [params.relation] - Narrow to one relation (e.g. implements_step)
+ * @param {number} [params.limit] - Cap results (default 100)
+ * @returns {Promise<EdgeConfidenceRow[]>}
+ */
+export async function listInferred(g, params = {}) {
+ return listEdgesByConfidence(g, {
+ confidence: CONFIDENCE.INFERRED,
+ relation: params.relation,
+ limit: params.limit || 100,
+ });
+}
diff --git a/.skills/tinker-review/scripts/patterns/coverage-gaps.js b/.skills/tinker-review/scripts/patterns/coverage-gaps.js
new file mode 100644
index 0000000000..7cbd763665
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/coverage-gaps.js
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import gremlin from "gremlin";
+import { changedMeaningful } from "../graph/change-levels.js";
+
+/**
+ * Find changed functions that have no incoming 'tests' edge.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource
+ * @param {object} params
+ * @param {boolean} [params.changedOnly] - Only check meaningfully-changed functions
+ * — BEHAVIORAL or STRUCTURAL (default: true)
+ * @returns {Promise<CoverageGapResult>}
+ */
+
+/**
+ * @typedef {Object} UncoveredFunction
+ * @property {string} name
+ * @property {string} signature
+ * @property {string} filePath
+ * @property {number} linesStart
+ * @property {number} linesEnd
+ *
+ * @typedef {Object} CoverageGapResult
+ * @property {UncoveredFunction[]} uncovered changed functions with no incoming `tests` edge
+ * @property {number} totalChanged changed functions considered
+ * @property {number} totalCovered changed functions that do have a test
+ */
+export async function coverageGaps(g, params = {}) {
+ const changedOnly = params.changedOnly !== false;
+
+ let traversal = g.V().hasLabel("Function");
+ if (changedOnly) {
+ // A formatting-only change does not create a coverage gap; a real body or
+ // signature change without a test does.
+ traversal = traversal.has("changeLevel", changedMeaningful());
+ }
+
+ const functions = await traversal.elementMap().toList();
+
+ const testFilePaths = new Set(
+ (await g.V().hasLabel("Test").values("filePath").toList())
+ );
+
+ const nonTestFunctions = functions.filter(
+ (fnMap) => !testFilePaths.has(fnMap.get("filePath"))
+ );
+
+ const totalChanged = nonTestFunctions.length;
+ const uncovered = [];
+
+ for (const fnMap of nonTestFunctions) {
+ const vertexId = fnMap.get(gremlin.process.t.id);
+ const hasTest = await g.V(vertexId).inE("tests").limit(1).toList();
+
+ if (hasTest.length === 0) {
+ uncovered.push({
+ name: fnMap.get("name"),
+ signature: fnMap.get("signature"),
+ filePath: fnMap.get("filePath"),
+ linesStart: fnMap.get("lines_start"),
+ linesEnd: fnMap.get("lines_end"),
+ });
+ }
+ }
+
+ const totalCovered = totalChanged - uncovered.length;
+
+ return { uncovered, totalChanged, totalCovered };
+}
diff --git a/.skills/tinker-review/scripts/patterns/orphans.js b/.skills/tinker-review/scripts/patterns/orphans.js
new file mode 100644
index 0000000000..15bf96b07c
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/orphans.js
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import gremlin from "gremlin";
+import { changedAny } from "../graph/change-levels.js";
+
+/**
+ * Find orphan vertices — nodes that are missing expected relationships.
+ * Useful for detecting undocumented functions, untested steps, or
+ * disconnected code.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource
+ * @param {object} params
+ * @param {string} params.vertexLabel - Label to check (e.g., "Step", "Function")
+ * @param {string} params.expectedEdge - Edge label that should exist
+ * @param {string} [params.direction] - "in" or "out" (default: "in")
+ * @param {boolean} [params.changedOnly] - Only check changed vertices — any level
+ * but NONE (default: false)
+ * @returns {Promise<OrphanResult>}
+ */
+
+/**
+ * @typedef {Object} Orphan
+ * @property {string} name
+ * @property {string} label vertex label checked (Function, Step, …)
+ * @property {string} filePath
+ * @property {string} missingEdge the expected relationship that is absent (e.g. "in:tests")
+ *
+ * @typedef {Object} OrphanResult
+ * @property {Orphan[]} orphaned vertices missing the expected relationship
+ * @property {number} totalChecked vertices examined
+ * @property {number} totalOrphaned orphaned.length
+ */
+export async function orphans(g, params) {
+ const { vertexLabel, expectedEdge } = params;
+ const direction = params.direction || "in";
+ const changedOnly = params.changedOnly || false;
+
+ let traversal = g.V().hasLabel(vertexLabel);
+ if (changedOnly) {
+ traversal = traversal.has("changeLevel", changedAny());
+ }
+
+ const vertices = await traversal.elementMap().toList();
+ const orphaned = [];
+
+ for (const vMap of vertices) {
+ const vertexId = vMap.get(gremlin.process.t.id);
+
+ let edgeTraversal;
+ if (direction === "in") {
+ edgeTraversal = g.V(vertexId).inE(expectedEdge);
+ } else {
+ edgeTraversal = g.V(vertexId).outE(expectedEdge);
+ }
+
+ const edges = await edgeTraversal.limit(1).toList();
+ if (edges.length === 0) {
+ orphaned.push({
+ name: vMap.get("name") || vMap.get("path") || String(vertexId),
+ label: vertexLabel,
+ filePath: vMap.get("filePath") || vMap.get("path"),
+ missingEdge: `${direction}:${expectedEdge}`,
+ });
+ }
+ }
+
+ return {
+ orphaned,
+ totalChecked: vertices.length,
+ totalOrphaned: orphaned.length,
+ };
+}
diff --git a/.skills/tinker-review/scripts/patterns/removal-refs.js b/.skills/tinker-review/scripts/patterns/removal-refs.js
new file mode 100644
index 0000000000..9d4792ccbe
--- /dev/null
+++ b/.skills/tinker-review/scripts/patterns/removal-refs.js
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { CONFIDENCE } from "../graph/confidence.js";
+import { symbolFromPath, isCodeFile, createReferenceEdge } from "../graph/references.js";
+
+const exec = promisify(execFile);
+
+// Whole-word search for a symbol across the PR-head worktree. Returns one hit
+// per file (first line), since deleted files no longer exist in the worktree the
+// results are surviving references only. `git grep` exits non-zero on no match.
+async function gitGrepWord(symbol, repoPath) {
+ try {
+ const { stdout } = await exec("git", ["grep", "-nw", symbol], {
+ cwd: repoPath,
+ maxBuffer: 16 * 1024 * 1024,
+ });
+ const firstLineByFile = new Map();
+ for (const line of stdout.split("\n")) {
+ const m = line.match(/^([^:]+):(\d+):/);
+ if (m && !firstLineByFile.has(m[1])) firstLineByFile.set(m[1], m[2]);
+ }
+ return [...firstLineByFile.entries()].map(([file, ln]) => ({ file, line: `L${ln}` }));
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Phase-1 removal-impact pass. Mechanical mirror of classifyExternals: for every
+ * deleted *code* file, grep the surviving worktree for its symbol and auto-create
+ * a `references` edge (INFERRED) for each hit. Finding the references is
+ * reproducible; classifying them (blocking vs. benign historical note) is the
+ * agent's judgment in the report. Config/non-code symbols are skipped here and
+ * left to the addReference escape hatch.
+ *
+ * @param {object} g - gremlin-js GraphTraversalSource (already connected)
+ * @param {string} repoPath - a git worktree (PR-head) to grep
+ * @returns {Promise<RemovalRefsResult>}
+ */
+
+/**
+ * @typedef {Object} RemovalReference
+ * @property {string} from surviving file that still names the removed symbol
+ * @property {string} to the deleted file path
+ * @property {string} symbol the removed symbol matched
+ * @property {string} location first line in `from` (e.g. "L42")
+ *
+ * @typedef {Object} RemovalRefsResult
+ * @property {string[]} deletedCodeSymbols symbols of deleted code files that were searched
+ * @property {RemovalReference[]} references surviving references found (also written as edges)
+ * @property {string[]} externalCallers external-callee stubs whose name matches a deleted
+ * symbol — changed code still calling removed code
+ * @property {number} total references.length
+ */
+export async function findRemovalRefs(g, repoPath) {
+ const deletedPaths = await g.V().hasLabel("File").has("deleted", true).values("path").toList();
+ const result = { deletedCodeSymbols: [], references: [], externalCallers: [], total: 0 };
+ if (deletedPaths.length === 0) return result;
+
+ const deletedSymbolSet = new Set(deletedPaths.map(symbolFromPath));
+
+ for (const path of deletedPaths) {
+ if (!isCodeFile(path)) continue;
+ const symbol = symbolFromPath(path);
+ if (!/^\w+$/.test(symbol)) continue;
+ result.deletedCodeSymbols.push(symbol);
+
+ for (const { file, line } of await gitGrepWord(symbol, repoPath)) {
+ await createReferenceEdge(g, {
+ fromPath: file,
+ toPath: path,
+ symbol,
+ location: line,
+ confidence: CONFIDENCE.INFERRED,
+ });
+ result.references.push({ from: file, to: path, symbol, location: line });
+ }
+ }
+
+ // In-graph dangling references: a changed function still calls a name that a
+ // deleted file defined (surfaced from the external-callee stubs, no grep).
+ const externalStubs = await g.V().hasLabel("Function").has("external", true).values("name").toList();
+ result.externalCallers = externalStubs.filter((n) => deletedSymbolSet.has(n));
+
+ result.total = result.references.length;
+ return result;
+}
diff --git a/.skills/tinker-review/scripts/renderer/render.js b/.skills/tinker-review/scripts/renderer/render.js
new file mode 100644
index 0000000000..6b4e3fe36f
--- /dev/null
+++ b/.skills/tinker-review/scripts/renderer/render.js
@@ -0,0 +1,612 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const TEMPLATE = readFileSync(join(__dirname, "template.html"), "utf-8");
+
+function esc(str) {
+ return String(str || "")
+ .replace(/&/g, "&")
+ .replace(/</g, "<")
+ .replace(/>/g, ">")
+ .replace(/"/g, """);
+}
+
+// Render a function/type's change level as a badge. STRUCTURAL (signature churn)
+// reads loudest; BEHAVIORAL is a body change; FORMATTING is muted; NONE shows
+// nothing.
+function changeLevelBadge(level) {
+ switch (level) {
+ case "STRUCTURAL": return `<span class="badge badge-structural">structural</span>`;
+ case "BEHAVIORAL": return `<span class="badge badge-modified">behavioral</span>`;
+ case "FORMATTING": return `<span class="badge badge-formatting">formatting</span>`;
+ default: return "";
+ }
+}
+
+/**
+ * Fields typed as raw *code* (appendixFunctional.testCode / .fullOutput) are
+ * wrapped by the renderer in its own `<pre><code>` and escaped. Agents
+ * sometimes pre-wrap the value in `<pre>`, `<code>`, or `<p>` anyway; escaping
+ * that renders the tags literally. Strip a single leading/trailing wrapper of
+ * those kinds so a slip degrades to clean text instead of visible markup. This
+ * is a lenient guard, not an HTML sanitizer — the field contract is raw text.
+ */
+function stripCodeWrapper(str) {
+ let s = String(str || "").trim();
+ const wrapper = /^<(pre|code|p)(?:\s[^>]*)?>([\s\S]*)<\/\1>$/i;
+ // Peel nested wrappers (e.g. `<pre><code>…</code></pre>`), up to two layers.
+ // Only peel an *unambiguous* single wrapper: if the inner content still holds
+ // the same tag, the string is not one wrapper (e.g. two sibling `<code>`
+ // blocks), so leave it alone rather than over-strip.
+ for (let i = 0; i < 2; i++) {
+ const m = s.match(wrapper);
+ if (!m) break;
+ const inner = m[2].trim();
+ if (new RegExp(`</${m[1]}>`, "i").test(inner)) break;
+ s = inner;
+ }
+ return s;
+}
+
+/**
+ * Render the full report from evidence data + agent narrative.
+ * Output matches the structure of reference-report.html exactly.
+ *
+ * Input contract — data fields (from review.js):
+ * meta: { pr, title, domains: [], language, changedFileCount, timestamp }
+ * graphStats: { vertices, edges, breakdown: { files, functions, types, tests, calls } }
+ * checks: { completeness, coverageGaps, centrality, blastRadius, clusters, confidence }
+ * discussions: { jiras, devList, secondary, prComments, devListSearchKeywords, ... }
+ * changedFiles: []
+ *
+ * Input contract — narrative fields (from agent/synthesize.js):
+ * summary: "HTML string"
+ * clusters: { svg: "<svg>...</svg>", assessment: "HTML string" }
+ * guidedWalk: [{ title, badge: "attention|info|safe", badgeText, body: "HTML" }]
+ * functionalTest: { plan: "HTML", results: [{name, pass, output}], observations: ["HTML"] }
+ * (results rows are THEME-level, each naming the scenario labels it covers)
+ * findings: [{ title, snippet: "code", body: "HTML" }]
+ * openQuestions: [{ title, body: "HTML", meta: "string" }]
+ * appendixFunctional: { environment: "HTML", testCode: "raw text", fullOutput: "raw text" }
+ * (testCode = the COMPLETE labeled battery; renderer wraps it in <pre><code>, do NOT pre-wrap)
+ */
+function notProvided(sectionId, title) {
+ return `<section id="${sectionId}">\n <h2>${esc(title)}</h2>\n <p class="section-intro" style="color: var(--danger);">Section not provided.</p>\n</section>`;
+}
+
+export function render(evidence) {
+ const { meta, graphStats, checks, discussions, summary, clusters, communityAssessment,
+ guidedWalk, functionalTest, findings, openQuestions, appendixFunctional } = evidence;
+
+ const parts = [];
+ parts.push(renderHeader(meta));
+ parts.push(renderNav());
+ parts.push(summary ? renderSummary(summary) : notProvided("summary", "Summary"));
+ parts.push(discussions ? renderContext(discussions) : notProvided("context", "Discovered Context"));
+ parts.push(renderClusters(clusters, checks && checks.clusters, evidence.architecture));
+ parts.push(renderCommunitySection(checks && checks.communities, communityAssessment));
+ parts.push(guidedWalk && guidedWalk.length > 0 ? renderGuidedWalk(guidedWalk) : notProvided("guided-walk", "Guided Walk"));
+ parts.push(functionalTest ? renderFunctionalTest(functionalTest) : notProvided("functional-test", "Functional Test"));
+ parts.push(findings && findings.length > 0 ? renderFindings(findings) : notProvided("findings", "Findings"));
+ parts.push(openQuestions && openQuestions.length > 0 ? renderOpenQuestions(openQuestions) : notProvided("open-questions", "Open Questions"));
+ parts.push(renderAppendixStructural(checks, graphStats));
+ parts.push(appendixFunctional ? renderAppendixFunctional(appendixFunctional) : notProvided("appendix-functional", "Appendix: Functional Test Details"));
+ parts.push(`<footer>Graph Review — Apache TinkerPop | PR #${esc(String(meta.pr))} | Generated ${esc(meta.timestamp)}</footer>`);
+
+ return TEMPLATE.replace("{{content}}", parts.join("\n\n"));
+}
+
+function renderHeader(meta) {
+ const domains = (meta.domains || []).join(", ");
+ return `<header>
+ <h1>PR #${esc(String(meta.pr))} — ${esc(meta.title)}</h1>
+ <div class="meta">
+ <span class="badge badge-domain">${esc(domains)}</span>
+ <span>${meta.changedFileCount} files changed</span>
+ </div>
+</header>`;
+}
+
+function renderNav() {
+ return `<nav>
+ <h2>Contents</h2>
+ <ul>
+ <li><a href="#summary">Summary</a></li>
+ <li><a href="#context">Context</a></li>
+ <li><a href="#clusters">Clusters</a></li>
+ <li><a href="#communities">Communities</a></li>
+ <li><a href="#guided-walk">Guided Walk</a></li>
+ <li><a href="#functional-test">Functional Test</a></li>
+ <li><a href="#findings">Findings</a></li>
+ <li><a href="#open-questions">Open Questions</a></li>
+ <li><a href="#appendix-structural">Appendix: Structural</a></li>
+ <li><a href="#appendix-functional">Appendix: Functional Test</a></li>
+ </ul>
+</nav>`;
+}
+
+function renderSummary(summary) {
+ return `<section id="summary">\n <h2>Summary</h2>\n ${summary}\n</section>`;
+}
+
+function renderContext(disc) {
+ const cards = [];
+
+ for (const jira of (disc.jiras || [])) {
+ let commentsHtml = "";
+ if (jira.comments && jira.comments.length > 0) {
+ const items = jira.comments.map(c =>
+ `<li><em>${esc(c.author)}:</em> "${esc((c.body || "").slice(0, 150))}"</li>`
+ ).join("\n ");
+ commentsHtml = `\n <p style="margin-top: 0.5rem;"><strong>JIRA comments:</strong></p>\n <ul style="margin: 0.25rem 0 0 1.5rem; font-size: 0.875rem;">\n ${items}\n </ul>`;
+ }
+ cards.push(`<div class="card card-context">
+ <h3><span class="badge badge-context">JIRA</span> <a href="${esc(jira.url)}">${esc(jira.id)}</a>: ${esc(jira.title)}</h3>
+ <p>Found in: ${esc(jira.found_in || "pr")}. Status: <strong>${esc(jira.status)}</strong>.</p>${commentsHtml}
+ </div>`);
+ }
+
+ for (const sec of (disc.secondary || [])) {
+ cards.push(`<div class="card card-context">
+ <h3><span class="badge badge-context">JIRA</span> <a href="${esc(sec.url)}">${esc(sec.id || "")}</a>: ${esc(sec.title)}</h3>
+ <p>Found via: ${esc(sec.found_via)} (${esc(sec.found_in)}).</p>
+ </div>`);
+ }
+
+ if (disc.devList && disc.devList.length > 0) {
+ for (const d of disc.devList) {
+ cards.push(`<div class="card card-context">\n <h3>Dev List: ${esc(d.title)}</h3>\n <p><a href="${esc(d.url)}">${esc(d.url)}</a></p>\n </div>`);
+ }
+ } else {
+ const kw = (disc.devListSearchKeywords || []).join(", ");
+ const meta = kw ? `\n <p class="discovery-meta">Searched dev@tinkerpop.apache.org (last 1 year) for: ${esc(kw)}</p>` : "";
+ cards.push(`<div class="card">\n <h3>Dev List</h3>\n <p>No discussion found.</p>${meta}\n </div>`);
+ }
+
+ if (disc.proposalMissing !== false) {
+ cards.push(`<div class="card">\n <h3>Proposals</h3>\n <p>No matching proposal in <code>docs/src/dev/future/</code>.</p>\n </div>`);
+ }
+
+ return `<section id="context">\n <h2>Discovered Context</h2>\n ${cards.join("\n ")}\n</section>`;
+}
+
+function generateClusterSvg(clusterData, architecture) {
+ if (!clusterData || !clusterData.clusters || clusterData.clusters.length === 0) return "";
+
+ const clusters = clusterData.clusters;
+ const primary = clusters[0];
+ const satellites = clusters.slice(1);
+ const hasSatellites = satellites.length > 0;
+
+ const svgWidth = hasSatellites ? 900 : 700;
+ const primaryWidth = hasSatellites ? 650 : 680;
+
+ // Group primary cluster files by directory
+ const groups = new Map();
+ for (const filePath of primary.files) {
+ const parts = filePath.split("/");
+ const filename = parts.pop();
+ const dir = parts.slice(-2).join("/") || "root";
+ if (!groups.has(dir)) groups.set(dir, []);
+ groups.get(dir).push(filename);
+ }
+
+ let svgContent = "";
+ const groupEntries = [...groups.entries()].slice(0, 6);
+
+ // Primary cluster background
+ const primaryHeight = Math.max(200, groupEntries.length * 70 + 60);
+ svgContent += `<rect x="10" y="10" width="${primaryWidth}" height="${primaryHeight}" rx="8" fill="#e8f5e9" stroke="#4caf50" stroke-width="1.5" stroke-dasharray="4"/>`;
+ svgContent += `<text x="25" y="32" font-size="11" font-weight="600" fill="#2e7d32">Cluster 1 — Primary (${primary.size} files)</text>`;
+
+ // Render groups inside primary
+ const colors = ["#1976d2", "#f57c00", "#7b1fa2", "#388e3c", "#455a64", "#546e7a"];
+ let y = 50;
+ for (let i = 0; i < groupEntries.length; i++) {
+ const [dir, files] = groupEntries[i];
+ const color = colors[i % colors.length];
+ const boxHeight = Math.min(files.length * 12 + 30, 90);
+ svgContent += `<rect x="30" y="${y}" width="280" height="${boxHeight}" rx="5" fill="#fff" stroke="${color}" stroke-width="1.5"/>`;
+ svgContent += `<text x="170" y="${y + 18}" font-size="9" font-weight="600" fill="${color}" text-anchor="middle">${esc(dir)}</text>`;
+ const shown = files.slice(0, 4);
+ for (let j = 0; j < shown.length; j++) {
+ svgContent += `<text x="170" y="${y + 33 + j * 12}" font-size="8" fill="#333" text-anchor="middle">${esc(shown[j])}</text>`;
+ }
+ if (files.length > 4) {
+ svgContent += `<text x="170" y="${y + 33 + 4 * 12}" font-size="8" fill="#666" text-anchor="middle">+${files.length - 4} more</text>`;
+ }
+ y += boxHeight + 10;
+ }
+
+ // Satellite clusters
+ if (hasSatellites) {
+ let satY = 10;
+ for (const sat of satellites.slice(0, 3)) {
+ const satHeight = Math.min(sat.files.length * 12 + 50, 100);
+ svgContent += `<rect x="680" y="${satY}" width="210" height="${satHeight}" rx="8" fill="#fff3e0" stroke="#ff9800" stroke-width="1.5" stroke-dasharray="4"/>`;
+ svgContent += `<text x="695" y="${satY + 20}" font-size="10" font-weight="600" fill="#e65100">Satellite (${sat.size} files)</text>`;
+ const shown = sat.files.slice(0, 4);
+ for (let j = 0; j < shown.length; j++) {
+ const fname = shown[j].split("/").pop();
+ svgContent += `<text x="785" y="${satY + 38 + j * 13}" font-size="8" fill="#333" text-anchor="middle">${esc(fname)}</text>`;
+ }
+ satY += satHeight + 15;
+ }
+ }
+
+ // Draw edges between directory groups based on cross-file function calls
+ const archEdges = (architecture && architecture.edges) || [];
+ if (archEdges.length > 0 && groupEntries.length > 1) {
+ const fileToGroup = new Map();
+ for (let i = 0; i < groupEntries.length; i++) {
+ const [dir, files] = groupEntries[i];
+ for (const f of files) {
+ fileToGroup.set(f, i);
+ }
+ }
+
+ // Also map full paths to group index
+ for (const filePath of primary.files) {
+ const fname = filePath.split("/").pop();
+ const parts = filePath.split("/");
+ const dir = parts.slice(-3, -1).join("/") || "root";
+ for (let i = 0; i < groupEntries.length; i++) {
+ if (groupEntries[i][0] === dir || groupEntries[i][1].includes(fname)) {
+ fileToGroup.set(filePath, i);
+ break;
+ }
+ }
+ }
+
+ const groupCenters = groupEntries.map((_, i) => ({ x: 170, y: 50 + i * 80 + 35 }));
+ const drawnEdges = new Set();
+
+ for (const edge of archEdges) {
+ const fromGroup = fileToGroup.get(edge.from) ?? fileToGroup.get(edge.from.split("/").pop());
+ const toGroup = fileToGroup.get(edge.to) ?? fileToGroup.get(edge.to.split("/").pop());
+ if (fromGroup != null && toGroup != null && fromGroup !== toGroup) {
+ const key = `${Math.min(fromGroup, toGroup)}-${Math.max(fromGroup, toGroup)}`;
+ if (!drawnEdges.has(key) && groupCenters[fromGroup] && groupCenters[toGroup]) {
+ drawnEdges.add(key);
+ const from = groupCenters[fromGroup];
+ const to = groupCenters[toGroup];
+ svgContent += `<line x1="${from.x + 140}" y1="${from.y}" x2="${to.x + 140}" y2="${to.y}" stroke="#999" stroke-width="1.5" stroke-dasharray="3" marker-end="url(#arrow)"/>`;
+ }
+ }
+ }
+
+ if (drawnEdges.size > 0) {
+ svgContent = `<defs><marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M 0 0 L 10 5 L 0 10 z" fill="#999"/></marker></defs>` + svgContent;
+ }
+ }
+
+ const svgHeight = Math.max(primaryHeight + 20, 200);
+ return `<svg class="cluster-svg" viewBox="0 0 ${svgWidth} ${svgHeight}" xmlns="http://www.w3.org/2000/svg">
+ ${svgContent}
+</svg>`;
+}
+
+function renderClusters(clusters, clusterData, architecture) {
+ const svg = generateClusterSvg(clusterData, architecture);
+ const assessment = (clusters && clusters.assessment) || "<p>No assessment provided.</p>";
+
+ return `<section id="clusters">
+ <h2>Change Coherence</h2>
+ <p class="section-intro"><strong>Connected components</strong> — the coarse guard: it asks whether any changed file is wholly unreachable from the rest. A strong signal when it fires, but usually one cluster in a well-connected codebase. The finer, density-based view is <a href="#communities">Thematic Communities</a> below.</p>
+ ${svg}
+ <div class="card card-safe">
+ <h3>Assessment</h3>
+ ${assessment}
+ </div>
+</section>`;
+}
+
+function renderCommunitySection(communityData, assessment) {
+ if (!communityData || !communityData.interpretation) return notProvided("communities", "Thematic Communities");
+
+ const interp = communityData.interpretation;
+ const svg = generateCommunitySvg(communityData);
+
+ // The main section is the analyst's meaning-making (enrichment). Until that runs,
+ // fall back to the deterministic reading so the section is never empty.
+ const body = assessment
+ ? assessment
+ : `<p>${esc(interp.headline)}</p>${interp.reading.length
+ ? `<ul style="margin: 0.5rem 0 0 1.25rem;">${interp.reading.map((r) => `<li>${esc(r)}</li>`).join("")}</ul>`
+ : ""}
+ <p style="font-size: 0.82rem; color: var(--muted, #666); margin: 0.5rem 0 0;">Automated reading — run enrichment for an analyst's assessment of what these communities mean for this PR.</p>`;
+
+ return `<section id="communities">
+ <h2>Thematic Communities <span class="badge">Louvain</span></h2>
+ <p class="section-intro">Louvain modularity over the code subgraph (Discussion/Step hubs excluded) groups the change into densely-tied themes even when everything is technically reachable. Box colour encodes change mode — <span style="color:#c62828">red reduced</span>, <span style="color:#2e7d32">green expanded</span>, <span style="color:#e65100">orange reworked</span>, <span style="color:#3949ab">indigo unchanged context</span>. Per-community membership is in the <a href="#appendix-st [...]
+ ${svg}
+ <div class="card ${assessment ? "card-safe" : ""}">
+ <h3>Assessment</h3>
+ ${body}
+ </div>
+</section>`;
+}
+
+function generateCommunitySvg(communityData) {
+ const communities = (communityData && communityData.communities) || [];
+ if (communities.length === 0) return "";
+
+ const modeColor = (c) => {
+ const m = c.churn && c.churn.mode;
+ if (m === "reduced" || m === "purely reduced") return { stroke: "#e53935", fill: "#ffebee", label: "#c62828" };
+ if (m === "expanded") return { stroke: "#43a047", fill: "#e8f5e9", label: "#2e7d32" };
+ if (m === "reworked") return { stroke: "#fb8c00", fill: "#fff3e0", label: "#e65100" };
+ return { stroke: "#5c6bc0", fill: "#e8eaf6", label: "#3949ab" }; // unchanged context / unknown
+ };
+
+ const shown = communities.slice(0, 9);
+ const cols = Math.min(shown.length, 3);
+ const boxW = 270, gapX = 20, gapY = 18;
+ const svgWidth = cols * boxW + (cols + 1) * gapX;
+
+ const heightOf = (c) => 44 + Math.min(c.files.length, 4) * 13 + (c.files.length > 4 ? 13 : 0);
+ const positions = shown.map((c, i) => ({ c, col: i % cols, row: Math.floor(i / cols) }));
+ const numRows = Math.max(...positions.map((p) => p.row)) + 1;
+ const rowH = [];
+ for (let r = 0; r < numRows; r++) rowH[r] = Math.max(...positions.filter((p) => p.row === r).map((p) => heightOf(p.c)));
+ const rowY = [];
+ let acc = gapY;
+ for (let r = 0; r < numRows; r++) { rowY[r] = acc; acc += rowH[r] + gapY; }
+
+ let content = "";
+ for (const { c, col, row } of positions) {
+ const x = gapX + col * (boxW + gapX);
+ const y = rowY[row];
+ const h = rowH[row];
+ const cc = modeColor(c);
+ const kind = c.role.split(",")[0];
+ const churnBadge = c.churn ? `−${c.churn.removed}/+${c.churn.added}` : "unchanged context";
+ content += `<rect x="${x}" y="${y}" width="${boxW}" height="${h}" rx="8" fill="${cc.fill}" stroke="${cc.stroke}" stroke-width="1.5"/>`;
+ content += `<text x="${x + 12}" y="${y + 19}" font-size="11" font-weight="600" fill="${cc.label}">Community ${c.id + 1} — ${esc(kind)}</text>`;
+ content += `<text x="${x + 12}" y="${y + 33}" font-size="9" fill="#555">${c.size} vertices · ${esc(churnBadge)}</text>`;
+ const files = c.files.slice(0, 4).map((f) => f.split("/").pop());
+ for (let j = 0; j < files.length; j++) {
+ content += `<text x="${x + 12}" y="${y + 48 + j * 13}" font-size="8" fill="#333">${esc(files[j])}</text>`;
+ }
+ if (c.files.length > 4) content += `<text x="${x + 12}" y="${y + 48 + 4 * 13}" font-size="8" fill="#666">+${c.files.length - 4} more files</text>`;
+ }
+
+ return `<svg class="cluster-svg" viewBox="0 0 ${svgWidth} ${acc}" xmlns="http://www.w3.org/2000/svg">
+ ${content}
+</svg>`;
+}
+
+function renderGuidedWalk(walk) {
+ const steps = walk.map((step, i) => {
+ const cls = step.badge === "attention" ? "card-attention" : step.badge === "safe" ? "card-safe" : "card-info";
+ const badgeCls = step.badge === "attention" ? "badge-attention" : step.badge === "safe" ? "badge-safe" : "";
+ const badge = step.badgeText ? ` <span class="badge ${badgeCls}">${esc(step.badgeText)}</span>` : "";
+ return `<div class="card ${cls}">
+ <h3><span class="walk-number">${i + 1}</span> ${step.title}${badge}</h3>
+ ${step.body}
+ </div>`;
+ }).join("\n ");
+ return `<section id="guided-walk">\n <h2>Guided Walk</h2>\n ${steps}\n</section>`;
+}
+
+function renderFunctionalTest(ft) {
+ const plan = ft.plan ? `<div class="card card-test">\n <h3>Test Plan</h3>\n ${ft.plan}\n </div>` : "";
+
+ let results = "";
+ if (ft.results && ft.results.length > 0) {
+ const passed = ft.results.filter(r => r.pass).length;
+ const total = ft.results.length;
+ const badgeText = passed === total ? "All Pass" : `${passed}/${total}`;
+ const grid = ft.results.map(r =>
+ `<span class="${r.pass ? "test-pass" : "test-fail"}">${r.pass ? "PASS" : "FAIL"}</span><span>${esc(r.name)}</span><span><code>${esc(r.output || "")}</code></span>`
+ ).join("\n ");
+ results = `<div class="card card-safe">
+ <h3>Results: ${passed}/${total} passed <span class="badge badge-safe">${badgeText}</span></h3>
+ <div class="test-grid">\n ${grid}\n </div>
+ </div>`;
+ }
+
+ let obs = "";
+ if (ft.observations && ft.observations.length > 0) {
+ const items = ft.observations.map(o => `<li>${o}</li>`).join("\n ");
+ obs = `<div class="card">\n <h3>Observations</h3>\n <ul style="margin: 0.5rem 0 0 1.5rem; font-size: 0.9rem;">\n ${items}\n </ul>\n </div>`;
+ }
+
+ return `<section id="functional-test">
+ <h2>Functional Test</h2>
+ <p class="section-intro">Built from PR source and tested against a live Gremlin Server. Tests derived from documentation and Gherkin features only. <a href="#appendix-functional">Full execution details in appendix.</a></p>
+ ${plan}
+ ${results}
+ ${obs}
+</section>`;
+}
+
+function renderFindings(findings) {
+ const cards = findings.map((f, i) => {
+ const snippet = f.snippet ? `\n <pre><code>${esc(f.snippet)}</code></pre>` : "";
+ return `<div class="card finding">
+ <p class="finding-title">${i + 1}. ${esc(f.title)}</p>${snippet}
+ ${f.body}
+ </div>`;
+ }).join("\n ");
+ return `<section id="findings">\n <h2>Findings</h2>\n ${cards}\n</section>`;
+}
+
+function renderOpenQuestions(questions) {
+ const cards = questions.map(q => {
+ const meta = q.meta ? `\n <p class="discovery-meta">${esc(q.meta)}</p>` : "";
+ return `<div class="card">\n <h3>${esc(q.title)}</h3>\n ${q.body}${meta}\n </div>`;
+ }).join("\n ");
+ return `<section id="open-questions">\n <h2>Open Questions</h2>\n ${cards}\n</section>`;
+}
+
+function renderConfidence(confidence) {
+ if (!confidence || !confidence.distribution) return "";
+ const d = confidence.distribution;
+ const ambiguous = confidence.ambiguous || [];
+
+ const chip = (label, value, cls) =>
+ `<div class="stat-box"><div class="value">${value || 0}</div><div class="label">${label}</div></div>`;
+
+ let ambiguousHtml;
+ if (ambiguous.length === 0) {
+ ambiguousHtml = `<p class="section-intro">No AMBIGUOUS edges — nothing was linked purely by keyword search or low-confidence guess.</p>`;
+ } else {
+ const rows = ambiguous.map(a => {
+ const via = a.foundVia ? ` <span class="discovery-meta">via ${esc(a.foundVia)}</span>` : "";
+ const found = a.foundIn ? esc(a.foundIn) : "—";
+ return `<tr><td><code>${esc(a.relation)}</code></td><td class="fn-name">${esc(a.from)}</td><td class="fn-name">${esc(a.to)}${via}</td><td>${found}</td></tr>`;
+ }).join("\n ");
+ ambiguousHtml = `<table class="gap-table">
+ <thead><tr><th>Relation</th><th>From</th><th>To</th><th>Found in</th></tr></thead>
+ <tbody>\n ${rows}\n </tbody>
+ </table>`;
+ }
+
+ const untagged = d.UNTAGGED
+ ? `<div class="stat-box"><div class="value">${d.UNTAGGED}</div><div class="label">Untagged</div></div>`
+ : "";
+
+ return `
+ <h3>Signal Confidence</h3>
+ <p class="section-intro">Every graph edge is tagged by how it was established. <strong>EXTRACTED</strong> edges are observed directly in source or the git diff; <strong>INFERRED</strong> edges are name-resolved or evidence-backed deductions; <strong>AMBIGUOUS</strong> edges are keyword-search or low-confidence guesses and are listed below for human review.</p>
+ <div class="stats-grid">
+ ${chip("Extracted", d.EXTRACTED)}
+ ${chip("Inferred", d.INFERRED)}
+ ${chip("Ambiguous", d.AMBIGUOUS)}
+ ${untagged}
+ </div>
+ <h4 style="margin-top: 1rem;">Ambiguous edges (${ambiguous.length}) — verify before relying on</h4>
+ ${ambiguousHtml}
+`;
+}
+
+function renderAppendixStructural(checks, graphStats) {
+ const hotspots = checks?.centrality?.hotspots || [];
+ const blast = checks?.blastRadius?.functions || [];
+ const stats = graphStats || {};
+ const bd = stats.breakdown || {};
+ const confidenceHtml = renderConfidence(checks?.confidence);
+
+ const hotspotRows = hotspots.slice(0, 10).map(h => {
+ const badge = changeLevelBadge(h.changeLevel);
+ return `<tr><td class="fn-name">${esc(h.name)}</td><td>${esc((h.filePath || "").split("/").pop())}</td><td class="num">${h.inDegree}</td><td class="num">${h.outDegree}</td><td class="num"><strong>${h.totalDegree}</strong></td><td>${badge}</td></tr>`;
+ }).join("\n ");
+
+ const blastRows = blast.slice(0, 10).map(b => {
+ const badge = changeLevelBadge(b.changeLevel);
+ return `<tr><td class="fn-name">${esc(b.name)}</td><td>${esc((b.filePath || "").split("/").pop())}</td><td class="num">${b.reachableCount}</td><td>${badge}</td></tr>`;
+ }).join("\n ");
+
+ const hierarchy = checks?.blastRadius?.types || [];
+ const truncated = checks?.blastRadius?.neighborhood?.truncated;
+ const hierarchyRows = hierarchy.slice(0, 10).map(t => {
+ return `<tr><td class="fn-name">${esc(t.name)}</td><td>${esc(t.kind || "")}</td><td>${esc((t.filePath || "").split("/").pop())}</td><td class="num">${t.implementerCount}</td></tr>`;
+ }).join("\n ");
+ const communities = checks?.communities?.communities || [];
+ const communityRows = communities.map(c => {
+ const labels = Object.entries(c.labelCounts || {}).sort((a, b) => b[1] - a[1]).map(([l, n]) => `${l}:${n}`).join(", ");
+ const files = c.files.map(f => `<code>${esc(f)}</code>`).join("<br>");
+ return `<tr><td>${c.id + 1}</td><td>${esc(c.role)}</td><td class="num">${c.size}</td><td>${esc(labels)}</td><td>${files}</td></tr>`;
+ }).join("\n ");
+ const isolated = checks?.communities?.isolatedCount ?? 0;
+ const communitiesHtml = communities.length === 0 ? "" : `
+ <h3>Community Membership</h3>
+ <p class="section-intro">Louvain communities over the code subgraph, largest first (modularity ${checks?.communities?.modularity}). The reading is in <a href="#communities">Thematic Communities</a>; this is the raw membership. Role carries the change mode and line churn (−removed/+added). ${isolated} vertices have no in-subgraph edge and are omitted; every clustered vertex carries a <code>community</code> property for direct querying.</p>
+ <table class="gap-table">
+ <thead><tr><th>#</th><th>Role</th><th>Vertices</th><th>Label mix</th><th>Files</th></tr></thead>
+ <tbody>\n ${communityRows}\n </tbody>
+ </table>`;
+
+ const truncNote = truncated ? ` <strong>Neighborhood truncated — these counts are a lower bound.</strong>` : "";
+ const hierarchyHtml = hierarchy.length === 0 ? "" : `
+ <h3>Type Hierarchy Impact</h3>
+ <p class="section-intro">For each changed type (typically an interface), the number of functions declared by everything that implements or extends it within 3 levels — impact that flows through the type hierarchy rather than direct calls.${truncNote}</p>
+ <table class="gap-table">
+ <thead><tr><th>Type</th><th>Kind</th><th>File</th><th>Implementer fns</th></tr></thead>
+ <tbody>\n ${hierarchyRows}\n </tbody>
+ </table>`;
+
+ return `<section id="appendix-structural">
+ <h2>Appendix: Structural Data</h2>
+
+ <h3>Structural Hotspots</h3>
+ <p class="section-intro">Functions with the most incoming/outgoing call edges among changed code. Inherently-central methods (equals, toString) included only when modified by this PR.</p>
+ <table class="gap-table">
+ <thead><tr><th>Function</th><th>File</th><th>In</th><th>Out</th><th>Total</th><th></th></tr></thead>
+ <tbody>\n ${hotspotRows}\n </tbody>
+ </table>
+
+ <h3>Blast Radius</h3>
+ <p class="section-intro">Reachable callers and overriders within 3 hops upstream — higher means more code affected by behavioral changes. Includes impact flowing through interface/abstract overrides, not just direct calls.</p>
+ <table class="gap-table">
+ <thead><tr><th>Function</th><th>File</th><th>Reachable</th><th></th></tr></thead>
+ <tbody>\n ${blastRows}\n </tbody>
+ </table>
+${hierarchyHtml}
+${communitiesHtml}
+${confidenceHtml}
+ <h3>Graph Statistics</h3>
+ <div class="stats-grid">
+ <div class="stat-box"><div class="value">${stats.vertices || 0}</div><div class="label">Vertices</div></div>
+ <div class="stat-box"><div class="value">${stats.edges || 0}</div><div class="label">Edges</div></div>
+ <div class="stat-box"><div class="value">${bd.files || 0}</div><div class="label">Files</div></div>
+ <div class="stat-box"><div class="value">${bd.functions || 0}</div><div class="label">Functions</div></div>
+ <div class="stat-box"><div class="value">${bd.types || 0}</div><div class="label">Types</div></div>
+ <div class="stat-box"><div class="value">${bd.tests || 0}</div><div class="label">Tests</div></div>
+ </div>
+</section>`;
+}
+
+function renderAppendixFunctional(af) {
+ return `<section id="appendix-functional">
+ <h2>Appendix: Functional Test Details</h2>
+
+ <h3>Execution Environment</h3>
+ <div class="card">\n ${af.environment}\n </div>
+
+ <h3>Test Code</h3>
+ <p class="section-intro">Complete, unabbreviated test battery. Each scenario is labeled in a comment; the Functional Test section refers to these labels.</p>
+ <pre><code>${esc(stripCodeWrapper(af.testCode))}</code></pre>
+
+ <h3>Full Output</h3>
+ <pre><code>${esc(stripCodeWrapper(af.fullOutput))}</code></pre>
+</section>`;
+}
+
+// CLI: node render.js <input.json> [output.html]
+import { basename } from "node:path";
+if (process.argv[1] && basename(process.argv[1]) === "render.js") {
+ const inputPath = process.argv[2];
+ if (!inputPath) {
+ console.error("Usage: node render.js <evidence.json> [output.html]");
+ process.exit(1);
+ }
+ const outputPath = process.argv[3] || inputPath.replace(/\.json$/, ".html");
+ const { readFileSync, writeFileSync } = await import("node:fs");
+ const evidence = JSON.parse(readFileSync(inputPath, "utf-8"));
+ const html = render(evidence);
+ writeFileSync(outputPath, html, "utf-8");
+ console.log(`Report written: ${outputPath}`);
+}
diff --git a/.skills/tinker-review/scripts/renderer/template.html b/.skills/tinker-review/scripts/renderer/template.html
new file mode 100644
index 0000000000..53901292c2
--- /dev/null
+++ b/.skills/tinker-review/scripts/renderer/template.html
@@ -0,0 +1,74 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Graph Review</title>
+<style>
+:root { --bg: #ffffff; --bg-alt: #f8f9fa; --bg-card: #ffffff; --border: #dee2e6; --text: #212529; --text-muted: #6c757d; --primary: #0d6efd; --success: #198754; --warning: #ffc107; --danger: #dc3545; --radius: 6px; --shadow: 0 1px 3px rgba(0,0,0,0.08); }
+@media (prefers-color-scheme: dark) { :root { --bg: #1a1a2e; --bg-alt: #16213e; --bg-card: #0f3460; --border: #2a4a7f; --text: #e4e4e4; --text-muted: #a0a0a0; --primary: #4dabf7; --success: #51cf66; --warning: #fcc419; --danger: #ff6b6b; } }
+* { margin: 0; padding: 0; box-sizing: border-box; }
+body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif; background: var(--bg); color: var(--text); line-height: 1.6; padding: 2rem; max-width: 960px; margin: 0 auto; }
+a { color: var(--primary); text-decoration: none; } a:hover { text-decoration: underline; }
+header { border-bottom: 2px solid var(--border); padding-bottom: 1.5rem; margin-bottom: 2rem; }
+header h1 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.25rem; }
+header .meta { display: flex; gap: 1rem; flex-wrap: wrap; font-size: 0.875rem; color: var(--text-muted); }
+.badge { display: inline-block; padding: 0.15rem 0.5rem; border-radius: 3px; font-weight: 500; font-size: 0.75rem; text-transform: uppercase; }
+.badge-domain { background: var(--primary); color: #fff; } .badge-attention { background: var(--danger); color: #fff; }
+.badge-safe { background: var(--success); color: #fff; } .badge-context { background: #6f42c1; color: #fff; }
+.badge-test { background: #20c997; color: #fff; } .badge-modified { background: var(--warning); color: #000; }
+.badge-structural { background: var(--danger); color: #fff; } .badge-formatting { background: #adb5bd; color: #000; }
+nav { background: var(--bg-alt); border: 1px solid var(--border); border-radius: var(--radius); padding: 1rem; margin-bottom: 2rem; }
+nav h2 { font-size: 0.875rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); margin-bottom: 0.5rem; }
+nav ul { list-style: none; display: flex; flex-wrap: wrap; gap: 0.5rem 1.5rem; } nav ul li a { font-size: 0.875rem; }
+section { margin-bottom: 2.5rem; }
+section h2 { font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--border); }
+section h3 { font-size: 1.05rem; font-weight: 600; margin: 1.25rem 0 0.5rem; }
+.card { background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius); padding: 1.25rem; margin-bottom: 1rem; box-shadow: var(--shadow); }
+.card h3 { font-size: 1rem; font-weight: 600; margin-bottom: 0.5rem; margin-top: 0; } .card p { margin-bottom: 0.5rem; }
+.card-attention { border-left: 4px solid var(--danger); } .card-safe { border-left: 4px solid var(--success); }
+.card-info { border-left: 4px solid var(--primary); } .card-context { border-left: 4px solid #6f42c1; }
+.card-test { border-left: 4px solid #20c997; }
+code { background: var(--bg-alt); padding: 0.1rem 0.4rem; border-radius: 3px; font-size: 0.85rem; font-family: "SF Mono", Consolas, monospace; }
+pre { background: var(--bg-alt); border: 1px solid var(--border); border-radius: var(--radius); padding: 0.75rem; overflow-x: auto; font-size: 0.8rem; line-height: 1.5; margin: 0.75rem 0; }
+pre code { background: none; padding: 0; }
+.walk-number { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; border-radius: 50%; background: var(--primary); color: #fff; font-size: 0.8rem; font-weight: 700; margin-right: 0.5rem; }
+.finding { border-left: 3px solid var(--warning); } .finding-title { font-weight: 600; margin-bottom: 0.25rem; }
+.test-pass { color: var(--success); font-weight: 600; } .test-fail { color: var(--danger); font-weight: 600; }
+.test-grid { display: grid; grid-template-columns: auto 1fr auto; gap: 0.25rem 0.75rem; font-size: 0.875rem; align-items: baseline; }
+.section-intro { font-size: 0.9rem; color: var(--text-muted); margin-bottom: 1rem; line-height: 1.5; }
+.cluster-svg { width: 100%; border: 1px solid var(--border); border-radius: var(--radius); background: var(--bg-alt); margin: 1rem 0; }
+.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 0.75rem; }
+.stat-box { background: var(--bg-alt); border: 1px solid var(--border); border-radius: var(--radius); padding: 0.75rem; text-align: center; }
+.stat-box .value { font-size: 1.25rem; font-weight: 700; color: var(--primary); } .stat-box .label { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); }
+.gap-table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
+.gap-table th { text-align: left; padding: 0.4rem 0.6rem; background: var(--bg-alt); border-bottom: 2px solid var(--border); font-weight: 600; font-size: 0.75rem; text-transform: uppercase; color: var(--text-muted); }
+.gap-table td { padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--border); } .gap-table .fn-name { font-family: monospace; font-weight: 500; } .gap-table .num { text-align: right; font-family: monospace; }
+.discovery-meta { font-size: 0.8rem; color: var(--text-muted); font-style: italic; margin-top: 0.5rem; }
+footer { margin-top: 3rem; padding-top: 1rem; border-top: 1px solid var(--border); font-size: 0.75rem; color: var(--text-muted); text-align: center; }
+</style>
+</head>
+<body>
+
+{{content}}
+
+</body>
+</html>
diff --git a/.skills/tinker-review/scripts/review.js b/.skills/tinker-review/scripts/review.js
new file mode 100644
index 0000000000..3aa600785a
--- /dev/null
+++ b/.skills/tinker-review/scripts/review.js
@@ -0,0 +1,565 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { writeFile, mkdir, rm } from "node:fs/promises";
+import { join, basename, extname } from "node:path";
+import { existsSync } from "node:fs";
+import gremlin from "gremlin";
+
+import { startServer, stopServer } from "./infrastructure/docker.js";
+import { extractMulti } from "./extraction/tree-sitter.js";
+import { populate } from "./graph/populate.js";
+import { populateDiscussions } from "./graph/populate-discussions.js";
+import { completeness } from "./patterns/completeness.js";
+import { coverageGaps } from "./patterns/coverage-gaps.js";
+import { highCentrality } from "./patterns/centrality.js";
+import { blastRadius } from "./patterns/blast-radius.js";
+import { clusterAnalysis } from "./patterns/cluster-analysis.js";
+import { communityDetection } from "./patterns/community-detection.js";
+import { architecture } from "./patterns/architecture.js";
+import { confidenceAudit } from "./patterns/confidence-audit.js";
+import { classifyExternals } from "./patterns/classify-externals.js";
+import { findRemovalRefs } from "./patterns/removal-refs.js";
+import { orphans } from "./patterns/orphans.js";
+import { createPrDiscussion } from "./enrichment/api.js";
+import { discoverDiscussions } from "./discovery/discussions.js";
+
+const exec = promisify(execFile);
+
+const LANGUAGE_HINTS = {
+ dart: "dart",
+ java: "java",
+ go: "go",
+ py: "python",
+ js: "javascript",
+ mjs: "javascript",
+ cs: "csharp",
+};
+
+function log(msg) {
+ process.stdout.write(`[review] ${msg}\n`);
+}
+
+// Every language present among the changed files, most-changed first. The graph
+// is built from all of them (extractMulti); by-name edges stay language-scoped so
+// mixing languages doesn't invent cross-language edges. Falls back to ["java"].
+function detectLanguages(changedFiles) {
+ const extCounts = new Map();
+ for (const file of changedFiles) {
+ const ext = extname(file).slice(1);
+ if (LANGUAGE_HINTS[ext]) {
+ extCounts.set(LANGUAGE_HINTS[ext], (extCounts.get(LANGUAGE_HINTS[ext]) || 0) + 1);
+ }
+ }
+ const langs = [...extCounts.entries()].sort((a, b) => b[1] - a[1]).map(([lang]) => lang);
+ return langs.length > 0 ? langs : ["java"];
+}
+
+async function getChangedFiles(repoPath, prBranch, remote = "upstream", baseBranch = "master") {
+ const { stdout: baseCommit } = await exec(
+ "git", ["merge-base", prBranch, `${remote}/${baseBranch}`],
+ { cwd: repoPath }
+ );
+ const base = baseCommit.trim();
+
+ const { stdout: diffOutput } = await exec(
+ "git", ["diff", "--name-only", `${base}...${prBranch}`],
+ { cwd: repoPath }
+ );
+ return diffOutput.trim().split("\n").filter(Boolean);
+}
+
+/**
+ * The base-version source text of each changed file, keyed by path, so extraction
+ * can diff base against head and grade every member's `changeLevel`. Reads
+ * `git show <merge-base>:<path>`; a path git can't produce — added by the PR, or
+ * binary — is omitted, and extraction treats a missing entry as an added file
+ * (STRUCTURAL). Returns `{ [path]: content }`.
+ */
+export async function getBaseContents(repoPath, prBranch, changedFiles, remote = "upstream", baseBranch = "master") {
+ const { stdout: baseCommit } = await exec(
+ "git", ["merge-base", prBranch, `${remote}/${baseBranch}`], { cwd: repoPath }
+ );
+ const base = baseCommit.trim();
+ const contents = {};
+ await Promise.all(changedFiles.map(async (path) => {
+ try {
+ const { stdout } = await exec(
+ "git", ["show", `${base}:${path}`], { cwd: repoPath, maxBuffer: 32 * 1024 * 1024 }
+ );
+ contents[path] = stdout;
+ } catch {
+ // Absent at base (added by the PR) or unreadable (binary) — leave unset.
+ }
+ }));
+ return contents;
+}
+
+/**
+ * Per-file line churn and deletion status for the PR, so downstream analysis can
+ * describe *how* code changed (reduced vs. expanded), not just that it changed.
+ * Merges `--numstat` (line counts) with `--name-status` (A/M/D/R). Binary files
+ * report 0/0. Returns `{ [path]: { added, removed, deleted } }`.
+ */
+export async function computeChurn(repoPath, prBranch, remote = "upstream", baseBranch = "master") {
+ const { stdout: baseCommit } = await exec(
+ "git", ["merge-base", prBranch, `${remote}/${baseBranch}`], { cwd: repoPath }
+ );
+ const range = `${baseCommit.trim()}...${prBranch}`;
+
+ const [numstat, nameStatus] = await Promise.all([
+ exec("git", ["diff", "--numstat", range], { cwd: repoPath }).then((r) => r.stdout).catch(() => ""),
+ exec("git", ["diff", "--name-status", range], { cwd: repoPath }).then((r) => r.stdout).catch(() => ""),
+ ]);
+
+ const churn = {};
+ for (const line of numstat.trim().split("\n").filter(Boolean)) {
+ const [added, removed, ...pathParts] = line.split("\t");
+ const path = pathParts.join("\t");
+ if (!path) continue;
+ churn[path] = { added: added === "-" ? 0 : Number(added), removed: removed === "-" ? 0 : Number(removed), deleted: false };
+ }
+ for (const line of nameStatus.trim().split("\n").filter(Boolean)) {
+ const [status, ...pathParts] = line.split("\t");
+ const path = pathParts.join("\t");
+ if (status && status[0] === "D" && path) {
+ churn[path] = churn[path] || { added: 0, removed: 0 };
+ churn[path].deleted = true;
+ }
+ }
+ return churn;
+}
+
+function classifyDomains(changedFiles) {
+ const paths = changedFiles.join("\n").toLowerCase();
+ const domains = ["general"];
+
+ if (paths.includes("gremlin-dart") || paths.includes("gremlin-swift") || paths.includes("gremlin-rust") ||
+ paths.includes("gremlin-go/") || paths.includes("gremlin-python/") || paths.includes("gremlin-dotnet/") ||
+ paths.includes("gremlin-js/") || paths.includes("gremlin-javascript/")) {
+ domains.push("glv");
+ }
+ if (paths.includes("gremlin-driver/") || paths.includes("gremlin-server/") || paths.includes("gremlin-util/") ||
+ paths.includes("serializ") || paths.includes("graphson") || paths.includes("graphbinary") || paths.includes("gryo")) {
+ domains.push("driver-server");
+ }
+ if (paths.includes("gremlin-language/") || paths.includes(".g4")) {
+ domains.push("grammar");
+ }
+ if (paths.includes("gremlin-core/") && (paths.includes("step/map/") || paths.includes("step/filter/") ||
+ paths.includes("step/sideeffect/") || paths.includes("step/branch/"))) {
+ domains.push("new-step");
+ }
+
+ return domains;
+}
+
+// Structural/infra filenames that describe packaging, not a topic — they match
+// boilerplate (e.g. NOTICE lives in every ASF license header) and must never
+// become search keywords.
+const STRUCTURAL_NAMES = new Set([
+ "index", "package", "pom", "build", "notice", "license", "dockerfile",
+ "docker-compose", "readme", "changelog", "makefile", "setup", "config",
+]);
+// Generic verbs/nouns in PR titles that carry no topic signal.
+const GENERIC_WORDS = new Set([
+ "remove", "removes", "removed", "removal", "add", "adds", "added", "fix",
+ "fixes", "fixed", "update", "updates", "updated", "support", "refactor",
+ "improve", "improves", "cleanup", "bump", "upgrade", "migrate", "implement",
+ "introduce", "enable", "disable", "allow", "the", "and", "for", "with",
+]);
+// Tokens so common across the repo that matching on them finds everything.
+const UBIQUITOUS_TOKENS = new Set([
+ "gremlin", "server", "client", "test", "tests", "docker", "tinkerpop",
+ "apache", "core", "impl", "util", "utils", "common", "base", "default",
+ "abstract", "main", "java", "python",
+]);
+
+// Split an identifier/filename into lowercased word tokens (camelCase and
+// non-alphanumeric boundaries), e.g. "Krb5Authenticator" -> ["krb5","authenticator"].
+function tokenizeName(name) {
+ return name
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
+ .split(/[^A-Za-z0-9]+/)
+ .map((t) => t.toLowerCase())
+ .filter((t) => t.length >= 3);
+}
+
+// Keywords for discovery search (dev-list + proposals). Topic first: PR-title
+// words (the human statement of intent) lead so they can't be truncated by the
+// cap, then distinctive tokens from changed-file basenames. Structural names,
+// generic verbs, and repo-ubiquitous tokens are filtered out so we don't search
+// on noise like "NOTICE" or "gremlin-server". Exported for testing.
+export function extractKeywords(changedFiles, prTitle) {
+ const keywords = [];
+ const seen = new Set();
+ const push = (word) => {
+ const k = word.toLowerCase();
+ if (k.length < 3 || seen.has(k)) return;
+ if (GENERIC_WORDS.has(k) || UBIQUITOUS_TOKENS.has(k)) return;
+ seen.add(k);
+ keywords.push(k);
+ };
+
+ for (const w of prTitle.split(/[\s\-_:,.()]+/)) {
+ if (!/^\d+$/.test(w)) push(w);
+ }
+ for (const file of changedFiles) {
+ const base = file.split("/").pop().replace(/\.\w+$/, "");
+ if (STRUCTURAL_NAMES.has(base.toLowerCase())) continue;
+ for (const tok of tokenizeName(base)) push(tok);
+ }
+ return keywords.slice(0, 8);
+}
+
+async function cleanupWorktree(repoPath, worktreePath, prBranch) {
+ if (existsSync(worktreePath)) {
+ await exec("git", ["worktree", "remove", "--force", worktreePath], { cwd: repoPath }).catch(() => {});
+ }
+ await exec("git", ["worktree", "prune"], { cwd: repoPath }).catch(() => {});
+ await exec("git", ["branch", "-D", prBranch], { cwd: repoPath }).catch(() => {});
+}
+
+// ============================================================
+// SETUP — fetch PR, create worktree, start server
+// Returns a session object the agent uses for all subsequent phases.
+// ============================================================
+
+async function detectRemote(repoPath) {
+ const { stdout } = await exec("git", ["remote", "-v"], { cwd: repoPath });
+ const lines = stdout.split("\n");
+ for (const line of lines) {
+ if (line.includes("apache/tinkerpop") && line.includes("(fetch)")) {
+ return line.split(/\s+/)[0];
+ }
+ }
+ // Fall back to origin if no apache/tinkerpop remote found
+ return "origin";
+}
+
+// Detect the branch a PR targets (e.g. master, 3.8-dev, 3.7-dev) from the
+// GitHub API. Falls back to "master" if the API is unreachable.
+async function detectBaseBranch(pr) {
+ try {
+ const { get } = await import("node:https");
+ const prData = await new Promise((resolve, reject) => {
+ get(`https://api.github.com/repos/apache/tinkerpop/pulls/${pr}`, {
+ headers: { "User-Agent": "tinker-review", "Accept": "application/json" },
+ }, (res) => {
+ let data = "";
+ res.on("data", (chunk) => { data += chunk; });
+ res.on("end", () => resolve(JSON.parse(data)));
+ }).on("error", reject);
+ });
+ return prData.base?.ref || "master";
+ } catch {
+ return "master";
+ }
+}
+
+export async function setup(params) {
+ const { pr, repoPath, options = {} } = params;
+ const remote = options.remote || await detectRemote(repoPath);
+ const baseBranch = options.baseBranch || await detectBaseBranch(pr);
+ const prBranch = `pr-review/${pr}`;
+ const workDir = `/tmp/pr-review-${pr}`;
+ const worktreePath = `${workDir}/src`;
+
+ await mkdir(workDir, { recursive: true });
+ await cleanupWorktree(repoPath, worktreePath, prBranch);
+
+ log(`PR #${pr} — targets ${baseBranch}, fetching...`);
+ await exec("git", ["fetch", remote, baseBranch], { cwd: repoPath }).catch(() => {});
+ await exec("git", ["fetch", remote, `pull/${pr}/head:${prBranch}`], { cwd: repoPath });
+ await exec("git", ["worktree", "add", worktreePath, prBranch], { cwd: repoPath });
+
+ const changedFiles = await getChangedFiles(repoPath, prBranch, remote, baseBranch);
+ const languages = detectLanguages(changedFiles);
+ const language = languages[0];
+ const domains = classifyDomains(changedFiles);
+ log(`PR #${pr} — classified as: ${domains.join(", ")} (${languages.join("+")}, ${changedFiles.length} files changed)`);
+
+ log(`Starting Gremlin Server...`);
+ const handle = await startServer({ port: options.port });
+ log(`Gremlin Server ready on port ${handle.port}`);
+
+ const connection = new gremlin.driver.DriverRemoteConnection(handle.url);
+ const g = gremlin.process.traversal().withRemote(connection);
+ const aConnection = new gremlin.driver.DriverRemoteConnection(handle.url, { traversalSource: "a" });
+ const a = gremlin.process.traversal().withRemote(aConnection);
+
+ await writeFile(join(workDir, "session.json"), JSON.stringify({
+ url: handle.url,
+ port: handle.port,
+ containerId: handle.containerId,
+ worktreePath,
+ workDir,
+ repoPath,
+ pr,
+ baseBranch,
+ }, null, 2));
+
+ return {
+ pr,
+ repoPath,
+ remote,
+ baseBranch,
+ prBranch,
+ workDir,
+ worktreePath,
+ changedFiles,
+ language,
+ languages,
+ domains,
+ handle,
+ connection,
+ aConnection,
+ g,
+ a,
+ };
+}
+
+// ============================================================
+// PHASE 1 — extract, populate, discover, run checks
+// Writes evidence JSON to workDir. The Gremlin Server container stays alive for
+// enrichment; the CLI process itself exits once Phase 1 completes (see main()).
+// ============================================================
+
+export async function phase1(session) {
+ const { pr, repoPath, remote, baseBranch = "master", prBranch, workDir, worktreePath, changedFiles, language, domains, g, a } = session;
+ const languages = session.languages || [language];
+
+ log(`Phase 1: Extracting structure (${languages.join("+")})...`);
+ const baseContents = await getBaseContents(repoPath, prBranch, changedFiles, remote, baseBranch);
+ const extraction = await extractMulti(worktreePath, languages, { changedFiles, baseContents });
+ log(`Phase 1 complete: ${extraction.files.length} files, ${extraction.functions.length} functions, ${extraction.types.length} types`);
+ const neighborhood = extraction.hierarchyNeighborhood;
+ if (neighborhood && neighborhood.files > 0) {
+ log(` hierarchy neighborhood: +${neighborhood.files} context files parsed for override/hierarchy edges${neighborhood.truncated ? " (TRUNCATED — hierarchy blast radius is a lower bound)" : ""}`);
+ }
+
+ log(`Populating graph...`);
+ const graphStats = await populate(g, extraction, { changedFiles, worktreePath });
+ log(`Graph populated: ${graphStats.vertices} vertices, ${graphStats.edges} edges`);
+
+ let prTitle = `PR #${pr}`;
+ let prBody = "";
+ try {
+ const { get } = await import("node:https");
+ const prData = await new Promise((resolve, reject) => {
+ get(`https://api.github.com/repos/apache/tinkerpop/pulls/${pr}`, {
+ headers: { "User-Agent": "tinker-review", "Accept": "application/json" },
+ }, (res) => {
+ let data = "";
+ res.on("data", (chunk) => { data += chunk; });
+ res.on("end", () => resolve(JSON.parse(data)));
+ }).on("error", reject);
+ });
+ prTitle = prData.title || prTitle;
+ prBody = (prData.body || "").slice(0, 2000);
+ } catch {
+ const { stdout } = await exec("git", ["log", "-1", "--format=%s", prBranch], { cwd: repoPath }).catch(() => ({ stdout: prTitle }));
+ prTitle = stdout.trim() || prTitle;
+ }
+
+ await createPrDiscussion(g, pr, prTitle.trim(), "");
+
+ log(`Discovering discussions...`);
+ const { stdout: diffText } = await exec(
+ "git", ["diff", "--unified=0", `${(await exec("git", ["merge-base", prBranch, `${remote}/${baseBranch}`], { cwd: repoPath })).stdout.trim()}...${prBranch}`],
+ { cwd: repoPath }
+ ).catch(() => ({ stdout: "" }));
+
+ const prKeywords = extractKeywords(changedFiles, prTitle.trim());
+ const discussions = await discoverDiscussions({
+ pr,
+ prTitle: prTitle,
+ prBody,
+ diff: diffText,
+ keywords: prKeywords,
+ repoPath,
+ });
+ log(` jiras: ${discussions.jiras.length} found${discussions.jiraMissing ? " (none referenced)" : ""}`);
+ log(` pr comments: ${discussions.prComments.issue.length} issue + ${discussions.prComments.review.length} review`);
+ log(` dev list: ${discussions.devList.length} found${discussions.devListSearchPerformed ? ` (searched: ${prKeywords.join(", ")})` : ""}`);
+ log(` proposals: ${discussions.proposals.length} found`);
+
+ log(`Loading discussions into graph...`);
+ await populateDiscussions(g, discussions, { pr, prTitle: prTitle.trim(), changedFiles });
+
+ log(`Classifying external callees...`);
+ const externalsResult = await classifyExternals(g, worktreePath);
+ log(` externals: ${externalsResult.library.length} library / ${externalsResult.project.length} project / ${externalsResult.unresolved.length} unresolved`);
+
+ log(`Finding references to removed code...`);
+ const removalRefsResult = await findRemovalRefs(g, worktreePath);
+ log(` removal_refs: ${removalRefsResult.total} surviving references to ${removalRefsResult.deletedCodeSymbols.length} removed symbols`);
+
+ log(`Running checks...`);
+ const completenessResults = await completeness(g, {
+ vertexLabel: "File",
+ expectedEdges: ["out:defines"],
+ });
+
+ const coverageResult = await coverageGaps(g, { changedOnly: true });
+ const centralityResult = await highCentrality(g, { changedOnly: true, topN: 10, minDegree: 3 });
+ const blastResult = await blastRadius(g, { depth: 3, changedOnly: true });
+ blastResult.neighborhood = extraction.hierarchyNeighborhood || null;
+ const clusterResult = await clusterAnalysis(a, { changedOnly: true });
+ const churn = await computeChurn(repoPath, prBranch, remote, baseBranch).catch(() => null);
+ const communityResult = await communityDetection(g, { churn });
+ const confidenceResult = await confidenceAudit(g);
+ const orphansResult = await orphans(g, { vertexLabel: "Function", expectedEdge: "tests", direction: "in", changedOnly: true });
+ log(` completeness: ${completenessResults.filter(r => r.missing.length > 0).length} gaps found`);
+ log(` coverage_gaps: ${coverageResult.uncovered.length} functions without tests`);
+ log(` centrality: ${centralityResult.aboveThreshold} hotspots`);
+ log(` blast_radius: max ${blastResult.maxReachable} reachable, ${blastResult.types.length} changed types with hierarchy impact`);
+ log(` clusters: ${clusterResult.clusterCount} (${clusterResult.coherent ? "coherent" : "fragmented"})`);
+ log(` communities: ${communityResult.communityCount} themes, modularity ${communityResult.modularity} (${communityResult.isolatedCount} isolated)`);
+ log(` confidence: ${confidenceResult.distribution.EXTRACTED} extracted / ${confidenceResult.distribution.INFERRED} inferred / ${confidenceResult.distribution.AMBIGUOUS} ambiguous`);
+ log(` orphans: ${orphansResult.totalOrphaned} functions with no test`);
+
+ log(`Generating architecture map...`);
+ const architectureResult = await architecture(g, { clusterResult, changedOnly: true });
+ log(` architecture: ${architectureResult.nodes.length} nodes, ${architectureResult.edges.length} edges`);
+
+ const evidence = {
+ meta: {
+ pr,
+ title: prTitle.trim(),
+ domains,
+ language,
+ languages,
+ changedFileCount: changedFiles.length,
+ timestamp: new Date().toISOString(),
+ },
+ graphStats,
+ architecture: architectureResult,
+ checks: {
+ completeness: completenessResults,
+ coverageGaps: coverageResult,
+ centrality: centralityResult,
+ blastRadius: blastResult,
+ clusters: clusterResult,
+ communities: communityResult,
+ confidence: confidenceResult,
+ externals: externalsResult,
+ removalRefs: removalRefsResult,
+ orphans: orphansResult,
+ },
+ discussions,
+ changedFiles,
+ };
+
+ const jsonPath = join(workDir, "evidence.json");
+ await writeFile(jsonPath, JSON.stringify(evidence, null, 2), "utf-8");
+ log(`Evidence written: ${jsonPath}`);
+
+ return { evidence, jsonPath };
+}
+
+// ============================================================
+// TEARDOWN — stop server, remove worktree
+// Call this ONLY when all phases are complete.
+// ============================================================
+
+export async function teardown(sessionOrWorkDir) {
+ let repoPath, worktreePath, prBranch, containerId, workDir;
+
+ if (typeof sessionOrWorkDir === "string") {
+ // Called with just a workDir path — read session.json
+ const { readFile: rf } = await import("node:fs/promises");
+ workDir = sessionOrWorkDir;
+ const sessionData = JSON.parse(await rf(join(sessionOrWorkDir, "session.json"), "utf-8"));
+ repoPath = sessionData.repoPath;
+ worktreePath = sessionData.worktreePath;
+ containerId = sessionData.containerId;
+ prBranch = `pr-review/${sessionData.pr}`;
+ } else {
+ // Called with a live session object
+ const session = sessionOrWorkDir;
+ workDir = session.workDir;
+ repoPath = session.repoPath;
+ worktreePath = session.worktreePath;
+ prBranch = session.prBranch;
+ containerId = session.handle?.containerId;
+ if (session.aConnection) await session.aConnection.close().catch(() => {});
+ if (session.connection) await session.connection.close().catch(() => {});
+ }
+
+ // Stop the functional-test server and remove its build worktree, if one was
+ // stood up (step 4 persists its handle to functional.json).
+ if (workDir) {
+ const { readFile: rf } = await import("node:fs/promises");
+ const handle = await rf(join(workDir, "functional.json"), "utf-8")
+ .then((s) => JSON.parse(s))
+ .catch(() => null);
+ if (handle) {
+ const { stop: stopFunctional } = await import("./functional/setup.js");
+ await stopFunctional(handle, { repoPath }).catch(() => {});
+ }
+ }
+
+ if (containerId) {
+ await exec("docker", ["stop", containerId]).catch(() => {});
+ await exec("docker", ["rm", containerId]).catch(() => {});
+ }
+ await cleanupWorktree(repoPath, worktreePath, prBranch);
+ log(`Teardown complete.`);
+}
+
+// ============================================================
+// CLI entry point — runs Phase 1 only, leaves server running
+// for the agent to continue with enrichment/synthesis.
+// ============================================================
+
+if (process.argv[1] && basename(process.argv[1]) === "review.js") {
+ const pr = parseInt(process.argv[2], 10);
+ if (!pr || isNaN(pr)) {
+ console.error("Usage: node review.js <pr-number> [repo-path]");
+ console.error(" Runs Phase 1 and outputs evidence JSON.");
+ console.error(" Server stays running for enrichment. Call teardown when done.");
+ process.exit(1);
+ }
+ const repoPath = process.argv[3] || process.cwd();
+
+ const session = await setup({ pr, repoPath });
+ try {
+ const { jsonPath } = await phase1(session);
+ log(`Server running on port ${session.handle.port} — ready for enrichment.`);
+ log(`Work directory: ${session.workDir}`);
+ log(`Worktree: ${session.worktreePath}`);
+ log(`To teardown: call teardown(session) or stop container ${session.handle.containerId}`);
+
+ // Phase 1 is done. Close OUR Gremlin connections so this process exits
+ // cleanly and completion is detectable (exit code 0 + the sentinel line
+ // below). The Gremlin Server container stays up independently — enrichment
+ // (scripts/enrichment/cli.js) opens its own connection per command from
+ // session.json, so nothing depends on this process lingering.
+ await session.connection.close().catch(() => {});
+ await session.aConnection.close().catch(() => {});
+ log(`PHASE1_COMPLETE pr=${pr} evidence=${jsonPath} port=${session.handle.port} container=${session.handle.containerId}`);
+ process.exit(0);
+ } catch (err) {
+ await teardown(session).catch(() => {});
+ throw err;
+ }
+}
diff --git a/.skills/tinker-review/test/cli-docs.test.js b/.skills/tinker-review/test/cli-docs.test.js
new file mode 100644
index 0000000000..db94f9b633
--- /dev/null
+++ b/.skills/tinker-review/test/cli-docs.test.js
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Drift guard for the enrichment CLI. The COMMANDS registry in cli.js is the
+// single source of truth for which commands exist and who each is for; this
+// test fails if the human-facing surfaces fall out of sync with it:
+//
+// - references/enrichment-cli.md must have a `## <name>` section per command
+// - `cli.js --help` must list every command in the right group
+// - SKILL.md must mention every agent-facing command, and no internal one
+//
+// Add / rename / remove a command and this goes red until the docs follow.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { execFileSync } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+
+import { COMMANDS } from "../scripts/enrichment/cli.js";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const root = join(here, "..");
+
+const all = Object.keys(COMMANDS);
+const agent = all.filter((c) => COMMANDS[c].facing === "agent");
+const internal = all.filter((c) => COMMANDS[c].facing === "internal");
+
+async function read(rel) {
+ return readFile(join(root, rel), "utf-8");
+}
+
+test("every command has a facing of agent or internal", () => {
+ for (const c of all) {
+ assert.ok(
+ COMMANDS[c].facing === "agent" || COMMANDS[c].facing === "internal",
+ `command "${c}" is missing a valid facing ("agent" | "internal")`,
+ );
+ }
+});
+
+test("enrichment-cli.md documents exactly the registry's commands", async () => {
+ const doc = await read("references/enrichment-cli.md");
+ const sections = [...doc.matchAll(/^###?\s+(\w+)\s*$/gm)].map((m) => m[1]);
+ const documented = new Set(sections);
+
+ for (const c of all) {
+ assert.ok(
+ documented.has(c),
+ `command "${c}" has no "## ${c}" section in references/enrichment-cli.md`,
+ );
+ }
+ // Catch stale sections describing a command that no longer exists. Section
+ // headers that aren't command names (e.g. "Invocation") are ignored by only
+ // checking single-word headers against the registry's known non-command set.
+ const knownNonCommands = new Set(["Invocation"]);
+ for (const s of sections) {
+ if (knownNonCommands.has(s)) continue;
+ assert.ok(
+ COMMANDS[s],
+ `references/enrichment-cli.md documents "${s}", which is not a registered command`,
+ );
+ }
+});
+
+test("cli.js --help lists every command in the correct group", () => {
+ const help = execFileSync(
+ process.execPath,
+ [join(root, "scripts/enrichment/cli.js"), "--help"],
+ { encoding: "utf-8" },
+ );
+ const [commandsPart, internalPart] = help.split(/^Internal .*$/m);
+ assert.ok(internalPart, "--help is missing the 'Internal' group header");
+
+ for (const c of agent) {
+ assert.match(
+ commandsPart,
+ new RegExp(`\\b${c}\\b`),
+ `agent command "${c}" is missing from the --help Commands group`,
+ );
+ }
+ for (const c of internal) {
+ assert.match(
+ internalPart,
+ new RegExp(`\\b${c}\\b`),
+ `internal command "${c}" is missing from the --help Internal group`,
+ );
+ }
+});
+
+test("SKILL.md points at enrichment-cli.md instead of duplicating the catalog", async () => {
+ // enrichment-cli.md is the single command catalog; SKILL.md must link to it
+ // (and must not grow its own exhaustive listing again). We assert the link
+ // survives rather than that SKILL.md names every command — it deliberately
+ // names only a few pivotal ones as workflow narrative.
+ const skill = await read("SKILL.md");
+ assert.match(
+ skill,
+ /references\/enrichment-cli\.md/,
+ "SKILL.md no longer links to references/enrichment-cli.md — the command catalog reference was dropped",
+ );
+});
diff --git a/.skills/tinker-review/test/community-detection.test.js b/.skills/tinker-review/test/community-detection.test.js
new file mode 100644
index 0000000000..ef147c21d4
--- /dev/null
+++ b/.skills/tinker-review/test/community-detection.test.js
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Pure Louvain community detection over plain node/edge lists — no server needed.
+// The gremlin I/O wrapper (communityDetection) is exercised end-to-end against a
+// live graph separately; here we pin the algorithm + roll-up + post-pass behavior.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { detectCommunities } from "../scripts/patterns/community-detection.js";
+
+const fn = (id, file) => ({ id, label: "Function", name: id, filePath: file });
+const edge = (from, to, conf = "INFERRED") => ({ from, to, conf });
+
+// Two triangles joined by a single weak bridge — the textbook two-community graph.
+function barbell() {
+ const nodes = [
+ fn("a", "auth.java"), fn("b", "auth.java"), fn("c", "auth.java"),
+ fn("x", "io.java"), fn("y", "io.java"), fn("z", "io.java"),
+ ];
+ const edges = [
+ edge("a", "b", "EXTRACTED"), edge("b", "c", "EXTRACTED"), edge("a", "c", "EXTRACTED"),
+ edge("x", "y", "EXTRACTED"), edge("y", "z", "EXTRACTED"), edge("x", "z", "EXTRACTED"),
+ edge("c", "x", "AMBIGUOUS"), // weak bridge between the two dense groups
+ ];
+ return { nodes, edges };
+}
+
+test("splits a barbell into two communities and rolls them up to files", () => {
+ const { nodes, edges } = barbell();
+ const r = detectCommunities(nodes, edges, {});
+ assert.equal(r.communityCount, 2, "two dense triangles => two communities");
+ assert.ok(r.modularity > 0.3, `expected clear modular structure, got ${r.modularity}`);
+ const files = r.communities.map((c) => c.dominantFile).sort();
+ assert.deepEqual(files, ["auth.java", "io.java"], "each community rolls up to its file");
+});
+
+test("a single dense triangle is one community", () => {
+ const nodes = [fn("a", "f.java"), fn("b", "f.java"), fn("c", "f.java")];
+ const edges = [edge("a", "b"), edge("b", "c"), edge("a", "c")];
+ const r = detectCommunities(nodes, edges, {});
+ assert.equal(r.communityCount, 1);
+ assert.equal(r.communities[0].size, 3);
+});
+
+test("vertices with no in-subgraph edge are counted as isolated, not communities", () => {
+ const nodes = [
+ fn("a", "f.java"), fn("b", "f.java"), // connected pair
+ fn("orphan1", "x.java"), fn("orphan2", "y.java"), // no edges
+ ];
+ const edges = [edge("a", "b")];
+ const r = detectCommunities(nodes, edges, {});
+ assert.equal(r.communityCount, 1, "only the connected pair is a community");
+ assert.equal(r.isolatedCount, 2, "the two edgeless vertices are isolated");
+ assert.equal(r.communities[0].size, 2);
+});
+
+test("edges to a filtered-out vertex are dropped, not invented", () => {
+ const nodes = [fn("a", "f.java"), fn("b", "f.java")];
+ // 'ext' is not in the node set (e.g. an external stub excluded upstream)
+ const edges = [edge("a", "b"), edge("a", "ext"), edge("b", "ext")];
+ const r = detectCommunities(nodes, edges, {});
+ assert.equal(r.totalNodes, 2, "the missing endpoint never becomes a node");
+ assert.equal(r.totalEdges, 1, "only the fully-resolved edge survives");
+});
+
+test("the assignments map covers every node so write-back can stamp them all", () => {
+ const { nodes, edges } = barbell();
+ const r = detectCommunities(nodes, edges, {});
+ assert.equal(r.assignments.size, nodes.length, "one community assignment per vertex");
+});
+
+const testNode = (id, file, changed = false) => ({ id, label: "Test", name: id, filePath: file, changed });
+
+test("an all-test partition reads as test scaffolding, not new functional groupings", () => {
+ const nodes = [
+ testNode("t1", "AbstractIT.java"), testNode("t2", "AbstractIT.java"), testNode("t3", "AbstractIT.java"),
+ testNode("u1", "AuditLogIT.java"), testNode("u2", "AuditLogIT.java"), testNode("u3", "AuditLogIT.java"),
+ ];
+ const edges = [
+ edge("t1", "t2"), edge("t2", "t3"), edge("t1", "t3"),
+ edge("u1", "u2"), edge("u2", "u3"), edge("u1", "u3"),
+ edge("t3", "u1"),
+ ];
+ const r = detectCommunities(nodes, edges, {});
+ assert.ok(r.communities.every((c) => c.role.startsWith("test scaffolding")), "each community typed as test scaffolding");
+ assert.match(r.interpretation.headline, /modularity/);
+ assert.ok(
+ r.interpretation.reading.some((line) => /test infrastructure/i.test(line)),
+ "reading calls out that dense structure is test infrastructure",
+ );
+});
+
+test("the reading reports the changed-vs-context share when no churn is supplied", () => {
+ const nodes = [
+ fn("a", "f.java"), fn("b", "f.java"), fn("c", "f.java"), // changed:false via fn()
+ ];
+ const edges = [edge("a", "b"), edge("b", "c"), edge("a", "c")];
+ const r = detectCommunities(nodes, edges, {});
+ assert.ok(
+ r.interpretation.reading.some((line) => /0% of clustered vertices are actually changed/.test(line)),
+ "0% changed when no vertex is marked changed",
+ );
+ assert.equal(r.communities[0].changedCount, 0);
+});
+
+test("churn drives the role's change clause with real line counts", () => {
+ const nodes = [fn("a", "AbstractIT.java"), fn("b", "AbstractIT.java"), fn("c", "AbstractIT.java")];
+ const edges = [edge("a", "b"), edge("b", "c"), edge("a", "c")];
+ const churn = { "AbstractIT.java": { added: 4, removed: 120, deleted: false } };
+ const r = detectCommunities(nodes, edges, { churn });
+ assert.equal(r.communities[0].churn.mode, "reduced", "removals dominate => reduced");
+ assert.match(r.communities[0].role, /reduced \(−120\/\+4\)/, "role carries the churn counts");
+});
+
+test("net-deletion PRs get a deletion caveat and a net-deletion reading", () => {
+ const nodes = [fn("a", "AbstractIT.java"), fn("b", "AbstractIT.java")];
+ const edges = [edge("a", "b")];
+ const churn = {
+ "AbstractIT.java": { added: 2, removed: 60, deleted: false },
+ "KerberosAuthenticator.java": { added: 0, removed: 400, deleted: true },
+ "KerberosIT.java": { added: 0, removed: 210, deleted: true },
+ };
+ const r = detectCommunities(nodes, edges, { churn });
+ assert.equal(r.churn.deletedFiles, 2, "two files deleted outright");
+ assert.ok(r.interpretation.reading.some((l) => /net-deletion overall/.test(l)), "reads as net-deletion");
+ assert.ok(
+ r.interpretation.reading.some((l) => /Deleted code has no vertices/.test(l)),
+ "warns that deleted code is absent from the communities",
+ );
+});
diff --git a/.skills/tinker-review/test/discovery.test.js b/.skills/tinker-review/test/discovery.test.js
new file mode 100644
index 0000000000..b2fd2b4950
--- /dev/null
+++ b/.skills/tinker-review/test/discovery.test.js
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Precision guards for discussion discovery — the keyword extraction and the
+// proposal matcher that over-linked on ASF license boilerplate (PR #3502).
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, writeFile, mkdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { extractKeywords } from "../scripts/review.js";
+import { findMatchingProposals } from "../scripts/discovery/discussions.js";
+
+const ASF_HEADER = `////
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information.
+////
+`;
+
+test("extractKeywords drops structural filenames and keeps the title topic", () => {
+ const kws = extractKeywords(
+ ["NOTICE", "gremlin-server/src/main/java/.../Krb5Authenticator.java", "pom.xml"],
+ "Remove Kerberos support",
+ );
+ assert.ok(kws.includes("kerberos"), "title topic retained");
+ assert.ok(!kws.includes("notice"), "NOTICE excluded (structural)");
+ assert.ok(!kws.includes("remove") && !kws.includes("support"), "generic verbs dropped");
+ assert.ok(kws.includes("krb5"), "distinctive identifier token kept");
+ assert.equal(kws[0], "kerberos", "title topic leads so it can't be truncated");
+});
+
+async function withProposals(files, fn) {
+ const dir = await mkdtemp(join(tmpdir(), "tinker-prop-"));
+ const pdir = join(dir, "docs/src/dev/future");
+ await mkdir(pdir, { recursive: true });
+ try {
+ for (const [name, body] of Object.entries(files)) await writeFile(join(pdir, name), body);
+ return await fn(dir);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+test("a keyword that only appears in the ASF license header does not match (the #3502 bug)", async () => {
+ await withProposals(
+ { "proposal-equality.asciidoc": `${ASF_HEADER}= Equality Semantics\n\nNothing about auth here.\n` },
+ async (dir) => {
+ const matched = await findMatchingProposals(dir, ["notice"]);
+ assert.equal(matched.length, 0, "NOTICE in the license header must not link the proposal");
+ },
+ );
+});
+
+test("the proposals index (index.asciidoc) is excluded even on a title match", async () => {
+ await withProposals(
+ { "index.asciidoc": `${ASF_HEADER}= TinkerPop Future\n\n== Gremlin Console\n\nLinks to everything.\n` },
+ async (dir) => {
+ const matched = await findMatchingProposals(dir, ["console"]);
+ assert.equal(matched.length, 0, "the TOC index page must not be treated as a proposal");
+ },
+ );
+});
+
+test("a title keyword matches at INFERRED strength; a lone body mention does not", async () => {
+ await withProposals(
+ {
+ "proposal-asbool.asciidoc": `${ASF_HEADER}= asBool() Step\n\nDefines the asBool step.\n`,
+ "proposal-other.asciidoc": `${ASF_HEADER}= Transactions\n\nOne passing mention of asbool somewhere.\n`,
+ },
+ async (dir) => {
+ const matched = await findMatchingProposals(dir, ["asbool"]);
+ const titles = matched.map((m) => m.title);
+ assert.ok(titles.includes("asBool() Step"), "title match kept");
+ assert.equal(matched.find((m) => m.title === "asBool() Step").matchedIn, "title");
+ assert.ok(!titles.includes("Transactions"), "single body mention below threshold is dropped");
+ },
+ );
+});
diff --git a/.skills/tinker-review/test/extraction.test.js b/.skills/tinker-review/test/extraction.test.js
new file mode 100644
index 0000000000..cde766ba73
--- /dev/null
+++ b/.skills/tinker-review/test/extraction.test.js
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Verifies the tree-sitter extractor captures the type hierarchy: supertypes
+// (split into extends/implements for Java) and the declares (Type -> method)
+// membership relation that override derivation and type-seeded blast radius
+// depend on.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, writeFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { extract, extractMulti } from "../scripts/extraction/tree-sitter.js";
+
+async function withJavaSources(files, fn) {
+ const dir = await mkdtemp(join(tmpdir(), "tinker-extract-"));
+ try {
+ const changed = [];
+ for (const [name, src] of Object.entries(files)) {
+ await writeFile(join(dir, name), src);
+ changed.push(name);
+ }
+ return await fn(await extract(dir, "java", { changedFiles: changed }));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+test("Java supertypes are split into extends and implements", async () => {
+ await withJavaSources(
+ {
+ "MapStep.java":
+ "package x;\npublic class MapStep extends AbstractStep implements Cloneable, Traversal {\n public Object next() { return null; }\n}\n",
+ },
+ (r) => {
+ const t = r.types.find((t) => t.name === "MapStep");
+ assert.ok(t, "MapStep type extracted");
+ const supers = t.supertypes.reduce((m, s) => ((m[s.name] = s.relation), m), {});
+ assert.equal(supers.AbstractStep, "extends");
+ assert.equal(supers.Cloneable, "implements");
+ assert.equal(supers.Traversal, "implements");
+ },
+ );
+});
+
+test("an interface extending an interface uses the extends relation", async () => {
+ await withJavaSources(
+ { "Named.java": "package x;\ninterface Named extends Traversal { String name(); }\n" },
+ (r) => {
+ const t = r.types.find((t) => t.name === "Named");
+ assert.deepEqual(t.supertypes, [{ name: "Traversal", relation: "extends" }]);
+ },
+ );
+});
+
+test("declares maps each method to its enclosing type", async () => {
+ await withJavaSources(
+ {
+ "AbstractStep.java":
+ "package x;\nabstract class AbstractStep implements Traversal {\n public Object next() { return null; }\n protected void reset() {}\n}\n",
+ },
+ (r) => {
+ const declared = r.declares
+ .filter((d) => d.typeName === "AbstractStep")
+ .map((d) => d.functionName)
+ .sort();
+ assert.deepEqual(declared, ["next", "reset"]);
+ },
+ );
+});
+
+test("a changed file with no base version grades its members STRUCTURAL (added file)", async () => {
+ await withJavaSources(
+ { "Traversal.java": "package x;\npublic interface Traversal { Object next(); }\n" },
+ (r) => {
+ assert.equal(r.types.find((t) => t.name === "Traversal").changeLevel, "STRUCTURAL");
+ },
+ );
+});
+
+// Hierarchy-neighborhood expansion (n6r): in changed-files mode the extractor
+// pulls in the type-hierarchy neighborhood as context so override/hierarchy
+// edges don't undercount.
+const HIERARCHY = {
+ "Traversal.java": "package x;\npublic interface Traversal { Object next(); }\n",
+ "AbstractStep.java":
+ "package x;\nabstract class AbstractStep implements Traversal {\n public Object next() { return null; }\n}\n",
+ "MapStep.java":
+ "package x;\npublic class MapStep extends AbstractStep {\n public Object next() { return null; }\n}\n",
+ "Unrelated.java": "package x;\npublic class Unrelated { void foo() {} }\n",
+};
+
+async function withChanged(files, changedFiles, fn) {
+ const dir = await mkdtemp(join(tmpdir(), "tinker-hier-"));
+ try {
+ for (const [name, src] of Object.entries(files)) await writeFile(join(dir, name), src);
+ return await fn(await extract(dir, "java", { changedFiles }));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+test("changing only an interface pulls its implementers in as context (downward)", async () => {
+ await withChanged(HIERARCHY, ["Traversal.java"], (r) => {
+ const byPath = r.files.reduce((m, f) => ((m[f.path] = f.changeLevel), m), {});
+ assert.equal(byPath["Traversal.java"], "STRUCTURAL");
+ assert.equal(byPath["AbstractStep.java"], "NONE", "direct implementer pulled in as context");
+ assert.equal(byPath["MapStep.java"], "NONE", "transitive subtype pulled in as context");
+ assert.equal(byPath["Unrelated.java"], undefined, "unrelated type not pulled in");
+ });
+});
+
+test("changing only a subclass pulls its ancestors in as context (upward)", async () => {
+ await withChanged(HIERARCHY, ["MapStep.java"], (r) => {
+ const byPath = r.files.reduce((m, f) => ((m[f.path] = f.changeLevel), m), {});
+ assert.equal(byPath["MapStep.java"], "STRUCTURAL");
+ assert.equal(byPath["AbstractStep.java"], "NONE", "parent pulled in as context");
+ assert.equal(byPath["Traversal.java"], "NONE", "transitive ancestor pulled in as context");
+ assert.equal(byPath["Unrelated.java"], undefined, "unrelated type not pulled in");
+ });
+});
+
+// Multi-language extraction (P1): every language a PR touches lands in one
+// merged result, and every record is stamped with its language so population can
+// keep by-name edges from crossing languages.
+test("extractMulti merges every language and stamps records with language", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "tinker-multi-"));
+ try {
+ await writeFile(join(dir, "Svc.java"), "package x;\npublic class Svc { public void foo() {} }\n");
+ await writeFile(join(dir, "svc.py"), "class Svc:\n def foo(self):\n pass\n");
+ const r = await extractMulti(dir, ["java", "python"], { changedFiles: ["Svc.java", "svc.py"] });
+
+ assert.deepEqual([...r.languages].sort(), ["java", "python"]);
+ const langs = new Set(r.functions.map((f) => f.language));
+ assert.ok(langs.has("java") && langs.has("python"), "functions from both languages present");
+ assert.equal(r.types.find((t) => t.language === "java").name, "Svc");
+ assert.equal(r.types.find((t) => t.language === "python").name, "Svc");
+ // Every record carries a language (no undefined leaked through the merge).
+ assert.ok(r.functions.every((f) => f.language) && r.types.every((t) => t.language));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("expandHierarchy:false keeps extraction to changed files only", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "tinker-hier-"));
+ try {
+ for (const [name, src] of Object.entries(HIERARCHY)) await writeFile(join(dir, name), src);
+ const r = await extract(dir, "java", { changedFiles: ["Traversal.java"], expandHierarchy: false });
+ assert.deepEqual(r.files.map((f) => f.path), ["Traversal.java"]);
+ assert.equal(r.hierarchyNeighborhood, undefined);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/.skills/tinker-review/test/fingerprint.test.js b/.skills/tinker-review/test/fingerprint.test.js
new file mode 100644
index 0000000000..9909445b56
--- /dev/null
+++ b/.skills/tinker-review/test/fingerprint.test.js
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Verifies structural fingerprinting: the pure grade logic (gradeMember /
+// gradeFile / maxLevel / atLeast) and the end-to-end grading in the tree-sitter
+// extractor, which diffs each changed file's base version against head and
+// stamps NONE / FORMATTING / BEHAVIORAL / STRUCTURAL.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, writeFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { extract } from "../scripts/extraction/tree-sitter.js";
+import { gradeMember, gradeFile, maxLevel, atLeast, CHANGE_LEVEL } from "../scripts/graph/change-levels.js";
+
+// === Pure grade logic ===
+
+test("gradeMember covers all four outcomes", () => {
+ const base = { signature: "f(a)", rawHash: "r1", normHash: "n1" };
+ assert.equal(gradeMember(null, base), "STRUCTURAL", "no base match = added member");
+ assert.equal(gradeMember(base, { signature: "f(a)", rawHash: "r1", normHash: "n1" }), "NONE");
+ assert.equal(gradeMember(base, { signature: "f(a)", rawHash: "r2", normHash: "n1" }), "FORMATTING");
+ assert.equal(gradeMember(base, { signature: "f(a)", rawHash: "r2", normHash: "n2" }), "BEHAVIORAL");
+ assert.equal(gradeMember(base, { signature: "f(a,b)", rawHash: "r2", normHash: "n2" }), "STRUCTURAL");
+});
+
+test("maxLevel and atLeast order NONE < FORMATTING < BEHAVIORAL < STRUCTURAL", () => {
+ assert.equal(maxLevel("NONE", "FORMATTING", "BEHAVIORAL"), "BEHAVIORAL");
+ assert.equal(maxLevel("NONE", "NONE"), "NONE");
+ assert.equal(maxLevel(), "NONE");
+ assert.ok(atLeast("STRUCTURAL", "BEHAVIORAL"));
+ assert.ok(atLeast("BEHAVIORAL", "BEHAVIORAL"));
+ assert.ok(!atLeast("FORMATTING", "BEHAVIORAL"));
+ assert.ok(!atLeast("NONE", "FORMATTING"));
+});
+
+test("gradeFile rolls members up, treats import change as STRUCTURAL, floors trivia at FORMATTING", () => {
+ assert.equal(gradeFile({ memberLevels: ["NONE", "BEHAVIORAL"], rawFileChanged: true }), "BEHAVIORAL");
+ assert.equal(gradeFile({ memberLevels: ["NONE"], importExportChanged: true, rawFileChanged: true }), "STRUCTURAL");
+ assert.equal(gradeFile({ memberLevels: ["NONE"], rawFileChanged: true }), "FORMATTING", "top-level trivia floor");
+ assert.equal(gradeFile({ memberLevels: ["NONE"], rawFileChanged: false }), "NONE");
+});
+
+// === End-to-end grading through the extractor ===
+
+// Parse one changed file, diffing `base` against `head`, and return the graded
+// records. `head` is what lands on disk; `base` is fed as the prior version.
+async function gradeFileChange(name, language, base, head) {
+ const dir = await mkdtemp(join(tmpdir(), "tinker-fp-"));
+ try {
+ await writeFile(join(dir, name), head);
+ const r = await extract(dir, language, {
+ changedFiles: [name],
+ baseContents: { [name]: base },
+ expandHierarchy: false,
+ });
+ return r;
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+const JAVA_BASE =
+ "package x;\npublic class Calc {\n public int add(int a, int b) {\n return a + b;\n }\n}\n";
+
+test("Java: identical content grades NONE", async () => {
+ const r = await gradeFileChange("Calc.java", "java", JAVA_BASE, JAVA_BASE);
+ assert.equal(r.functions.find((f) => f.name === "add").changeLevel, "NONE");
+ assert.equal(r.files.find((f) => f.path === "Calc.java").changeLevel, "NONE");
+});
+
+test("Java: comment/whitespace-only edit grades FORMATTING", async () => {
+ const head =
+ "package x;\npublic class Calc {\n public int add(int a, int b) {\n // sum the two operands\n return a + b;\n }\n}\n";
+ const r = await gradeFileChange("Calc.java", "java", JAVA_BASE, head);
+ assert.equal(r.functions.find((f) => f.name === "add").changeLevel, "FORMATTING");
+});
+
+test("Java: body logic change grades BEHAVIORAL", async () => {
+ const head =
+ "package x;\npublic class Calc {\n public int add(int a, int b) {\n return a - b;\n }\n}\n";
+ const r = await gradeFileChange("Calc.java", "java", JAVA_BASE, head);
+ assert.equal(r.functions.find((f) => f.name === "add").changeLevel, "BEHAVIORAL");
+});
+
+test("Java: signature change grades STRUCTURAL", async () => {
+ const head =
+ "package x;\npublic class Calc {\n public int add(int a, int b, int c) {\n return a + b + c;\n }\n}\n";
+ const r = await gradeFileChange("Calc.java", "java", JAVA_BASE, head);
+ assert.equal(r.functions.find((f) => f.name === "add").changeLevel, "STRUCTURAL");
+});
+
+test("Java: an untouched helper in a changed file grades NONE", async () => {
+ const base =
+ "package x;\npublic class Calc {\n public int add(int a, int b) {\n return a + b;\n }\n public int untouched(int a) {\n return a;\n }\n}\n";
+ const head =
+ "package x;\npublic class Calc {\n public int add(int a, int b) {\n return a - b;\n }\n public int untouched(int a) {\n return a;\n }\n}\n";
+ const r = await gradeFileChange("Calc.java", "java", base, head);
+ assert.equal(r.functions.find((f) => f.name === "add").changeLevel, "BEHAVIORAL");
+ assert.equal(r.functions.find((f) => f.name === "untouched").changeLevel, "NONE",
+ "the helper the PR did not touch is not in the changed set");
+});
+
+// Python exercises the comment-skip on a second grammar (comment node type
+// "comment") and significant indentation.
+const PY_BASE = "class Calc:\n def add(self, a, b):\n return a + b\n";
+
+test("Python: comment-only edit grades FORMATTING", async () => {
+ const head = "class Calc:\n def add(self, a, b):\n # add them\n return a + b\n";
+ const r = await gradeFileChange("calc.py", "python", PY_BASE, head);
+ assert.equal(r.functions.find((f) => f.name === "add").changeLevel, "FORMATTING");
+});
+
+test("Python: body change grades BEHAVIORAL", async () => {
+ const head = "class Calc:\n def add(self, a, b):\n return a * b\n";
+ const r = await gradeFileChange("calc.py", "python", PY_BASE, head);
+ assert.equal(r.functions.find((f) => f.name === "add").changeLevel, "BEHAVIORAL");
+});
diff --git a/.skills/tinker-review/test/playbook-sections.test.js b/.skills/tinker-review/test/playbook-sections.test.js
new file mode 100644
index 0000000000..8f89cd345e
--- /dev/null
+++ b/.skills/tinker-review/test/playbook-sections.test.js
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Structural conformance guard for the playbooks. Every playbook must carry the
+// same six sections in the same order, split by data flow:
+//
+// Context — applicability gate
+// Enrich — graph mutation only; names real enrichment CLI commands
+// Inspect — reads changed source into findings (no graph representation)
+// Verify — functional-test battery + the gate deciding whether to run it
+// Interpret — weighs evidence.json checks (+ Inspect/Verify notes) into the report
+// Escape — stop/escalate gates
+//
+// It also fails if an Enrich section names no registered command (and doesn't
+// explicitly declare that none applies) — the drift that let playbooks gesture
+// at "link it as a discussion" without ever naming `linkDiscussion`.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFile, readdir } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+
+import { COMMANDS } from "../scripts/enrichment/cli.js";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const playbooksDir = join(here, "..", "playbooks");
+
+const CANONICAL = ["Context", "Enrich", "Inspect", "Verify", "Interpret", "Escape"];
+
+// An Enrich section that legitimately has no domain-specific graph write must
+// say so with this phrase rather than silently naming nothing.
+const NO_ENRICHMENT = /\bnone\b.*\bappl/i;
+
+const agentCommands = Object.keys(COMMANDS).filter(
+ (c) => COMMANDS[c].facing === "agent",
+);
+
+async function playbookFiles() {
+ const entries = await readdir(playbooksDir);
+ return entries.filter((f) => f.endsWith(".md"));
+}
+
+/** The level-2 headers of a markdown doc, in document order. */
+function sectionHeaders(md) {
+ return [...md.matchAll(/^##\s+(.+?)\s*$/gm)].map((m) => m[1]);
+}
+
+/** The body of one `## <name>` section, up to the next `## ` header or EOF. */
+function sectionBody(md, name) {
+ const headers = [...md.matchAll(/^##\s+(.+?)\s*$/gm)];
+ const idx = headers.findIndex((h) => h[1] === name);
+ if (idx === -1) return "";
+ const start = headers[idx].index + headers[idx][0].length;
+ const end = idx + 1 < headers.length ? headers[idx + 1].index : md.length;
+ return md.slice(start, end);
+}
+
+test("every playbook carries the six canonical sections in order", async () => {
+ for (const file of await playbookFiles()) {
+ const md = await readFile(join(playbooksDir, file), "utf-8");
+ const headers = sectionHeaders(md);
+ assert.deepEqual(
+ headers,
+ CANONICAL,
+ `${file} must have exactly these level-2 sections in order: ${CANONICAL.join(", ")} (found: ${headers.join(", ") || "none"})`,
+ );
+ }
+});
+
+test("every Enrich section names a registered command or declares none applies", async () => {
+ for (const file of await playbookFiles()) {
+ const md = await readFile(join(playbooksDir, file), "utf-8");
+ const enrich = sectionBody(md, "Enrich");
+ assert.ok(enrich.trim(), `${file} has an empty Enrich section`);
+
+ const named = agentCommands.filter((c) =>
+ new RegExp(`\\b${c}\\b`).test(enrich),
+ );
+ assert.ok(
+ named.length > 0 || NO_ENRICHMENT.test(enrich),
+ `${file} Enrich names no registered enrichment command and doesn't state that none applies`,
+ );
+ }
+});
diff --git a/bin/agent-setup.sh b/bin/agent-setup.sh
index db09b49eb1..f16cef3fd0 100755
--- a/bin/agent-setup.sh
+++ b/bin/agent-setup.sh
@@ -23,6 +23,7 @@
# TinkerPop maintains Agent Skills in .skills/:
# tinker-dev - Development guidance (coding conventions, build recipes, etc.)
# tinker-doc - Documentation authoring and review (voice, per-book style, etc.)
+# tinker-review - Graph-based PR review (knowledge graph analysis, playbooks, etc.)
#
# Different AI coding tools discover skills in different directories. This script
# creates the necessary symlinks or shims so your tool can find the skills.
@@ -47,7 +48,7 @@
set -uo pipefail
-SKILLS=("tinker-dev" "tinker-doc")
+SKILLS=("tinker-dev" "tinker-doc" "tinker-review")
RED='\033[0;31m'
GREEN='\033[0;32m'
diff --git a/docs/src/dev/developer/development-environment.asciidoc b/docs/src/dev/developer/development-environment.asciidoc
index b97a230bc1..55209ec793 100644
--- a/docs/src/dev/developer/development-environment.asciidoc
+++ b/docs/src/dev/developer/development-environment.asciidoc
@@ -476,6 +476,13 @@ open Agent Skills standard:
and development environment setup, along with a verification script in `scripts/`
* `tinker-doc` covers documentation authoring and review, meaning the per-book voice, the executable Gremlin code-block
pipeline, and AsciiDoc conventions
+* `tinker-review` covers review of a pull request by number, building a knowledge graph from the changed source and
+analyzing it against domain playbooks to produce an evidence report
+
+Unlike the other two, `tinker-review` depends on more than the repository. It requires Docker, Node.js 20 or newer, a
+remote that fetches from `apache/tinkerpop`, and a one-time `npm install --prefix .skills/tinker-review` to install its
+dependencies. A review runs against the branch the pull request targets rather than the branch that is checked out, so
+any checkout can review any pull request.
Tools that support Agent Skills (Claude Code, GitHub Copilot, Cursor, OpenAI Codex, JetBrains Junie, Kiro, and others)
will discover and activate a skill automatically when it is placed in the tool's expected directory. A setup script is