ThatAIguyA world of ideas

THE CONSCIOUSNESS ATLAS
Read. Experiment. Follow the evidence.

ConsciousnessLearn · Explore · Joseph Anady

Janady13/missionmatch / internal/modules/staffing/portfolio.go

Source identity, revision, and recovered contents.

GitHub sourceSource text recovered

Source identity

FieldRecorded value
Source typeGitHub source
Original recordJanady13/missionmatch / internal/modules/staffing/portfolio.go
DateNot specified in source
RepositoryJanady13/missionmatch
Revision720d47fae476b0d38477ae4401697d372b1ea2bc
Branchfeature/opportunity-to-outcome
Path or archive memberinternal/modules/staffing/portfolio.go
Original SHA-2567a5c1fc451c522aaeae533eea889b5075e34f72101c63f1acc2517d0f839471c
Git blob SHA270659209e96a970fda3fcba943066c6cfa978e3
Reading-copy SHA-2567a5c1fc451c522aaeae533eea889b5075e34f72101c63f1acc2517d0f839471c

Original source ↗

Every recorded occurrence

These 2 records contain identical original source bytes. Their paths and revisions remain part of the archive.

Original recordBranch or archiveRevision / identifierOriginal location
Janady13/missionmatch / internal/modules/staffing/portfolio.gofeature/opportunity-to-outcome720d47fae476b0d38477ae4401697d372b1ea2bcOpen original
Janady13/missionmatch / internal/modules/staffing/portfolio.gofeature/aioe-upgrade2178e7298d0e5d9af83afa12402fd587f0ba6ed8Open original

Recovered source transcript

package staffing import ( "context" "sort" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/shopspring/decimal" "github.com/missionworkforce/missionmatch/internal/modules/matching" "github.com/missionworkforce/missionmatch/internal/modules/matching/engine" "github.com/missionworkforce/missionmatch/internal/platform/database/dbgen" ) // GeneratePortfolio allocates the available bench across the open requirements to maximize total value // (POST /recommendations/portfolio). The available bench excludes candidates already committed elsewhere; // each requirement's open slots are its quantity minus its current commitments. The optimizer arbitrates // only among engine qualified, available candidates, and each assignment carries the value matrix // counterfactual. Two portfolio runs for the same org serialize on a Postgres advisory lock, so a fresh // run never interleaves its supersede and insert with another. An empty eligible bench or no open // requirement returns an empty allocation (200), not an error; an over large problem returns // ErrProblemTooLarge and a solve over budget returns ErrSolveBudget. func (s *Service) GeneratePortfolio(ctx context.Context, req PortfolioRequest) (RunResponse, error) { if s.db == nil { return RunResponse{}, ErrNoDatabase } orgID, err := s.orgID(ctx) if err != nil { return RunResponse{}, err } floor, adj, verr := parseOverrides(req.StaffingFloor, req.AdjacencyThreshold) if verr != nil { return RunResponse{}, verr } cfg := s.cfg.WithOverrides(floor, adj) asOf := s.clock() var ( pin PortfolioInput resByPair = map[[2]int]engine.MatchResult{} candIDs []string // candidate index -> uuid string (available bench, stable order) candProv []string // candidate index -> clearance provenance candComp []decimal.Decimal // candidate index -> profile completeness reqIDs []string // requirement index -> uuid string valueSource string verr2 *ValidationError ) // Phase A (read): score the bench against each in scope open requirement and build the assignment graph. err = s.db.RunInTenantTx(ctx, func(ctx context.Context, tx pgx.Tx) error { q := dbgen.New(tx) score, e := s.scorerOnTx(ctx, tx) if e != nil { return e } openRows, e := q.ListOpenRequirementsWithValue(ctx, dbgen.ListOpenRequirementsWithValueParams{Limit: openRequirementCap, Offset: 0}) if e != nil { return e } priorities, vs := buildPriorities(cfg, openRows) valueSource = vs var subset map[string]bool if len(req.RequirementIDs) > 0 { known := map[string]bool{} for _, r := range openRows { known[r.ID.String()] = true } subset = map[string]bool{} for _, idStr := range req.RequirementIDs { if _, perr := uuid.Parse(idStr); perr != nil || !known[idStr] { verr2 = validationErr("requirement_ids", "must all be open requirement ids in this tenant") return nil // surfaced as 422 after the tx } subset[idStr] = true } } commitRows, e := q.ListCommitments(ctx) if e != nil { return e } commit := buildCommitments(commitRows) cands, e := q.ListCandidates(ctx, dbgen.ListCandidatesParams{Limit: benchScanLimit, Offset: 0}) if e != nil { return e } // Available bench = candidates not already committed anywhere. var avail []dbgen.Candidate for _, c := range cands { if _, committed := commit.byCand[c.ID.String()]; committed { continue } avail = append(avail, c) } candIDs = make([]string, len(avail)) candProv = make([]string, len(avail)) candComp = make([]decimal.Decimal, len(avail)) ecs := make([]engine.Candidate, len(avail)) for i, c := range avail { ec, e := matching.LoadEngineCandidate(ctx, q, c, asOf) if e != nil { return e } candIDs[i] = c.ID.String() candProv[i] = c.ClearanceProvenance candComp[i] = completeness(ec) ecs[i] = ec } pin.NumCandidates = len(avail) for _, rr := range openRows { if subset != nil && !subset[rr.ID.String()] { continue } openSlots := int(rr.Quantity) - commit.countByReq[rr.ID.String()] if openSlots <= 0 { continue // already fully committed: no open slots to allocate } er, e := matching.LoadEngineRequirement(ctx, q, rr.ID) if e != nil { return e } reqIdx := len(reqIDs) reqIDs = append(reqIDs, rr.ID.String()) pin.Slots = append(pin.Slots, openSlots) priority := priorities[rr.ID.String()] for candIdx, ec := range ecs { res := score(ctx, ec, er) if !ec.Available || res.Total.LessThan(cfg.StaffingFloor) { continue // the optimizer only sees engine qualified, available candidates } v := ScaledValue(res.Total, priority, cfg.ValueScalePrecision) if v <= 0 { continue } pin.Edges = append(pin.Edges, AssignEdge{CandidateIdx: candIdx, RequirementIdx: reqIdx, Value: v}) resByPair[[2]int{candIdx, reqIdx}] = res } } return nil }) if err != nil { return RunResponse{}, err } if verr2 != nil { return RunResponse{}, verr2 } // Phase A.5 (no tx): solve, bounded by the size cap and the solve budget. solveCtx, cancel := context.WithTimeout(ctx, cfg.SolveBudget) defer cancel() sol, err := SolvePortfolio(solveCtx, pin, cfg.MaxProblemEdges, cfg.MaxProblemNodes) if err != nil { return RunResponse{}, err // ErrProblemTooLarge or ErrSolveBudget, surfaced as 413 or 503 } cf := Counterfactuals(pin, sol) // Build the recommendations: an ASSIGN per optimal assignment, a SOURCE per requirement left short. recs := s.buildPortfolioRecs(cfg, sol, pin, cf, resByPair, candIDs, candProv, candComp, reqIDs) // The frozen result for each assigned pair, keyed for the eval upsert in persistRun. assignedRes := map[string]engine.MatchResult{} for _, a := range sol.Assignments { assignedRes[pairKey(candIDs[a.CandidateIdx], reqIDs[a.RequirementIdx])] = resByPair[[2]int{a.CandidateIdx, a.RequirementIdx}] } // Phase B (no tx): narrate. enriched := s.enrich(ctx, recs) // Phase C (write): serialize per org on an advisory lock, then persist atomically. var run dbgen.RecommendationRun var rows []dbgen.StaffingRecommendation err = s.db.RunInTenantTx(ctx, func(ctx context.Context, tx pgx.Tx) error { // Serialize portfolio runs for this org so a fresh run never interleaves its supersede and insert // with another (the read committed snapshot would otherwise leave two live pending sets). if e := acquireAdvisoryLock(ctx, tx, advisoryKey(ViewPortfolio, orgID, "")); e != nil { return e } var e error run, rows, e = s.persistRun(ctx, tx, orgID, ViewPortfolio, nil, runParams(cfg, valueSource), "staffing.portfolio", enriched, assignedRes, func(ctx context.Context, q *dbgen.Queries) error { return q.SupersedePendingPortfolio(ctx) }) return e }) if err != nil { return RunResponse{}, err } return RunResponse{Run: runView(run), Recommendations: recommendationViews(rows)}, nil } // buildPortfolioRecs turns the optimal allocation into ranked recommendations: ASSIGN rows (highest value // first) with the value matrix counterfactual, then a SOURCE row per requirement whose open slots the bench // could not fill. func (s *Service) buildPortfolioRecs(cfg Config, sol PortfolioSolution, pin PortfolioInput, cf map[int]AssignCounterfactual, resByPair map[[2]int]engine.MatchResult, candIDs, candProv []string, candComp []decimal.Decimal, reqIDs []string) []Recommendation { assigns := append([]Assignment(nil), sol.Assignments...) sort.SliceStable(assigns, func(i, j int) bool { if assigns[i].Value != assigns[j].Value { return assigns[i].Value > assigns[j].Value } if assigns[i].CandidateIdx != assigns[j].CandidateIdx { return assigns[i].CandidateIdx < assigns[j].CandidateIdx } return assigns[i].RequirementIdx < assigns[j].RequirementIdx }) filled := make([]int, len(pin.Slots)) var recs []Recommendation rank := 0 for _, a := range assigns { filled[a.RequirementIdx]++ rank++ res := resByPair[[2]int{a.CandidateIdx, a.RequirementIdx}] ev := Evidence{ EngineTotal: res.Total.StringFixed(2), Band: res.Band.Code(), Counterfactual: portfolioCounterfactual(cf[a.CandidateIdx], res, candIDs, reqIDs), } conf := Confidence(cfg, ScoredCandidate{Total: res.Total, Provenance: candProv[a.CandidateIdx], Completeness: candComp[a.CandidateIdx]}) value := a.Value recs = append(recs, Recommendation{ RequirementID: reqIDs[a.RequirementIdx], CandidateID: candIDs[a.CandidateIdx], Action: ActionAssign, Rank: rank, Confidence: conf, ValueScore: &value, Evidence: ev, }) } for j := range pin.Slots { if remaining := pin.Slots[j] - filled[j]; remaining > 0 { rank++ rem := remaining recs = append(recs, Recommendation{ RequirementID: reqIDs[j], Action: ActionSource, Rank: rank, Confidence: decimal.NewFromInt(1), Evidence: Evidence{OpenSlots: &rem}, }) } } return recs } func portfolioCounterfactual(cf AssignCounterfactual, res engine.MatchResult, candIDs, reqIDs []string) *Counterfactual { c := &Counterfactual{AssignedTotal: res.Total.StringFixed(2)} if cf.CandidateNextReqIdx >= 0 && cf.CandidateNextReqIdx < len(reqIDs) { c.CandidateNextRequirement = reqIDs[cf.CandidateNextReqIdx] d := cf.CandidateValueDelta c.CandidateValueDelta = &d } if cf.RequirementNextCandIdx >= 0 && cf.RequirementNextCandIdx < len(candIDs) { c.RequirementNextCandidate = candIDs[cf.RequirementNextCandIdx] d := cf.RequirementValueDelta c.RequirementValueDelta = &d } return c }

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