Skip to content

feat: add reproducible demo proof kit - #10

Merged
mohanagy merged 1 commit into
mainfrom
feature/demo-proof-kit
Apr 24, 2026
Merged

mohanagy merged 1 commit into
mainfrom
feature/demo-proof-kit

Conversation

@mohanagy

@mohanagy mohanagy commented Apr 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add --questions <path> support to benchmark and eval, plus shared question loading and clearer custom-question reporting
  • add examples/demo-repo/ as a reproducible 3-command proof kit and update README/docs to use the local built CLI flow
  • persist corpus metadata in manifest.json so benchmark/eval token comparisons use real corpus size when available

Test Plan

  • npm run typecheck
  • CI=1 npm run test:run
  • npm run build

Summary by CodeRabbit

  • New Features

    • Added reproducible demo repository with multi-tenant billing example
    • CLI now supports loading benchmark questions from JSON files via --questions option
    • Enhanced benchmark and evaluation to handle custom question sets and improved corpus baseline detection
  • Documentation

    • Added demo repository documentation including architecture guide and operations runbook
    • Updated main README with reproducible demo workflow instructions
    • Included benchmark question set for demo dataset validation

- add --questions support for benchmark and eval\n- add a checked-in demo repo and reproducible 3-command proof flow\n- use manifest-backed corpus sizing for honest benchmark and eval token baselines\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This pull request introduces a reproducible demo workflow for the Graphify toolkit. It includes a complete multi-tenant billing example repository (examples/demo-repo), extends the CLI with --questions file support for custom benchmark question sets, refactors benchmarking infrastructure to calculate and track corpus baselines with explicit sources, and updates manifest handling to embed metadata such as total word counts.

Changes

Cohort / File(s) Summary
Demo Repository Structure
examples/demo-repo/package.json, examples/demo-repo/tsconfig.json, examples/demo-repo/README.md
New Node.js TypeScript project configuration with ES module support, private package metadata, and strict type-checking for the multi-tenant billing demo.
Demo Domain Services
examples/demo-repo/src/auth/*, examples/demo-repo/src/billing/invoice-service.ts, examples/demo-repo/src/notifications/email-notifier.ts, examples/demo-repo/src/reports/revenue-report.ts, examples/demo-repo/src/jobs/monthly-close-job.ts
New authentication service with password policy enforcement and session management, invoice billing with email notification, revenue report generation, and a monthly close job orchestrating billing/reporting workflows.
Demo Supporting Modules
examples/demo-repo/src/shared/tenant-context.ts, examples/demo-repo/src/customers/customer-directory.ts, examples/demo-repo/src/audit/audit-log.ts, examples/demo-repo/src/support/support-escalation.ts
New shared tenant context type for multi-tenancy, customer directory lookup, audit logging, and support tier assignment utilities.
Demo Entrypoint and Questions
examples/demo-repo/src/app.ts, examples/demo-repo/benchmark-questions.json
New runDemoScenario function orchestrating a complete workflow (authenticate, invoice, monthly close, report), and a benchmark question set with five domain-specific questions and their expected labeled answers.
Demo Documentation
examples/demo-repo/docs/architecture.md, examples/demo-repo/docs/operations.md
New architecture documentation describing service components and control flow relationships, and operations runbook detailing workflows, month-end expectations, support investigation scenarios, and usage instructions.
CLI Enhancements
src/cli/main.ts, src/cli/parser.ts
CLI now supports --questions PATH option to load custom benchmark/evaluation questions from JSON files, with updated parser logic, validation, and help text.
Benchmark Corpus Baseline
src/infrastructure/benchmark/corpus.ts
New module providing corpus word/token counting, deterministic word-to-token conversion, human-readable token ratio formatting, and resolveCorpusBaseline function that prioritizes provided values, reads manifest metadata, or estimates from graph size.
Benchmark Quality Evaluation
src/infrastructure/benchmark/quality.ts
Enhanced to support both gold questions and custom benchmark question specs, normalize labels consistently, skip questions without expected_labels, derive corpus tokens from baseline, and include corpus_source in reports.
Benchmark Questions Loading
src/infrastructure/benchmark/questions.ts
New label normalization function, updated question normalization with text trimming and label filtering, and new loadBenchmarkQuestions function to load/validate/normalize questions from JSON files.
Benchmark Output
src/infrastructure/benchmark.ts
Refactored to use resolveCorpusBaseline for corpus sizing, report explicit corpus_source, use formatted token-ratio text instead of raw reduction ratios, and add early error handling for empty/unmatched question sets with context-specific messaging.
Manifest Metadata Support
src/pipeline/detect.ts
Extended manifest handling to parse and preserve embedded metadata under reserved __graphify_meta__ key, including total_words field, with new loadManifestMetadata function and updated saveManifest signature.
Graph Generation
src/infrastructure/generate.ts
Updated to pass detected total_words into manifest metadata during graph generation.
Comprehensive Test Coverage
tests/unit/benchmark-quality.test.ts, tests/unit/benchmark.test.ts, tests/unit/cli.test.ts, tests/unit/generate.test.ts
New tests for skipped-questions behavior, demo-repo reproducible benchmarking with detailed metric validation, CLI --questions option parsing and execution, and manifest metadata in generated artifacts.
Root Documentation and Configuration
.gitignore, README.md, examples/why-graphify.md
Updated to ignore demo artifacts directory, document reproducible demo workflow with expected metrics, and add "Reproducible Demo Proof" section with end-to-end command validation.

Sequence Diagram(s)

sequenceDiagram
    participant User as User/Demo
    participant App as runDemoScenario()
    participant Auth as AuthService
    participant PasswordPolicy as PasswordPolicy
    participant SessionStore as SessionStore
    participant Invoice as InvoiceService
    participant Email as EmailNotifier
    participant Job as runMonthlyCloseJob()
    participant Report as RevenueReport

    User->>App: runDemoScenario(userId, password)
    App->>Auth: loginWithPassword(userId, tenantContext, password)
    Auth->>PasswordPolicy: allows(password)
    PasswordPolicy-->>Auth: true/false
    alt Password Valid
        Auth->>SessionStore: createSession(userId, tenantContext)
        SessionStore-->>Auth: SessionRecord
        Auth-->>App: session
    else Password Invalid
        Auth-->>App: Error "Weak password"
    end
    App->>Invoice: sendInvoiceReceipt(tenantContext, customerId, amount)
    Invoice->>Email: sendReceiptEmail(invoice)
    Email-->>Invoice: receipt identifier
    Invoice-->>App: InvoiceSummary
    App->>Job: runMonthlyCloseJob(month, invoiceService, revenueReport)
    Job->>Invoice: collectOutstandingInvoices(month)
    Invoice-->>Job: count
    Job->>Report: buildMonthlyRevenueReport(month, settledInvoices)
    Report-->>Job: MonthlyRevenueSnapshot
    Job-->>App: monthlySnapshot
    App-->>User: { session, invoice, monthlySnapshot }
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • PR #7: Modifies the same benchmarking infrastructure (questions loading, normalization, BenchmarkSuccessResult fields, CLI parser options for --questions), introducing overlapping enhancements to benchmark question handling and corpus baseline logic.
  • PR #3: Updates manifest handling in src/pipeline/detect.ts (extending saveManifest/loadManifest behavior and adding manifest metadata support), which aligns with the new metadata approach in this PR.

Poem

🐰 A graph blooms in demo-repo fields,
Five questions hop through billing yields,
From login hops to invoice leaps,
Monthly close and report sweeps,
Benchmarks run, metrics bloom—
Reproducible proof in the room! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add reproducible demo proof kit' directly summarizes the main change: introducing a new demo proof kit with reproducible workflows.
Description check ✅ Passed The description includes the required Summary and Testing sections with all checklist items marked complete, and covers the main changes, test verification, and documentation updates.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/demo-proof-kit

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (9)
examples/demo-repo/src/jobs/monthly-close-job.ts (1)

9-10: Naming inconsistency: outstanding vs settled.

invoiceService.collectOutstandingInvoices(month) semantically returns the count of outstanding invoices, but here it's stored as settledInvoices and forwarded to buildMonthlyRevenueReport as the settled count (which then multiplies by 1200 to get grossRevenue). Either the method name, the variable name, or the revenue-report parameter name is wrong — and since this demo is advertised as exercising cross-module comprehension, the inconsistency may trip up readers/agents scanning the graph.

Proposed rename
-  const settledInvoices = invoiceService.collectOutstandingInvoices(month)
-  return revenueReport.buildMonthlyRevenueReport(month, settledInvoices)
+  const outstandingInvoices = invoiceService.collectOutstandingInvoices(month)
+  return revenueReport.buildMonthlyRevenueReport(month, outstandingInvoices)

(Or rename collectOutstandingInvoices → collectSettledInvoices if that's the intended semantics.)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/demo-repo/src/jobs/monthly-close-job.ts` around lines 9 - 10, The
variable and parameter naming are inconsistent:
invoiceService.collectOutstandingInvoices(month) returns outstanding invoices
but is stored as settledInvoices and passed into
revenueReport.buildMonthlyRevenueReport as if it were settled; update names so
semantics match — either rename the method to collectSettledInvoices
(invoiceService.collectOutstandingInvoices → collectSettledInvoices) or rename
the local variable settledInvoices to outstandingInvoices and adjust the
parameter name used by buildMonthlyRevenueReport (and any internal references
like the grossRevenue calculation that multiplies the count by 1200) to reflect
“outstanding” consistently across invoiceService.collectOutstandingInvoices, the
local variable, and revenueReport.buildMonthlyRevenueReport.
src/cli/main.ts (1)

519-534: Benchmark/eval --questions wiring looks correct.

options.questionsPath is conditionally loaded and forwarded to the respective entry points, and parseBenchmarkArgs(args, 'eval') correctly passes the command name for error messaging. Passing undefined for corpusWords on line 522 is intentional and defers to the manifest-backed baseline resolution inside runBenchmark.

One minor note: evaluateRetrievalQuality and formatQualityReport are still imported and called directly rather than routed through CliDependencies, unlike runBenchmark/printBenchmark. Preserving the existing asymmetry is fine, but if you later want eval to be mockable in unit tests without spying on the module, consider adding it to CliDependencies in a follow-up.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/cli/main.ts` around lines 519 - 534, The eval path calls
evaluateRetrievalQuality and formatQualityReport directly instead of via the CLI
dependency abstraction, so add evaluateRetrievalQuality and formatQualityReport
to the CliDependencies interface/implementation and replace the direct
imports/calls in main.ts with dependencies.evaluateRetrievalQuality and
dependencies.formatQualityReport (similar to how runBenchmark/printBenchmark are
invoked); update the dependency provider and any tests to supply mocks for these
new functions and ensure loadGraph/parseBenchmarkArgs usage remains unchanged.
examples/demo-repo/src/customers/customer-directory.ts (1)

16-18: Nit: add an explicit return type for consistency.

findCustomerByEmail declares its return type explicitly; listPreferredContacts relies on inference. Aligning them improves readability of the demo and keeps the graph-extracted signature predictable.

Proposed tweak
-  listPreferredContacts() {
+  listPreferredContacts(): string[] {
     return ['finance@demo.example', 'ops@demo.example']
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/demo-repo/src/customers/customer-directory.ts` around lines 16 - 18,
Add an explicit return type to the listPreferredContacts method to match the
style of findCustomerByEmail; update the signature of listPreferredContacts
(function name: listPreferredContacts) to declare its return type (e.g.,
string[] or the appropriate array type) so the demo's signatures are consistent
and the graph-extracted signature is predictable.
src/cli/parser.ts (1)

561-571: Inconsistent option-value validation between --questions and --questions= forms.

The space-separated form (Line 562) uses requireOptionValue, which rejects values that look like another flag (e.g., graphify-ts benchmark --questions --graph foo.json correctly errors out). The = form (Line 569) only calls requireNonEmptyValue, so --questions=--graph would silently be accepted as a path literally starting with --.

This is likely harmless in practice (users explicitly opt in to the = form), but for consistency consider applying requireOptionValue to both branches.

♻️ Suggested change
     if (argument.startsWith('--questions=')) {
       const [, value] = argument.split('=', 2)
-      questionsPath = requireNonEmptyValue('--questions', value)
+      questionsPath = requireOptionValue('--questions', value)
       continue
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/cli/parser.ts` around lines 561 - 571, The two parsing branches for the
--questions option are inconsistent: the space-separated branch uses
requireOptionValue (which rejects values that are other flags) but the = form
uses requireNonEmptyValue; update the = branch (the conditional that checks
argument.startsWith('--questions='), which currently extracts value and sets
questionsPath) to call requireOptionValue('--questions', value) instead of
requireNonEmptyValue so both forms validate flags the same way.
src/infrastructure/benchmark/questions.ts (2)

35-37: Aggressive label normalization may cause false-positive matches.

normalizeExpectedLabel strips every non-alphanumeric character, so labels like foo-bar, foo_bar, foo.bar(), and foobar all collapse to the same normalized form. This is intentional (and relied on by tests such as 'DEFAULT' ↔ default() and 'auth ts' ↔ auth.ts), but it means superficially distinct symbols can match.

If that's acceptable for the proof kit, consider adding a short comment documenting the design intent so future maintainers don't tighten it accidentally.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/infrastructure/benchmark/questions.ts` around lines 35 - 37,
normalizeExpectedLabel aggressively strips non-alphanumeric chars which
collapses distinct labels (e.g., "foo-bar", "foo_bar", "foo.bar()", "foobar")
into the same normalized form; to address the review, add a concise comment
above the normalizeExpectedLabel function stating this aggressive normalization
is intentional for the proof kit/tests (mentioning examples like "DEFAULT" ↔
"default()" and "auth ts" ↔ "auth.ts") and warning future maintainers that
tightening the regex may break test expectations or matching behavior.

120-121: Minor: compute matched/missing in a single pass.

Both arrays iterate expectedLabels and run the same match.labels.has(normalizeExpectedLabel(label)) predicate. For small label lists this is negligible, but a single pass avoids recomputing normalizeExpectedLabel per label twice.

♻️ Optional refactor
-  const matchedExpectedLabels = expectedLabels.filter((label) => match.labels.has(normalizeExpectedLabel(label)))
-  const missingLabels = expectedLabels.filter((label) => !match.labels.has(normalizeExpectedLabel(label)))
+  const matchedExpectedLabels: string[] = []
+  const missingLabels: string[] = []
+  for (const label of expectedLabels) {
+    if (match.labels.has(normalizeExpectedLabel(label))) {
+      matchedExpectedLabels.push(label)
+    } else {
+      missingLabels.push(label)
+    }
+  }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/infrastructure/benchmark/questions.ts` around lines 120 - 121, The two
separate filters recompute normalizeExpectedLabel for each label twice; iterate
expectedLabels once and for each label compute const n =
normalizeExpectedLabel(label) then push label into matchedExpectedLabels if
match.labels.has(n) else into missingLabels, updating the existing variables
matchedExpectedLabels and missingLabels (referencing expectedLabels,
match.labels, normalizeExpectedLabel, matchedExpectedLabels, missingLabels) to
avoid duplicate work.
src/infrastructure/benchmark.ts (1)

59-60: Subtle mismatch between usesSampleQuestions and the nullish-coalesce fallback.

questions ?? SAMPLE_QUESTIONS falls back to the sample set when questions is either undefined or null, but usesSampleQuestions = questions === undefined is false for null. If a caller ever passes null, the sample questions would run but the error messaging would blame a "supplied" question file.

The current type (questions?: BenchmarkQuestionInput[]) keeps this out of reach for TS callers, so this is defensive rather than user-visible.

♻️ Suggested alignment
-  const benchmarkQuestions = questions ?? SAMPLE_QUESTIONS
-  const usesSampleQuestions = questions === undefined
+  const benchmarkQuestions = questions ?? SAMPLE_QUESTIONS
+  const usesSampleQuestions = questions == null
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/infrastructure/benchmark.ts` around lines 59 - 60, The flag
usesSampleQuestions mismatches the nullish fallback because benchmarkQuestions
uses questions ?? SAMPLE_QUESTIONS (falls back on null or undefined) while
usesSampleQuestions checks questions === undefined (only true for undefined);
change the check to detect nullish values too (e.g., use questions == null or an
explicit questions === undefined || questions === null) so usesSampleQuestions
accurately reflects when SAMPLE_QUESTIONS is used; update references to
benchmarkQuestions, usesSampleQuestions, questions, and SAMPLE_QUESTIONS
accordingly.
src/infrastructure/benchmark/quality.ts (2)

96-107: Minor: redundant ?? [] fallback.

normalizeBenchmarkQuestion always returns expected_labels as an array (see src/infrastructure/benchmark/questions.ts lines 39-47), so normalized.expected_labels ?? [] never hits the fallback. Safe to simplify.

♻️ Proposed tweak
 function normalizeGoldQuestion(question: QualityQuestionInput): GoldQuestion | null {
   const normalized = normalizeBenchmarkQuestion(question)
-  const expectedLabels = normalized.expected_labels ?? []
-  if (expectedLabels.length === 0) {
+  if (normalized.expected_labels.length === 0) {
     return null
   }
 
   return {
     question: normalized.question,
-    expected_labels: expectedLabels,
+    expected_labels: normalized.expected_labels,
   }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/infrastructure/benchmark/quality.ts` around lines 96 - 107, The fallback
`?? []` in normalizeGoldQuestion is redundant because normalizeBenchmarkQuestion
already guarantees expected_labels is an array; update normalizeGoldQuestion to
use normalized.expected_labels directly (e.g., const expectedLabels =
normalized.expected_labels) and keep the existing length check and return
behavior so the function still returns null when expected_labels is empty.

109-130: Precompute normalized expected labels to avoid repeated work.

normalizeExpectedLabel(expected) is re-invoked for every element of returnedLabels across three separate passes (lines 114-119 and 126). For typical gold sets the cost is negligible, but precomputing once keeps the matching logic simpler and a bit cheaper.

♻️ Proposed refactor
 function evaluateQuestion(graph: KnowledgeGraph, gold: GoldQuestion, budget: number): QualityResult {
   const expectedLabels = gold.expected_labels
+  const normalizedExpected = expectedLabels.map((label) => normalizeExpectedLabel(label))
   const result: RetrieveResult = retrieveContext(graph, { question: gold.question, budget })
   const returnedLabels = result.matched_nodes.map((node) => normalizeExpectedLabel(node.label))
 
-  const matchedLabels = expectedLabels.filter((expected) =>
-    returnedLabels.some((returned) => isExactMatch(returned, normalizeExpectedLabel(expected))),
-  )
-  const missingLabels = expectedLabels.filter(
-    (expected) => !returnedLabels.some((returned) => isExactMatch(returned, normalizeExpectedLabel(expected))),
-  )
+  const returnedSet = new Set(returnedLabels)
+  const matchedLabels = expectedLabels.filter((_, i) => returnedSet.has(normalizedExpected[i]!))
+  const missingLabels = expectedLabels.filter((_, i) => !returnedSet.has(normalizedExpected[i]!))
 
   // Reciprocal rank: position of first expected label in results (1-indexed)
   let reciprocalRank = 0
   for (let i = 0; i < returnedLabels.length; i++) {
     const returned = returnedLabels[i]
     if (returned === undefined) continue
-    if (expectedLabels.some((expected) => isExactMatch(returned, normalizeExpectedLabel(expected)))) {
+    if (normalizedExpected.includes(returned)) {
       reciprocalRank = 1 / (i + 1)
       break
     }
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/infrastructure/benchmark/quality.ts` around lines 109 - 130, In
evaluateQuestion, avoid repeatedly calling normalizeExpectedLabel on each
expected label by precomputing a new array (e.g. normalizedExpected =
expectedLabels.map(normalizeExpectedLabel)) and then use normalizedExpected for
all comparisons (matchedLabels, missingLabels and the reciprocalRank loop)
instead of normalizeExpectedLabel(expected) — update references in the
matchedLabels/missingLabels filters and the reciprocal rank check to use
normalizedExpected and adjust any isExactMatch calls to compare returned
(already normalized) values against the precomputed normalizedExpected entries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@examples/demo-repo/src/customers/customer-directory.ts`:
- Around line 16-18: Add an explicit return type to the listPreferredContacts
method to match the style of findCustomerByEmail; update the signature of
listPreferredContacts (function name: listPreferredContacts) to declare its
return type (e.g., string[] or the appropriate array type) so the demo's
signatures are consistent and the graph-extracted signature is predictable.

In `@examples/demo-repo/src/jobs/monthly-close-job.ts`:
- Around line 9-10: The variable and parameter naming are inconsistent:
invoiceService.collectOutstandingInvoices(month) returns outstanding invoices
but is stored as settledInvoices and passed into
revenueReport.buildMonthlyRevenueReport as if it were settled; update names so
semantics match — either rename the method to collectSettledInvoices
(invoiceService.collectOutstandingInvoices → collectSettledInvoices) or rename
the local variable settledInvoices to outstandingInvoices and adjust the
parameter name used by buildMonthlyRevenueReport (and any internal references
like the grossRevenue calculation that multiplies the count by 1200) to reflect
“outstanding” consistently across invoiceService.collectOutstandingInvoices, the
local variable, and revenueReport.buildMonthlyRevenueReport.

In `@src/cli/main.ts`:
- Around line 519-534: The eval path calls evaluateRetrievalQuality and
formatQualityReport directly instead of via the CLI dependency abstraction, so
add evaluateRetrievalQuality and formatQualityReport to the CliDependencies
interface/implementation and replace the direct imports/calls in main.ts with
dependencies.evaluateRetrievalQuality and dependencies.formatQualityReport
(similar to how runBenchmark/printBenchmark are invoked); update the dependency
provider and any tests to supply mocks for these new functions and ensure
loadGraph/parseBenchmarkArgs usage remains unchanged.

In `@src/cli/parser.ts`:
- Around line 561-571: The two parsing branches for the --questions option are
inconsistent: the space-separated branch uses requireOptionValue (which rejects
values that are other flags) but the = form uses requireNonEmptyValue; update
the = branch (the conditional that checks argument.startsWith('--questions='),
which currently extracts value and sets questionsPath) to call
requireOptionValue('--questions', value) instead of requireNonEmptyValue so both
forms validate flags the same way.

In `@src/infrastructure/benchmark.ts`:
- Around line 59-60: The flag usesSampleQuestions mismatches the nullish
fallback because benchmarkQuestions uses questions ?? SAMPLE_QUESTIONS (falls
back on null or undefined) while usesSampleQuestions checks questions ===
undefined (only true for undefined); change the check to detect nullish values
too (e.g., use questions == null or an explicit questions === undefined ||
questions === null) so usesSampleQuestions accurately reflects when
SAMPLE_QUESTIONS is used; update references to benchmarkQuestions,
usesSampleQuestions, questions, and SAMPLE_QUESTIONS accordingly.

In `@src/infrastructure/benchmark/quality.ts`:
- Around line 96-107: The fallback `?? []` in normalizeGoldQuestion is redundant
because normalizeBenchmarkQuestion already guarantees expected_labels is an
array; update normalizeGoldQuestion to use normalized.expected_labels directly
(e.g., const expectedLabels = normalized.expected_labels) and keep the existing
length check and return behavior so the function still returns null when
expected_labels is empty.
- Around line 109-130: In evaluateQuestion, avoid repeatedly calling
normalizeExpectedLabel on each expected label by precomputing a new array (e.g.
normalizedExpected = expectedLabels.map(normalizeExpectedLabel)) and then use
normalizedExpected for all comparisons (matchedLabels, missingLabels and the
reciprocalRank loop) instead of normalizeExpectedLabel(expected) — update
references in the matchedLabels/missingLabels filters and the reciprocal rank
check to use normalizedExpected and adjust any isExactMatch calls to compare
returned (already normalized) values against the precomputed normalizedExpected
entries.

In `@src/infrastructure/benchmark/questions.ts`:
- Around line 35-37: normalizeExpectedLabel aggressively strips non-alphanumeric
chars which collapses distinct labels (e.g., "foo-bar", "foo_bar", "foo.bar()",
"foobar") into the same normalized form; to address the review, add a concise
comment above the normalizeExpectedLabel function stating this aggressive
normalization is intentional for the proof kit/tests (mentioning examples like
"DEFAULT" ↔ "default()" and "auth ts" ↔ "auth.ts") and warning future
maintainers that tightening the regex may break test expectations or matching
behavior.
- Around line 120-121: The two separate filters recompute normalizeExpectedLabel
for each label twice; iterate expectedLabels once and for each label compute
const n = normalizeExpectedLabel(label) then push label into
matchedExpectedLabels if match.labels.has(n) else into missingLabels, updating
the existing variables matchedExpectedLabels and missingLabels (referencing
expectedLabels, match.labels, normalizeExpectedLabel, matchedExpectedLabels,
missingLabels) to avoid duplicate work.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 44ae4610-2fbb-4a97-9d16-f9f10f718b0b

📥 Commits

Reviewing files that changed from the base of the PR and between 4b3600f and 09dbe91.

📒 Files selected for processing (33)
  • .gitignore
  • README.md
  • examples/demo-repo/README.md
  • examples/demo-repo/benchmark-questions.json
  • examples/demo-repo/docs/architecture.md
  • examples/demo-repo/docs/operations.md
  • examples/demo-repo/package.json
  • examples/demo-repo/src/app.ts
  • examples/demo-repo/src/audit/audit-log.ts
  • examples/demo-repo/src/auth/auth-service.ts
  • examples/demo-repo/src/auth/password-policy.ts
  • examples/demo-repo/src/auth/session-store.ts
  • examples/demo-repo/src/billing/invoice-service.ts
  • examples/demo-repo/src/customers/customer-directory.ts
  • examples/demo-repo/src/jobs/monthly-close-job.ts
  • examples/demo-repo/src/notifications/email-notifier.ts
  • examples/demo-repo/src/reports/revenue-report.ts
  • examples/demo-repo/src/shared/tenant-context.ts
  • examples/demo-repo/src/support/support-escalation.ts
  • examples/demo-repo/tsconfig.json
  • examples/why-graphify.md
  • src/cli/main.ts
  • src/cli/parser.ts
  • src/infrastructure/benchmark.ts
  • src/infrastructure/benchmark/corpus.ts
  • src/infrastructure/benchmark/quality.ts
  • src/infrastructure/benchmark/questions.ts
  • src/infrastructure/generate.ts
  • src/pipeline/detect.ts
  • tests/unit/benchmark-quality.test.ts
  • tests/unit/benchmark.test.ts
  • tests/unit/cli.test.ts
  • tests/unit/generate.test.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant