Source identity
| Field | Recorded value |
|---|---|
| Source type | GitHub source |
| Original record | Janady13/missionmatch / internal/modules/ai/graph_agency_test.go |
| Date | Not specified in source |
| Repository | Janady13/missionmatch |
| Revision | 720d47fae476b0d38477ae4401697d372b1ea2bc |
| Branch | feature/opportunity-to-outcome |
| Path or archive member | internal/modules/ai/graph_agency_test.go |
| Original SHA-256 | 60b7963e9c6b815b25a8649e63fd2e608a7862492c774aab2676003ab9a66bfe |
| Git blob SHA | fef9d128cd2dd29ce50c22530e6676cf96ff1726 |
| Reading-copy SHA-256 | 60b7963e9c6b815b25a8649e63fd2e608a7862492c774aab2676003ab9a66bfe |
Every recorded occurrence
These 12 records contain identical original source bytes. Their paths and revisions remain part of the archive.
| Original record | Branch or archive | Revision / identifier | Original location |
|---|---|---|---|
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | feature/opportunity-to-outcome | 720d47fae476b0d38477ae4401697d372b1ea2bc | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | collision-deconfliction | 4ee5a09972608ed89f8377c6665542d5f450f0a6 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | m5-price-to-win | 41000ad30fff4129fdaf5ec84e15ba14c27d4890 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | master | 1e9249840a4302ec82e123b9c9cb6f75badea3e4 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | mag-substrate | b82c7100a492dec67dfd1eda6b3f53def859be35 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | time-to-fill-survival | b66e1e505863d4f17741a4b9ede73509e45bd6c6 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | graphrag-foundation | b0ddeb9f633fd138d09309d1a17b7d13bc3a67f7 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | presentation-readiness | eb574acaa29d71ce4d0f852572e87c275c79fdb7 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | vendor-intelligence | fe9796a19c261951d3f2565206c0c1b5ac294465 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | phase2-connectors | e038d4c687aec16f8bd9bc4d907eea14d91f8704 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | feature/aioe-upgrade | 2178e7298d0e5d9af83afa12402fd587f0ba6ed8 | Open original |
| Janady13/missionmatch / internal/modules/ai/graph_agency_test.go | capture-readiness | bae6af7cb2997e819174a9e9cfff5e16067a1975 | Open original |
Recovered source transcript
Download complete source text ↓359 lines · 17.1 KB
package ai
import (
"strings"
"testing"
)
// TestGraphAgencyIntentsAreRegistered proves the three G7 agency buying pattern traversals are in the closed
// Registry, so ValidateRegistry asserts them at boot and ExecuteIntent can run them. A missing intent means
// the registration regressed.
func TestGraphAgencyIntentsAreRegistered(t *testing.T) {
cases := map[string]int{
IntentAgencyBuyingPatternDetail: 2, // agency_prefix, naics
IntentAgencyVendorConcentration: 2, // agency, naics
IntentAgencySpendTrend: 2, // agency, naics
}
for name, wantParams := range cases {
it, ok := IntentByName(name)
if !ok {
t.Fatalf("intent %q must be registered in the closed Registry", name)
}
if len(it.Params) != wantParams {
t.Errorf("intent %q must bind exactly %d params, got %d", name, wantParams, len(it.Params))
}
}
}
// TestGraphAgencyIntentsPassTheReadOnlyGuard is the load bearing security assertion: each registered agency
// intent passes GuardReadOnlyQuery against the real ReadAllowlist. A query that referenced a non allowlisted
// table, hid a mutation, or named an eeo marker would fail here, the same gate ValidateRegistry runs at boot
// and ExecuteIntent re runs at execution time.
func TestGraphAgencyIntentsPassTheReadOnlyGuard(t *testing.T) {
for _, sql := range []string{
agencyBuyingPatternDetailSQL,
agencyVendorConcentrationSQL,
agencySpendTrendSQL,
} {
if err := GuardReadOnlyQuery(sql, ReadAllowlist); err != nil {
t.Errorf("a registered agency intent must pass the read only guard: %v", err)
}
}
}
// TestValidateRegistryWithAgencyIntents proves the whole closed Registry, now carrying the three G7 intents
// alongside the TAG, G3, G1, and G9 intents, validates at boot. This is the assertion the api boot runs.
func TestValidateRegistryWithAgencyIntents(t *testing.T) {
if err := ValidateRegistry(); err != nil {
t.Fatalf("ValidateRegistry must pass with the three G7 agency intents registered: %v", err)
}
}
// TestAgencyRollupUsesSplitPartNotRecursion confirms the agency rollup is the sam_opportunities
// full_parent_path string split plus a GROUP BY, NOT a recursive CTE: the SAM hierarchy is already a
// materialized dotted path, so recursion would add a determinism risk and no value. The honesty mandate is
// explicit that the agency rollup is a split_part, never a WITH RECURSIVE.
func TestAgencyRollupUsesSplitPartNotRecursion(t *testing.T) {
// The detail intent is the only one that rolls up the agency hierarchy; the vendor concentration and the
// spend trend key directly on the award awarding_agency.
lower := strings.ToLower(agencyBuyingPatternDetailSQL)
if !strings.Contains(lower, "split_part(s.full_parent_path, '.', 1)") {
t.Error("the agency rollup must use split_part(full_parent_path, '.', 1), the materialized path split")
}
for name, sql := range map[string]string{
"agency_buying_pattern_detail": agencyBuyingPatternDetailSQL,
"agency_vendor_concentration": agencyVendorConcentrationSQL,
"agency_spend_trend": agencySpendTrendSQL,
} {
if strings.Contains(strings.ToLower(sql), "with recursive") {
t.Errorf("%s: a G7 agency read must not use a recursive CTE; the hierarchy is a materialized path", name)
}
}
}
// TestAgencyAwardsArmsKeyOnlyOnAgencyAndNaics is the honesty mandate, pinned statically: usaspending_awards
// carries NO psc, NO set_aside, and NO pop_state column, so every G7 arm that reads the award table (the award
// totals in the detail intent, the vendor concentration, and the spend trend) may not select or join on those
// columns against the award alias. The award arms key ONLY on awarding_agency and naics_code. A regression that
// reached for a phantom award column would fail here.
func TestAgencyAwardsArmsKeyOnlyOnAgencyAndNaics(t *testing.T) {
for name, sql := range map[string]string{
"agency_buying_pattern_detail": agencyBuyingPatternDetailSQL,
"agency_vendor_concentration": agencyVendorConcentrationSQL,
"agency_spend_trend": agencySpendTrendSQL,
} {
lower := strings.ToLower(sql)
// The phantom columns the award table does NOT have. None may appear qualified to the award alias a.
for _, phantom := range []string{"a.psc", "a.set_aside", "a.pop_state", "a.award_date"} {
if strings.Contains(lower, phantom) {
t.Errorf("%s: usaspending_awards has no %s column; an award arm must not reference it", name, phantom)
}
}
}
// The detail award totals and the vendor concentration and the spend trend all key on awarding_agency and
// naics_code, the only keys usaspending_awards carries.
for name, sql := range map[string]string{
"agency_vendor_concentration": agencyVendorConcentrationSQL,
"agency_spend_trend": agencySpendTrendSQL,
} {
lower := strings.ToLower(sql)
if !strings.Contains(lower, "a.awarding_agency = $1") {
t.Errorf("%s: the award arm must key on awarding_agency", name)
}
if !strings.Contains(lower, "a.naics_code = $2") {
t.Errorf("%s: the award arm must key on naics_code", name)
}
}
}
// TestAgencySpendTrendKeysFiscalPeriodOnPopStart pins the honesty detail that usaspending_awards has no
// award_date column, so the obligation trend keys the fiscal period on the only date the award carries,
// pop_start_date, and a null pop_start_date is excluded rather than bucketed under a fabricated year. A
// regression that invented an award_date or bucketed a null year would fail here.
func TestAgencySpendTrendKeysFiscalPeriodOnPopStart(t *testing.T) {
lower := strings.ToLower(agencySpendTrendSQL)
if !strings.Contains(lower, "date_part('year', a.pop_start_date)") {
t.Error("the spend trend must key the fiscal period on pop_start_date, the only award date the table carries")
}
if !strings.Contains(lower, "a.pop_start_date is not null") {
t.Error("the spend trend must exclude a null pop_start_date rather than bucket it under a fabricated year")
}
}
// TestAgencyNoFloatTouchesADollarShareOrBand is the decimal mandate, pinned statically across all three G7
// intents: no ::float8, no ::float, no ::double precision, and no ::real cast may touch a dollar figure, a
// share, an average, a median, or a band. Every dollar, average, median (percentile_cont, a numeric), and
// share stays Postgres numeric end to end and is scanned into shopspring/decimal in Go. A cast to a float type
// would silently lose the bit stable precision the AEDT compliance asset requires.
func TestAgencyNoFloatTouchesADollarShareOrBand(t *testing.T) {
intents := map[string]string{
"agency_buying_pattern_detail": agencyBuyingPatternDetailSQL,
"agency_vendor_concentration": agencyVendorConcentrationSQL,
"agency_spend_trend": agencySpendTrendSQL,
}
for name, sql := range intents {
lower := strings.ToLower(sql)
for _, floatCast := range []string{"::float8", "::float", "::double precision", "::real"} {
if strings.Contains(lower, floatCast) {
t.Errorf("%s: a float cast %q must never touch a dollar, a share, or a band (decimal mandate)", name, floatCast)
}
}
}
// The median is computed with percentile_cont, a numeric, never a float histogram; pin its presence so the
// value band stays exact decimal.
if !strings.Contains(strings.ToLower(agencyBuyingPatternDetailSQL), "percentile_cont(0.5) within group") {
t.Error("the value band median must be percentile_cont, a numeric, scanned into decimal")
}
}
// TestAgencyEveryListOrderEndsWithAUniqueTiebreaker pins the byte stable mandate: every G7 intent that returns
// a list ends its ORDER BY with a unique tiebreaker, so the same inputs yield byte identical rows. The detail
// intent orders by the record count then the grouped slice keys (a total order over the grouped rows), the
// vendor concentration orders by the share then the recipient UEI, and the spend trend orders by the fiscal
// period (a unique grouping key, one row per year, a total order on its own).
func TestAgencyEveryListOrderEndsWithAUniqueTiebreaker(t *testing.T) {
listCases := []struct {
name string
sql string
mustContain string
}{
// The detail intent orders by the record count then the full grouped slice key, a total order.
{"agency_buying_pattern_detail", agencyBuyingPatternDetailSQL, "s.naics, s.psc, s.set_aside, s.contract_vehicle"},
// The vendor concentration orders by the share then the recipient UEI tiebreaker.
{"agency_vendor_concentration", agencyVendorConcentrationSQL, "w.recipient_uei"},
// The spend trend orders by the fiscal period, the unique grouping key.
{"agency_spend_trend", agencySpendTrendSQL, "fiscal_period"},
}
for _, tc := range listCases {
lower := strings.ToLower(tc.sql)
idx := strings.LastIndex(lower, "order by")
if idx < 0 {
t.Errorf("%s: the list must be ordered for byte stability", tc.name)
continue
}
orderClause := lower[idx:]
if !strings.Contains(orderClause, strings.ToLower(tc.mustContain)) {
t.Errorf("%s: the ORDER BY must carry the unique tiebreaker %q, got %q", tc.name, tc.mustContain, orderClause)
}
}
}
// TestAgencyNullableSlicesAreCoalescedOrNullableTargets pins the G9 NULL discipline carried into G7: a nullable
// text slice column (naics, psc, set_aside, contract_vehicle) is COALESCEd to the empty string so a record with
// a missing slice still groups cleanly, and the nullable numeric value band (the average and the median) is left
// as a numeric so a slice with no priced record scans into a decimal pointer rather than failing the scan. A
// live staging run will hit these NULLs, so the discipline is load bearing.
func TestAgencyNullableSlicesAreCoalescedOrNullableTargets(t *testing.T) {
lower := strings.ToLower(agencyBuyingPatternDetailSQL)
for _, coalesced := range []string{
"coalesce(o.naics, '')",
"coalesce(o.psc, '')",
"coalesce(o.set_aside, '')",
"coalesce(o.contract_vehicle, '')",
} {
if !strings.Contains(lower, coalesced) {
t.Errorf("the detail intent must COALESCE the nullable slice column %q so a missing slice groups cleanly", coalesced)
}
}
// The average and median are aggregate over a nullable column, so they are nullable numerics; the Go scan
// targets are *decimal.Decimal. Pin the row struct fields are decimal pointers (the nullable target shape).
r := BuyingPatternDetailRow{}
if r.AvgValue != nil || r.MedianValue != nil {
t.Error("the value band average and median must be nullable decimal pointers so a slice with no priced record scans cleanly")
}
}
// TestAgencyIntentsArePublicTablesOnly pins the public data mandate: every G7 intent reads ONLY the global
// public market tables (opportunity_records, usaspending_awards, sam_opportunities) and never a tenant table.
// A regression that joined a tenant table (candidates, requirements, the bench, the eeo schema) would fail
// here, the same boundary the read allowlist enforces.
func TestAgencyIntentsArePublicTablesOnly(t *testing.T) {
publicTables := map[string]bool{
"opportunity_records": true,
"usaspending_awards": true,
"sam_opportunities": true,
}
tenantTables := []string{
"candidates", "candidate_skills", "candidate_mission_tags", "requirements",
"required_skills", "requirement_mission_tags", "slates", "slate_members",
"candidate_evaluations", "candidate_demographics", "eeo",
}
for name, sql := range map[string]string{
"agency_buying_pattern_detail": agencyBuyingPatternDetailSQL,
"agency_vendor_concentration": agencyVendorConcentrationSQL,
"agency_spend_trend": agencySpendTrendSQL,
} {
lower := strings.ToLower(sql)
for _, tt := range tenantTables {
// A whole word boundary check so a public table that contains a tenant word as a substring is not a
// false positive (none here, but the boundary keeps the assertion honest).
if strings.Contains(lower, " "+tt+" ") || strings.Contains(lower, " "+tt+"\n") || strings.Contains(lower, "from "+tt) || strings.Contains(lower, "join "+tt) {
t.Errorf("%s: must not read the tenant or eeo table %q (public data only)", name, tt)
}
}
// Positively confirm the intent reads at least one of the public market tables.
var sawPublic bool
for pt := range publicTables {
if strings.Contains(lower, pt) {
sawPublic = true
}
}
if !sawPublic {
t.Errorf("%s: must read a public market table", name)
}
}
}
// TestAgencyIntentsAreGraphIntents proves the three G7 intents are classified as GRAPH intents (dispatched to
// AnswerGraph, not AnswerTAG), so the graph evidence rendering and the graph route audit apply, and each is
// also a real registered intent in the closed Registry.
func TestAgencyIntentsAreGraphIntents(t *testing.T) {
for _, name := range []string{IntentAgencyBuyingPatternDetail, IntentAgencyVendorConcentration, IntentAgencySpendTrend} {
if !IsGraphIntent(name) {
t.Errorf("%q must be a graph intent", name)
}
if _, ok := IntentByName(name); !ok {
t.Errorf("graph intent %q must be registered in the closed Registry", name)
}
}
}
// TestGraphClassifyRoutesAgencyQuestions proves the conservative NL router maps a free form G7 agency question
// that clearly names a traversal AND carries the params to bind it unambiguously to the right intent with the
// right args. The vendor concentration and the spend trend need BOTH a quoted agency and a bare NAICS; the
// buying pattern detail needs a quoted agency with an optional NAICS. It never authors a param the user did not
// delimit.
func TestGraphClassifyRoutesAgencyQuestions(t *testing.T) {
cases := []struct {
name string
question string
intent string
args []any
}{
{
name: "vendor concentration with quoted agency and bare naics",
question: `show me the vendor concentration in "DEPT OF THE AIR FORCE" for 541512`,
intent: IntentAgencyVendorConcentration,
args: []any{"DEPT OF THE AIR FORCE", "541512"},
},
{
name: "spend trend with quoted agency and bare naics",
question: `what is the spend trend for "DEPT OF DEFENSE" 541330, concentrating or fragmenting`,
intent: IntentAgencySpendTrend,
args: []any{"DEPT OF DEFENSE", "541330"},
},
{
name: "buying pattern detail with quoted agency and optional naics",
question: `give me the vehicle mix and value band, the buying pattern detail for "GSA" 541519`,
intent: IntentAgencyBuyingPatternDetail,
args: []any{"GSA", "541519"},
},
{
name: "buying pattern detail with quoted agency and no naics",
question: `how does the agency buy, the vehicle mix for "GSA"`,
intent: IntentAgencyBuyingPatternDetail,
args: []any{"GSA", ""},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
gr := graphClassify(tc.question)
if gr == nil {
t.Fatalf("graphClassify(%q) must route to a graph intent", tc.question)
}
if gr.intent != tc.intent {
t.Errorf("intent: got %q, want %q", gr.intent, tc.intent)
}
if len(gr.args) != len(tc.args) {
t.Fatalf("args length: got %d %v, want %d %v", len(gr.args), gr.args, len(tc.args), tc.args)
}
for i := range tc.args {
if gr.args[i] != tc.args[i] {
t.Errorf("arg %d: got %v, want %v", i, gr.args[i], tc.args[i])
}
}
})
}
}
// TestGraphClassifyAgencyFallsBackWhenParamsMissing is the conservatism test for the G7 routes: an agency
// question that clearly names a traversal but does NOT carry the params to bind it returns nil, so the caller
// falls back to RAG rather than guessing an agency or a NAICS. The model never authors params; an unbindable
// agency question is a RAG question.
func TestGraphClassifyAgencyFallsBackWhenParamsMissing(t *testing.T) {
fallback := []string{
// A vendor concentration question with no quoted agency and no NAICS: nothing to bind.
"who has the vendor concentration in the cloud market",
// A vendor concentration question with a NAICS but no quoted agency: the segment key is incomplete.
"what is the vendor concentration for 541512",
// A vendor concentration question with a quoted agency but no NAICS: still incomplete.
`what is the vendor concentration in "DEPT OF THE AIR FORCE"`,
// A spend trend question with no quoted agency.
"is the spend trend concentrating or fragmenting in general",
// A spend trend question with a quoted agency but no NAICS.
`what is the spend trend for "DEPT OF DEFENSE"`,
// A buying pattern detail question with no quoted agency.
"what is the vehicle mix in general",
}
for _, q := range fallback {
if gr := graphClassify(q); gr != nil {
t.Errorf("graphClassify(%q) must fall back (nil) when params cannot be bound, got intent %q args %v", q, gr.intent, gr.args)
}
}
}
// TestGraphClassifyExistingBuyingPatternRouteUnchanged pins the Phase 0 route is byte unchanged: the existing
// G1 buying pattern keywords (agency buys, buying pattern, where to position, set aside mix) still route to the
// existing G1 IntentAgencyBuyingPattern, not the new G7 detail intent. The new detail intent is selected only by
// its distinct detail keywords (vehicle mix, value band, buying pattern detail), so the existing route is
// untouched.
func TestGraphClassifyExistingBuyingPatternRouteUnchanged(t *testing.T) {
gr := graphClassify(`what does the agency buy, the buying pattern for "GSA"`)
if gr == nil {
t.Fatal("the existing G1 buying pattern question with a quoted agency must still route")
}
if gr.intent != IntentAgencyBuyingPattern {
t.Errorf("the existing buying pattern question must route to the Phase 0 G1 intent, got %q", gr.intent)
}
}