ThatAIguyA world of ideas

THE CONSCIOUSNESS ATLAS
Read. Experiment. Follow the evidence.

ConsciousnessLearn · Explore · Joseph Anady

Janady13/missionmatch / internal/modules/ai/tag.go

Source identity, revision, and recovered contents.

GitHub sourceSource text recovered

Source identity

FieldRecorded value
Source typeGitHub source
Original recordJanady13/missionmatch / internal/modules/ai/tag.go
DateNot specified in source
RepositoryJanady13/missionmatch
Revisionbae6af7cb2997e819174a9e9cfff5e16067a1975
Branchcapture-readiness
Path or archive memberinternal/modules/ai/tag.go
Original SHA-256a5a9fcaf4c669eb9164ba2f5fc958fa97f99727fe4304dab66fcdadaa90b251f
Git blob SHAab2d4cc6ec00c3696ba7205d6e68566660bf01b0
Reading-copy SHA-256a5a9fcaf4c669eb9164ba2f5fc958fa97f99727fe4304dab66fcdadaa90b251f

Original source ↗

Recovered source transcript

package ai import ( "context" "errors" "fmt" "strings" "github.com/jackc/pgx/v5" "github.com/missionworkforce/missionmatch/internal/platform/tenant" ) // TAG (table augmented generation) answers questions that require the database to COMPUTE (count, sum, // filter, aggregate), which retrieval over text cannot do. The research is explicit that aggregation // questions must go to the database, not to vector RAG (docs/AI_RESEARCH.md, TAG). // // For cleared data the safe design is structured tool use, NOT free form natural language to SQL: the // model selects from a CURATED set of named, parameterized, read only intents and supplies typed // parameters. The model never authors SQL. Every intent is validated at startup against the read only // guard and the table allowlist, and references no eeo table, so a write or a demographics read is // impossible from the natural language path by construction. // ParamKind constrains an intent parameter so a model supplied value is type checked before binding. type ParamKind string const ( ParamText ParamKind = "text" ParamInt ParamKind = "int" ParamUUID ParamKind = "uuid" ParamEnum ParamKind = "enum" // value must be in Allowed ParamBoolean ParamKind = "bool" ) // Param describes one bound parameter of an intent. type Param struct { Name string Kind ParamKind Allowed []string // for ParamEnum Min int // for ParamInt: lower clamp bound (used only when Max > 0) Max int // for ParamInt: upper clamp bound; 0 means no clamp } // Executor selects how a registered intent runs. ExecutorSQL (the default and the only value for every TAG // and graph intent) means the intent is a curated read only SELECT run through ExecuteIntent. ExecutorModel // means the intent is a MAG (Model Augmented Generation) intent: a model backed intent whose answer is a // calibrated number computed from stored coefficients over features gathered from other Registry intents, // NOT raw SQL. A model intent carries NO reachable SQL and ExecuteIntent hard rejects it, so it can never run // as a raw query; it runs only through ExecuteModelIntent. type Executor string const ( ExecutorSQL Executor = "sql" // the default: a curated read only SELECT run through ExecuteIntent ExecutorModel Executor = "model" // a MAG intent scored from stored coefficients, run through ExecuteModelIntent ) // OutputKind is the HARD enum a MAG intent may emit. It is THE mechanism that keeps the frozen decimal engine // (internal/modules/matching, ModelVersion v1.4.0) the only per candidate scorer by construction: a learned // model may emit ONLY an opportunity level number, a display order, or a confidence, NEVER a per candidate // match score. A ModelSpec whose OutputKind is not one of these three fails ValidateRegistry at boot, and the // same three values are the CHECK constraint on aedt_learned_models.output_kind, so a candidate score is // impossible to register, impossible to store, and impossible to emit. const ( OutputKindOpportunityScore = "opportunity_score" OutputKindDisplayOrder = "display_order" OutputKindConfidence = "confidence" ) // validOutputKind reports whether a MAG output kind is one of the three legal values. Anything else (most of // all a candidate score) is rejected by ValidateRegistry, so it can never ship. func validOutputKind(kind string) bool { switch kind { case OutputKindOpportunityScore, OutputKindDisplayOrder, OutputKindConfidence: return true default: return false } } // ModelSpec is the static shape of a MAG intent: the champion model_key it serves, the OutputKind it may // emit (one of the three legal kinds), and the FeatureIntents it gathers its features from. Every // FeatureIntent MUST be another name in the closed Registry, so a model intent reads its features only // through the already guarded ExecuteIntent path (RLS, ReadAllowlist, ForbidEEO, suppression all hold). The // champion coefficients themselves are loaded from aedt_learned_models at serve time (a runtime check), so // this static spec carries no coefficient and no value. type ModelSpec struct { ModelKey string OutputKind string FeatureIntents []string } // QueryIntent is one safe, named, read only question the TAG layer can answer. SQL is parameterized // ($1, $2, ...) and runs RLS scoped as the application role, so it sees only the caller's tenant. A MAG // intent sets Executor to ExecutorModel and carries a Model spec instead of a reachable SQL body; ExecuteIntent // rejects it, so it runs only through ExecuteModelIntent. type QueryIntent struct { Name string Description string // what question it answers, used for model routing SQL string Params []Param // Executor is the empty string for a SQL intent (treated as ExecutorSQL) and ExecutorModel for a MAG // intent. Model is nil for a SQL intent and non nil for a MAG intent. Executor Executor Model *ModelSpec } // IsSQLIntent reports whether an intent runs as a curated read only SELECT (the default). A MAG intent is the // only non SQL kind; every existing TAG and graph intent leaves Executor empty and is a SQL intent. func (it QueryIntent) IsSQLIntent() bool { return it.Executor != ExecutorModel } // Registry is the closed set of TAG intents. Adding one is a reviewed security decision. var Registry = []QueryIntent{ { Name: "count_candidates_by_clearance", Description: "How many candidates hold a given clearance level (and optionally are available).", SQL: "SELECT clearance_level, count(*) AS n FROM candidates WHERE deleted_at IS NULL AND anonymized_at IS NULL AND ($1 = '' OR clearance_level = $1) GROUP BY clearance_level ORDER BY n DESC", Params: []Param{{Name: "clearance_level", Kind: ParamEnum, Allowed: []string{"", "none", "confidential", "secret", "top_secret", "ts_sci"}}}, }, { Name: "proposal_ready_for_requirement", Description: "How many persisted evaluations for a requirement are in the Green (proposal ready) band.", SQL: "SELECT band, count(*) AS n FROM candidate_evaluations WHERE requirement_id = $1 GROUP BY band ORDER BY n DESC", Params: []Param{{Name: "requirement_id", Kind: ParamUUID}}, }, { Name: "open_requirements_count", Description: "How many requirements are open (not soft deleted), optionally for one customer agency.", SQL: "SELECT count(*) AS n FROM requirements WHERE deleted_at IS NULL AND ($1 = '' OR customer_agency = $1)", Params: []Param{{Name: "customer_agency", Kind: ParamText}}, }, { Name: "slate_decision_mix", Description: "The approve/reject/pending decision mix of a slate's members.", SQL: "SELECT decision, count(*) AS n FROM slate_members WHERE slate_id = $1 GROUP BY decision ORDER BY n DESC", Params: []Param{{Name: "slate_id", Kind: ParamUUID}}, }, // G3 skill and role adjacency graph (Phase 0.B). Two FIXED recursive traversals over the curated // global skill_relationships graph and the ontology_crosswalk taxonomy. The recursive CTE text is a // reviewed static constant in graph_skill.go (skillSubstitutionClosureSQL, skillGapBridgeSQL); each // carries a hard depth cap, a visited path cycle guard, and a total order tiebreaker, so the same // inputs yield byte identical rows. They read only GLOBAL public reference tables, never eeo, never a // score. ValidateRegistry asserts them at boot and ExecuteIntent re guards them at execution. { Name: IntentSkillSubstitutionClosure, Description: "From a skill, the transitive curated substitution and broadening neighborhood with the accumulated curated strength per hop and the evidence path of edges, bounded by a hard depth cap with a cycle guard.", SQL: skillSubstitutionClosureSQL, Params: []Param{ {Name: "start_skill_id", Kind: ParamUUID}, {Name: "max_depth", Kind: ParamInt, Min: 1, Max: 5}, }, }, { Name: IntentSkillGapBridge, Description: "Given a required skill not exactly held, the nearest curated skills one or two hops away plus any ontology crosswalk bridge that maps to it, each with the evidence path, bounded by a hard depth cap with a cycle guard.", SQL: skillGapBridgeSQL, Params: []Param{ {Name: "required_skill_id", Kind: ParamUUID}, {Name: "max_depth", Kind: ParamInt, Min: 1, Max: 5}, }, }, // G1 market and relationship graph (Phase 0.C). Four FIXED capture intelligence reads over the GLOBAL // public market tables usaspending_awards, opportunity_records, and sam_opportunities. Mostly aggregates // and a full_parent_path string split for the agency hierarchy, NOT recursion (the data already carries // the keys). The SQL text is a reviewed static constant in graph_market.go. Honesty is enforced by // construction: the awards competitor field and the incumbent walk key ONLY on (agency, naics) because // usaspending_awards carries no psc, set_aside, or pop_state column; every incumbent edge is labeled // prime-of-record because the staffing subcontractor reality is absent from public award data; the finer // slices come from opportunity_records, which does carry the full tuple. Every dollar and share figure is // numeric end to end and is scanned into shopspring/decimal in Go, never float. These reads compute MARKET // aggregates, never a match score, a band, or any employment decision number; the frozen engine stays the // only scorer. ValidateRegistry asserts them at boot and ExecuteIntent re guards them on every execution. { Name: IntentSegmentCompetitorField, Description: "For an agency and NAICS, the recency weighted dollar share of each recipient UEI awarded in that segment, ordered share descending with a UEI tiebreaker, so a dominant share reads wired and a fragmented field reads open, with the contributing award count as evidence and the tenant's own past performance labeled.", SQL: segmentCompetitorFieldSQL, Params: []Param{ {Name: "agency", Kind: ParamText}, {Name: "naics", Kind: ParamText}, {Name: "lookback_years", Kind: ParamInt}, }, }, { Name: IntentIncumbentOfRecord, Description: "For an opportunity record, the predecessor award matched on agency, NAICS, and the cross source dedupe key, returning the prime recipient UEI explicitly labeled prime-of-record with the matched award as evidence.", SQL: incumbentOfRecordSQL, Params: []Param{ {Name: "opportunity_id", Kind: ParamUUID}, }, }, { Name: IntentRecompetePipeline, Description: "For an agency and a forward window in months, the opportunities and awards whose period of performance end falls inside the window, the takeaway pipeline ordered by that end date with a record id tiebreaker, each row carrying its source so an award is never conflated with an opportunity.", SQL: recompetePipelineSQL, Params: []Param{ {Name: "agency", Kind: ParamText}, // Min 1 Max 60 matches the sibling window intents (recompete_clock, recompete_teaming) so the // planner path, which runs this through ExecuteIntent and validateIntentArgs, clamps the window // identically to the dedicated RecompetePipeline wrapper and a 999 month question cannot broaden // the read only scan past five years. {Name: "window_months", Kind: ParamInt, Min: 1, Max: 60}, }, }, { Name: IntentAgencyBuyingPattern, Description: "For an agency or department prefix (rolled up through the sam_opportunities full_parent_path string split) and an optional NAICS, the NAICS and PSC distribution, set aside mix, and estimated value band of that buyer's opportunities, the where to position view.", SQL: agencyBuyingPatternSQL, Params: []Param{ {Name: "agency_prefix", Kind: ParamText}, {Name: "naics", Kind: ParamText}, }, }, // G9 recompete lifecycle and foresight graph (Phase 1.A). Three FIXED lifecycle reads over the GLOBAL // public market tables opportunity_records, usaspending_awards, federal_mission_tags, and mission_areas. // The succession is a FIXED set of LEFT JOINs over opportunity_records (the only table with the full // (agency, naics, psc, pop_state, set_aside) segment tuple), NOT a recursive CTE, because the dedupe_key // already links the phases. The recompete clock and the forecast runway are forward window reads; the // clock award arm keys ONLY on awarding_agency because usaspending_awards carries no finer key. Every // incumbent edge is labeled prime-of-record. Every dollar (estimated_value, award_amount) is numeric end // to end and is scanned into shopspring/decimal in Go, never float. These reads compute lifecycle FACTS, // never a match score, a band, or any employment decision number; the frozen engine stays the only // scorer. The window_months ParamInt carries Min 1 Max 60 so the structured path clamps the scan to the // bounded range. ValidateRegistry asserts them at boot and ExecuteIntent re guards them on every // execution. { Name: IntentProcurementSuccession, Description: "For an active solicitation opportunity, the lifecycle succession walked through the dedupe key within the same agency, NAICS, PSC, place of performance state, and set aside segment to the predecessor contract award and any announcing forecast, returning whether it is a new start or a recompete, the prior award amount and the prior prime UEI explicitly labeled prime-of-record, with the cited record ids and dates.", SQL: procurementSuccessionSQL, Params: []Param{ {Name: "opportunity_id", Kind: ParamUUID}, }, }, { Name: IntentRecompeteClock, Description: "For an agency and a forward window in months, the opportunities and awards whose period of performance end falls inside the window, the takeaway pipeline ordered by that end date with a record id tiebreaker, each row carrying its source so an award is never conflated with an opportunity and the incumbent prime named and labeled prime-of-record.", SQL: recompeteClockSQL, Params: []Param{ {Name: "agency", Kind: ParamText}, {Name: "window_months", Kind: ParamInt, Min: 1, Max: 60}, }, }, { Name: IntentForecastRunway, Description: "For a forward window in months, the forecasts whose estimated award date falls inside the window, the lead time runway joined to the federal mission area and carrying the place of performance state, ordered by estimated award date with an id tiebreaker.", SQL: forecastRunwaySQL, Params: []Param{ {Name: "window_months", Kind: ParamInt, Min: 1, Max: 60}, }, }, // G7 agency buying pattern graph (Phase 1.B). Three FIXED aggregate reads over the GLOBAL public market // tables opportunity_records, usaspending_awards, and sam_opportunities. The agency rollup is a // split_part(full_parent_path, '.', 1) string split plus a GROUP BY, NOT a recursive CTE, because the SAM // hierarchy is already a materialized dotted path. Honesty is enforced by construction: the award dollar // totals, the vendor concentration, and the spend trend key ONLY on (agency, naics) because // usaspending_awards carries no psc, set_aside, or pop_state column; the finer slices (the vehicle mix, the // set aside mix, the NAICS and PSC distribution, the value band) come from opportunity_records, which does // carry the full tuple. The spend trend keys the award fiscal period on pop_start_date because the award // table has no award_date column. Every dollar, average, median (percentile_cont, a numeric), and share is // numeric end to end and is scanned into shopspring/decimal in Go, never float; nullable text slices are // COALESCEd and nullable numerics are scanned into decimal pointers (the G9 NULL discipline). These reads // compute MARKET aggregates, never a match score, a band, or any employment decision number; the frozen // engine stays the only scorer. ValidateRegistry asserts them at boot and ExecuteIntent re guards them on // every execution. { Name: IntentAgencyBuyingPatternDetail, Description: "For an agency or department prefix (rolled up through the sam_opportunities full_parent_path string split) and an optional NAICS, the vehicle mix, set aside mix, NAICS and PSC distribution, and average and median estimated value band of the buyer's opportunity records, plus the usaspending_awards obligation totals keyed on agency and NAICS, each slice carrying the contributing record count as evidence, the where to position view.", SQL: agencyBuyingPatternDetailSQL, Params: []Param{ {Name: "agency_prefix", Kind: ParamText}, {Name: "naics", Kind: ParamText}, }, }, { Name: IntentAgencyVendorConcentration, Description: "For an agency and NAICS, the recency weighted recipient UEI dollar share over the award segment, ordered share descending with a UEI tiebreaker, the wired versus open read, with the tenant's own past performance labeled and the contributing award count as evidence.", SQL: agencyVendorConcentrationSQL, Params: []Param{ {Name: "agency", Kind: ParamText}, {Name: "naics", Kind: ParamText}, }, }, { Name: IntentAgencySpendTrend, Description: "For an agency and NAICS, the obligation total and award count per fiscal period over the award segment, ordered by the period, so the capture team reads whether the buyer's spend is concentrating or fragmenting.", SQL: agencySpendTrendSQL, Params: []Param{ {Name: "agency", Kind: ParamText}, {Name: "naics", Kind: ParamText}, }, }, // G2 public vendor co occurrence and teaming field graph (Phase 1.C). Three FIXED reads over the GLOBAL // PUBLIC market tables usaspending_awards and opportunity_records ONLY. The Phase 1 scope boundary is // enforced by construction: NONE of these read a tenant table (no requirements, no candidates, no bench, // never the eeo schema); the tenant gap intersection questions (which partner closes OUR bench gap) are // DEFERRED to Phase 2 and G6, when the person plane comes online under RLS. The only tenant side these // reads touch is the PUBLIC is_galapagos self tag on usaspending_awards, a column on the public award // catalog, never a tenant table. Honesty is enforced by construction: the awards co occurrence keys ONLY // on (agency, naics) because usaspending_awards carries no psc, set_aside, or pop_state column; the finer // five tuple precision is opportunity_records sourced and each edge carries its source_table; every vendor // edge is labeled prime-of-record. The team versus compete ratio is a numeric over a numeric guarded with // NULLIF so a partner with no compete market divides safely (a null ratio, never a divide by zero). Every // dollar, concentration, and ratio is numeric end to end and is scanned into shopspring/decimal in Go, // never float; nullable text is COALESCEd and nullable numerics are scanned into decimal pointers (the G9 // NULL discipline). These reads compute MARKET aggregates, never a match score, a band, or any employment // decision number; the frozen engine stays the only scorer. The window_months ParamInt carries Min 1 Max // 60 so the structured path clamps the scan to the bounded range. ValidateRegistry asserts them at boot and // ExecuteIntent re guards them on every execution. { Name: IntentVendorCooccurrenceField, Description: "For an agency and NAICS segment, the set of recipient and incumbent UEIs that co occur in that segment, the likely teaming and competitor field, ordered by dollar concentration with a UEI tiebreaker, each edge labeled prime-of-record and carrying its source so an award keyed on agency and NAICS is never conflated with an opportunity sourced slice.", SQL: vendorCooccurrenceFieldSQL, Params: []Param{ {Name: "agency", Kind: ParamText}, {Name: "naics", Kind: ParamText}, }, }, { Name: IntentPartnerOrCompetitorRatio, Description: "For a target partner UEI and a core NAICS, from public co occurrence alone, the count of markets where the partner co occurs with the tenant's own past performance (the is_galapagos self tag, same side teaming context) versus the markets where the partner holds the prime in the core NAICS, expressed as a team versus compete ratio guarded against a divide by zero, never a tenant table.", SQL: partnerOrCompetitorRatioSQL, Params: []Param{ {Name: "partner_uei", Kind: ParamText}, {Name: "naics", Kind: ParamText}, }, }, { Name: IntentRecompeteTeamingField, Description: "For an agency and a forward window in months, the opportunities whose period of performance end falls inside the window, each carrying its incumbent UEI labeled prime-of-record joined to that incumbent's co occurring vendor neighborhood in the same NAICS over the public awards, the likely teaming field before the RFP drops, ordered by the period of performance end with a unique tiebreaker.", SQL: recompeteTeamingFieldSQL, Params: []Param{ {Name: "agency", Kind: ParamText}, {Name: "window_months", Kind: ParamInt, Min: 1, Max: 60}, }, }, // G5 clearance lattice (Phase 2.B). Two GLOBAL reference reads over the four clearance reference tables // seeded by migration 0023 (clearance_reachability over the rank ladder plus any seeded reciprocity // exception, compartment_requirement_closure resolving a requirement's compartment codes to their kind), // plus one person touching read (bench_clearance_coverage) that intersects the global clearance_levels // ladder with the RLS protected candidates table. The two reference intents carry no person data and need // no suppression; the coverage intent runs under RunInTenantTx (the app role sees only the caller's bench) // and pipes its partition through the deterministic small cell suppression layer before any count leaves // the process. The SQL text is a reviewed static constant in graph_clearance.go. These reads compute a // lattice FACT and a suppressed structural headcount, never a match score, a band, or any employment // decision number; the frozen engine stays the only scorer. The held_code ParamEnum bounds the held // clearance to the six reference codes; the required_compartments ParamText carries the comma separated // compartment list; bench_clearance_coverage takes no SQL parameter (the suppression threshold is a Go // argument, not a bound SQL param). ValidateRegistry asserts them at boot and ExecuteIntent re guards them // on every execution. { Name: IntentClearanceReachability, Description: "For a held clearance code, every required clearance level it satisfies by the rank ladder (a held rank satisfies any required rank at or below it) plus any seeded reciprocity exception, the lattice fact a capture team reads to know which requirements a cleared candidate can fill, ordered by the required rank descending with a required code tiebreaker.", SQL: clearanceReachabilitySQL, Params: []Param{ {Name: "held_code", Kind: ParamEnum, Allowed: []string{"none", "confidential", "secret", "top_secret", "ts_sci", "unknown"}}, }, }, { Name: IntentCompartmentRequirement, Description: "For a requirement's comma separated list of required compartment codes, each recognized compartment resolved to its kind (sci or sap) and label over the global clearance compartment reference table, the closure a capture team reads to explain a compartment gap, ordered by the compartment code.", SQL: compartmentRequirementClosureSQL, Params: []Param{ {Name: "required_compartments", Kind: ParamText}, }, }, { Name: IntentBenchClearanceCoverage, Description: "How many bench candidates hold each clearance level for the caller's org, a suppressed structural headcount partition (every candidate has exactly one FK enforced clearance level, so the cells sum to the bench size), RLS scoped and piped through small cell suppression so a sub k level never surfaces a raw count, ordered by the level rank descending with a level code tiebreaker.", SQL: benchClearanceCoverageSQL, Params: nil, }, // G4 bench graph (Phase 2.C). Three FIXED person touching structural reads over the RLS protected person // tables (candidates, candidate_skills, candidate_evaluations). Each runs under RunInTenantTx (the app // role sees only the caller's bench) and pipes its aggregate partition through the deterministic small // cell suppression layer before any count leaves the process. The SQL text is a reviewed static constant // in graph_bench.go; each builds a closed partition whose counts sum to the matched total so complementary // suppression is well defined. bench_skill_coverage partitions the bench into holds versus does not hold a // skill; bench_readiness_distribution reports the distribution of bands the frozen engine ALREADY decided // and audited at evaluation time read from candidate_evaluations, recomputing nothing; bench_gap_for_ // requirement partitions the bench into meets versus does not meet by a STRUCTURAL coverage test (the // clearance rank ladder plus a fixed fraction of the required skills), a count to size a gap, never a match // score. The per candidate score and ranking remain the frozen engine, which is untouched. Each binds one // ParamUUID id; the suppression threshold is a Go argument, not a bound SQL param. ValidateRegistry asserts // them at boot and ExecuteIntent re guards them on every execution. { Name: IntentBenchSkillCoverage, Description: "How many bench candidates hold a given skill versus do not hold it for the caller's org, a suppressed two bucket structural headcount partition (each candidate either holds the skill or does not, so the cells sum to the bench size), RLS scoped and piped through small cell suppression so a sub k bucket never surfaces a raw count, ordered by the bucket label. The single skill partition is the only version; a multi skill ontology family rollup is deferred because a family is not a partition.", SQL: benchSkillCoverageSQL, Params: []Param{ {Name: "skill_id", Kind: ParamUUID}, }, }, { Name: IntentBenchReadinessDistribution, Description: "For a requirement, how many evaluated bench candidates fall in each band green, yellow, red for the caller's org, read from the already audited candidate_evaluations (the band the frozen engine assigned at evaluation time, never a recomputed score), a suppressed single valued distribution (each evaluation has one band, so the cells sum to the evaluated count), RLS scoped and piped through small cell suppression, ordered by the band label.", SQL: benchReadinessDistributionSQL, Params: []Param{ {Name: "requirement_id", Kind: ParamUUID}, }, }, { Name: IntentBenchGapForRequirement, Description: "For a requirement, how many bench candidates STRUCTURALLY meet it (hold at least the required clearance level by the rank ladder AND at least four fifths of the required skills) versus do not, a suppressed two bucket headcount partition to size a gap, explicitly NOT a match score (the per candidate score and ranking remain the frozen engine), RLS scoped and piped through small cell suppression, ordered by the bucket label.", SQL: benchGapForRequirementSQL, Params: []Param{ {Name: "requirement_id", Kind: ParamUUID}, }, }, // G6 the loop (Phase 3). capture_picture_for_requirement is an ORCHESTRATOR COMPOSITION, NOT a raw SQL // intent: it reuses the already validated bench and market planes (G4 bench_gap_for_requirement, G5 // bench_clearance_coverage, G9 recompete_clock, G1 segment_competitor_field) to answer one integrated // capture question for a requirement, who on the caller's bench can structurally staff it (the SUPPRESSED // person touching legs), the public market context (the recompete clock and, when a naics binds, the // incumbent and competitor field), and the gap, plus the price to win honest floor. It is registered here // so ValidateRegistry asserts it at boot and so it carries a real guarded read, but it NEVER runs through // the raw ExecuteIntent path: it is a benchIntent (person touching), so ExecuteIntent hard rejects it and // the AnswerGraph bench fork routes it to the answerCapturePicture composition instead. The registered SQL // is the segment resolver read (requirementSegmentSQL in graph_loop.go), a valid allowlisted single SELECT // over requirements, opportunities, and opportunity_records that passes the read only guard; it is the read // the composition runs to resolve the requirement's market segment under RLS, never a reachable raw query. // The composition computes a STRUCTURAL bench coverage and public market structure, never a match score, a // band, or any employment decision number; the frozen engine stays the only scorer. { Name: IntentCapturePictureForRequirement, Description: "For a requirement, the integrated capture picture composed across the planes: who on the caller's bench can structurally staff it (the suppressed bench gap and clearance coverage), the public market context (the recompete clock for the customer agency and, when a linked opportunity naics binds, the incumbent and competitor field), the structural gap, and the price to win honest floor, RLS scoped and small cell suppressed on the bench legs, explicitly NOT a match score (the per candidate score and ranking remain the frozen engine).", SQL: requirementSegmentSQL, Params: []Param{ {Name: "requirement_id", Kind: ParamUUID}, }, }, // M7 bid outcomes advisory base rate (bid_baserate.go). ONE aggregate read over the caller's own // bid_outcomes ledger joined to the linked requirement for the customer agency segment. It is a plain TAG // aggregate intent, NOT a graph intent and NOT a bench intent: it reads no person table, it is not in // graphIntents or benchIntents, and it runs the standard ExecuteIntent path RLS scoped as the tenant. It // reports an advisory MARKET base rate (the win count, the total decided, and the win rate as a numeric // ratio guarded with NULLIF against a divide by zero), explicitly NOT a candidate score and NOT an // employment decision number; the frozen engine stays the only scorer and no learned model consumes it // yet. The win rate is scanned into shopspring/decimal in Go, never float. It takes no SQL parameter (it // reports every segment of the caller's ledger). ValidateRegistry asserts it at boot and ExecuteIntent re // guards it on every execution. { Name: IntentBidWinRateBySegment, Description: "An advisory market base rate over the caller's own bid outcomes ledger: per customer agency segment read from the linked requirement, the win count, the total decided bids (win plus loss), and the win rate as a numeric ratio guarded against a divide by zero, RLS scoped, explicitly NOT a candidate score and NOT an employment decision number.", SQL: bidWinRateBySegmentSQL, Params: nil, }, // M5 price to win OEWS wage band (graph_wage.go). ONE aggregate read over the GLOBAL public bls_wages // reference, pivoting the two metric rows (annual_mean and annual_median) for a SOC occupation code and an // OEWS area code (HI or NM) into one advisory wage band row. It is PUBLIC reference data, NOT a bench // intent (it reads no person table), NOT suppressed, and NOT a candidate score: it reports an advisory // MARKET labor rate a capture analyst reads, explicitly NOT a match score and NOT an employment decision // number; the frozen engine stays the only scorer. The mean and median are numeric(14,2) scanned into // shopspring/decimal in Go, never float. It is a graph intent (it feeds the G6 price to win leg) but the NL // path binds it only on a clearly quoted role and a named state. ValidateRegistry asserts it at boot and // ExecuteIntent re guards it on every execution. { Name: IntentLaborRateBand, Description: "For a SOC occupation code and an OEWS area code (HI or NM), the advisory OEWS wage band pivoted from the annual mean and annual median metric rows of the global bls_wages reference, carrying the occupation title, the Galapagos role label, and the area name, both dollar figures exact decimal, explicitly NOT a match score and NOT an employment decision number.", SQL: laborRateBandSQL, Params: []Param{ {Name: "occupation_code", Kind: ParamText}, {Name: "area", Kind: ParamEnum, Allowed: []string{"HI", "NM"}}, }, }, // MAG (Model Augmented Generation) opportunity win probability (mag.go). The FIRST model backed intent // on the closed Registry. It is Executor ExecutorModel and carries a Model spec, NOT a reachable SQL body: // ExecuteIntent hard rejects it (like a bench intent), so it can never run as a raw query. It runs ONLY // through ExecuteModelIntent, which loads the CHAMPION coefficients from aedt_learned_models, gathers its // features by running each FeatureIntent through the existing ExecuteIntent path (so RLS, ReadAllowlist, // ForbidEEO, and suppression all hold), computes a calibrated probability in shopspring/decimal, and // returns an additive per feature contribution trace shaped like engine.ComponentScore. Its OutputKind is // opportunity_score, one of the three legal kinds; it can NEVER emit a per candidate match score, so the // frozen v1.4.0 engine stays the only per candidate scorer. The registered SQL is empty (a model intent // carries no query the guard would run); ValidateRegistry asserts the static MAG shape at boot and the // champion row is resolved at serve time. Params carry the segment keys it needs to bind its feature // source: an agency, and optionally a naics, bound like the other market intents. { Name: IntentOpportunityWinProbability, Description: "For a customer agency segment (and optionally a naics), the calibrated probability of winning an opportunity in that segment, a MAG opportunity_score computed from the champion opportunity_win_probability coefficients over the advisory market base rate feature, returned with the ordered per feature driver contributions and a reliability disclosure. Prior only at v0 (all learned coefficients zero), so it returns the shrunk market base rate, explicitly NOT a per candidate match score and NOT an employment decision number; the frozen engine stays the only per candidate scorer.", SQL: "", // a MAG intent carries no reachable SQL; ExecuteIntent rejects it and it runs only through ExecuteModelIntent Executor: ExecutorModel, Model: &ModelSpec{ ModelKey: WinProbabilityModelKey, OutputKind: OutputKindOpportunityScore, FeatureIntents: []string{IntentBidWinRateBySegment}, }, Params: []Param{ {Name: "agency", Kind: ParamText}, {Name: "naics", Kind: ParamText}, }, }, // Capture Readiness (capture_readiness.go), the bid pursue decision. A graph COMPOSITION, not a raw SQL // intent and not a MAG model intent: AnswerGraph intercepts it by name and dispatches to // answerCaptureReadiness, which resolves the opportunity's agency segment under RLS (this registered SQL, // guarded read only), gathers the four opportunity level factors (market win likelihood and engagement depth // from the caller's own bid ledger, staffing readiness from the opportunity's requirements, incumbency // position from the public award reference), reads the tunable weights from the coefficient store, composes // an EXACT decimal weighted average, and maps it to a GO / REVIEW / NO_GO recommendation. It is an // OPPORTUNITY level advisory, explicitly NOT a per candidate match score and NOT an employment decision; the // frozen engine stays the only per candidate scorer and it never touches the eeo schema. The registered SQL // resolves only the opportunity's segment; the composition runs it, never a reachable raw query for scoring. { Name: IntentOpportunityCaptureReadiness, Description: "For an opportunity, a Capture Readiness Score and a GO / REVIEW / NO_GO bid pursue recommendation composed from grounded opportunity level factors (the segment win likelihood, the org's engagement depth, the staffing readiness of the requirements, and the agency incumbency structure), each factor's value and weight and contribution in the trace, the weights tunable in the coefficient store. An advisory bid decision aid a human resolves, explicitly NOT a per candidate match score and NOT an employment decision number; the frozen engine stays the only per candidate scorer.", SQL: captureContextSQL, Params: []Param{ {Name: "opportunity_id", Kind: ParamUUID}, }, }, } // ValidateRegistry asserts every intent is safe: a SQL intent is read only, references no eeo, and touches // only allowlisted tables; a MAG (ExecutorModel) intent has a legal OutputKind, a non empty ModelKey, and a // feature spec that references NO eeo marker and only names in the Registry. It is called at startup and by a // test, so an unsafe intent cannot ship. The champion coefficient row is resolved at SERVE time (boot has no // database), so at boot the MAG branch asserts only the static shape. func ValidateRegistry() error { names := map[string]bool{} for _, it := range Registry { names[it.Name] = true } for _, it := range Registry { if it.Executor == ExecutorModel { if err := validateModelIntent(it, names); err != nil { return err } continue } if err := GuardReadOnlyQuery(it.SQL, ReadAllowlist); err != nil { return fmt.Errorf("ai: intent %q is unsafe: %w", it.Name, err) } } return nil } // validateModelIntent asserts the static shape of a MAG intent at boot: a non nil Model spec, a legal // OutputKind (one of the three legal kinds, so a candidate score is structurally impossible), a non empty // ModelKey, at least one FeatureIntent, and every FeatureIntent both present in the closed Registry AND free // of any eeo marker (reusing the eeo guard, so a demographics feature can never be declared). A MAG intent // must NOT carry a reachable SQL body (it never runs through the raw path), so a non empty SQL is rejected. // The champion coefficient row is resolved at serve time (boot has no database), not here. func validateModelIntent(it QueryIntent, registered map[string]bool) error { if it.Model == nil { return fmt.Errorf("ai: model intent %q has no ModelSpec", it.Name) } if strings.TrimSpace(it.SQL) != "" { return fmt.Errorf("ai: model intent %q must carry no reachable SQL", it.Name) } if !validOutputKind(it.Model.OutputKind) { return fmt.Errorf("ai: model intent %q has an illegal output kind %q; a candidate score is forbidden by construction", it.Name, it.Model.OutputKind) } if strings.TrimSpace(it.Model.ModelKey) == "" { return fmt.Errorf("ai: model intent %q has an empty model key", it.Name) } if len(it.Model.FeatureIntents) == 0 { return fmt.Errorf("ai: model intent %q declares no feature intents", it.Name) } // The feature spec (the model key and every feature intent name) must name no eeo marker, so a // demographics feature can never be declared even by a crafted spec. if err := ForbidEEO(it.Model.ModelKey); err != nil { return fmt.Errorf("ai: model intent %q references eeo in its model key: %w", it.Name, err) } for _, fi := range it.Model.FeatureIntents { if err := ForbidEEO(fi); err != nil { return fmt.Errorf("ai: model intent %q references eeo in a feature intent: %w", it.Name, err) } if !registered[fi] { return fmt.Errorf("ai: model intent %q declares feature intent %q that is not in the closed Registry", it.Name, fi) } } return nil } // IsModelIntent reports whether a registered intent name is a MAG (model backed) intent, so the dispatcher // routes it to ExecuteModelIntent rather than the raw SQL path. An unknown or empty name is not a model // intent. func IsModelIntent(name string) bool { it, ok := IntentByName(name) return ok && it.Executor == ExecutorModel } // IntentByName returns a registered intent. func IntentByName(name string) (QueryIntent, bool) { for _, it := range Registry { if it.Name == name { return it, true } } return QueryIntent{}, false } // TAGResult is the executed answer: the column names and the rows, ready to narrate. It carries no free // text from the model, only data the database returned. type TAGResult struct { Intent string Columns []string Rows [][]any } // ExecuteIntent binds the model supplied args (in the order of Params) and runs the intent RLS scoped as // the tenant. It re validates the SQL through the guard at execution time too (defense in depth), so even // a tampered registry cannot run a write or reach eeo. func ExecuteIntent(ctx context.Context, db *tenant.DB, intent QueryIntent, args []any) (*TAGResult, error) { if db == nil { return nil, errors.New("ai: no database") } // Defense in depth: a person touching bench intent must run through its suppressing executor, which builds // the partition and applies small cell suppression in Go. The raw intent path returns the database rows // verbatim, which for a bench intent would be the UNSUPPRESSED sub k headcounts, a re identification leak. // So the raw path hard rejects every bench intent; the only way to run one is the suppressing executor. if IsBenchIntent(intent.Name) { return nil, fmt.Errorf("ai: %q is a suppressed bench intent and must run through its suppressing executor, not the raw intent path", intent.Name) } // Defense in depth: a MAG (model backed) intent carries no reachable SQL and computes a calibrated number // from stored coefficients, NOT a database read. The raw path would try to run an empty query. So the raw // path hard rejects every model intent; the only way to run one is ExecuteModelIntent. if intent.Executor == ExecutorModel { return nil, fmt.Errorf("ai: %q is a model backed MAG intent and must run through ExecuteModelIntent, not the raw intent path", intent.Name) } if err := GuardReadOnlyQuery(intent.SQL, ReadAllowlist); err != nil { return nil, err } if len(args) != len(intent.Params) { return nil, fmt.Errorf("ai: intent %q expects %d params, got %d", intent.Name, len(intent.Params), len(args)) } // Defense in depth on the structured API path: enforce the declared ParamEnum allowlist and clamp a // bounded ParamInt (for example max_depth) to its range, so a caller cannot bind an out of vocabulary // enum value or an unbounded recursion depth. The recursive walks also carry an independent cycle guard, // so this is hardening, not the only bound. args, err := validateIntentArgs(intent, args) if err != nil { return nil, err } out := &TAGResult{Intent: intent.Name} err = db.RunInTenantTx(ctx, func(ctx context.Context, tx pgx.Tx) error { rows, err := tx.Query(ctx, intent.SQL, args...) if err != nil { return err } defer rows.Close() for _, fd := range rows.FieldDescriptions() { out.Columns = append(out.Columns, string(fd.Name)) } for rows.Next() { vals, err := rows.Values() if err != nil { return err } out.Rows = append(out.Rows, vals) } return rows.Err() }) if err != nil { return nil, err } return out, nil } // validateIntentArgs enforces the declared parameter contract before binding: a ParamEnum value must be in // its Allowed set, and a bounded ParamInt is clamped to [Min, Max]. It returns a copy of args with any // clamped integer replaced, so a caller on the structured API path cannot bind an out of vocabulary enum or // an unbounded value. Other kinds (UUID, text, bool) are left to pgx to type check at bind time. func validateIntentArgs(intent QueryIntent, args []any) ([]any, error) { out := make([]any, len(args)) copy(out, args) for i, p := range intent.Params { switch p.Kind { case ParamEnum: s, ok := out[i].(string) if !ok { return nil, fmt.Errorf("ai: param %q must be a string", p.Name) } if !allowedValue(s, p.Allowed) { return nil, fmt.Errorf("ai: param %q value is not in the allowed set", p.Name) } case ParamInt: if p.Max > 0 { n, err := asInt(out[i]) if err != nil { return nil, fmt.Errorf("ai: param %q must be an integer: %w", p.Name, err) } if n < p.Min { n = p.Min } if n > p.Max { n = p.Max } out[i] = n } } } return out, nil } // allowedValue reports whether v is in the allowed set. func allowedValue(v string, allowed []string) bool { for _, a := range allowed { if v == a { return true } } return false } // asInt coerces a bound argument to an int across the common numeric shapes a request decoder produces // (int, int32, int64, and a JSON float64 that is a whole number), so a bounded ParamInt can be clamped. func asInt(v any) (int, error) { switch n := v.(type) { case int: return n, nil case int32: return int(n), nil case int64: return int(n), nil case float64: if n == float64(int64(n)) { return int(n), nil } return 0, fmt.Errorf("not a whole number") default: return 0, fmt.Errorf("unsupported integer type %T", v) } }

Search equations, builds, manuscript text, and recovered sources.