Repository navigation
feat: add reproducible demo proof kit - #10
Conversation
- 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>
📝 WalkthroughWalkthroughThis pull request introduces a reproducible demo workflow for the Graphify toolkit. It includes a complete multi-tenant billing example repository ( Changes
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 }
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (9)
examples/demo-repo/src/jobs/monthly-close-job.ts (1)
9-10: Naming inconsistency:outstandingvssettled.
invoiceService.collectOutstandingInvoices(month)semantically returns the count of outstanding invoices, but here it's stored assettledInvoicesand forwarded tobuildMonthlyRevenueReportas the settled count (which then multiplies by1200to getgrossRevenue). 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→collectSettledInvoicesif 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--questionswiring looks correct.
options.questionsPathis conditionally loaded and forwarded to the respective entry points, andparseBenchmarkArgs(args, 'eval')correctly passes the command name for error messaging. PassingundefinedforcorpusWordson line 522 is intentional and defers to the manifest-backed baseline resolution insiderunBenchmark.One minor note:
evaluateRetrievalQualityandformatQualityReportare still imported and called directly rather than routed throughCliDependencies, unlikerunBenchmark/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 toCliDependenciesin 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.
findCustomerByEmaildeclares its return type explicitly;listPreferredContactsrelies 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--questionsand--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.jsoncorrectly errors out). The=form (Line 569) only callsrequireNonEmptyValue, so--questions=--graphwould 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 applyingrequireOptionValueto 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.
normalizeExpectedLabelstrips every non-alphanumeric character, so labels likefoo-bar,foo_bar,foo.bar(), andfoobarall 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
expectedLabelsand run the samematch.labels.has(normalizeExpectedLabel(label))predicate. For small label lists this is negligible, but a single pass avoids recomputingnormalizeExpectedLabelper 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 betweenusesSampleQuestionsand the nullish-coalesce fallback.
questions ?? SAMPLE_QUESTIONSfalls back to the sample set whenquestionsis eitherundefinedornull, butusesSampleQuestions = questions === undefinedisfalsefornull. If a caller ever passesnull, 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.
normalizeBenchmarkQuestionalways returnsexpected_labelsas an array (seesrc/infrastructure/benchmark/questions.tslines 39-47), sonormalized.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 ofreturnedLabelsacross 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
📒 Files selected for processing (33)
.gitignoreREADME.mdexamples/demo-repo/README.mdexamples/demo-repo/benchmark-questions.jsonexamples/demo-repo/docs/architecture.mdexamples/demo-repo/docs/operations.mdexamples/demo-repo/package.jsonexamples/demo-repo/src/app.tsexamples/demo-repo/src/audit/audit-log.tsexamples/demo-repo/src/auth/auth-service.tsexamples/demo-repo/src/auth/password-policy.tsexamples/demo-repo/src/auth/session-store.tsexamples/demo-repo/src/billing/invoice-service.tsexamples/demo-repo/src/customers/customer-directory.tsexamples/demo-repo/src/jobs/monthly-close-job.tsexamples/demo-repo/src/notifications/email-notifier.tsexamples/demo-repo/src/reports/revenue-report.tsexamples/demo-repo/src/shared/tenant-context.tsexamples/demo-repo/src/support/support-escalation.tsexamples/demo-repo/tsconfig.jsonexamples/why-graphify.mdsrc/cli/main.tssrc/cli/parser.tssrc/infrastructure/benchmark.tssrc/infrastructure/benchmark/corpus.tssrc/infrastructure/benchmark/quality.tssrc/infrastructure/benchmark/questions.tssrc/infrastructure/generate.tssrc/pipeline/detect.tstests/unit/benchmark-quality.test.tstests/unit/benchmark.test.tstests/unit/cli.test.tstests/unit/generate.test.ts
Summary
--questions <path>support tobenchmarkandeval, plus shared question loading and clearer custom-question reportingexamples/demo-repo/as a reproducible 3-command proof kit and update README/docs to use the local built CLI flowmanifest.jsonso benchmark/eval token comparisons use real corpus size when availableTest Plan
Summary by CodeRabbit
New Features
--questionsoptionDocumentation