diff --git a/apps/nextpath/README.md b/apps/nextpath/README.md index 87603be..ac45f8f 100644 --- a/apps/nextpath/README.md +++ b/apps/nextpath/README.md @@ -47,6 +47,13 @@ six-digit CIP programs, Projections Central for Arizona annual openings and employment growth, and Ayla's public government hiring feed for a current Arizona posting snapshot. +The same unattended refresh expands the original 12 curated careers to 75 by +joining O*NET 31.0 interests and descriptions, the official NCES CIP-to-SOC +crosswalk, Arizona IPEDS completions, and Arizona projections. The curated set +remains required and is used as the embedded fallback. Set +`LAB_NEXTPATH_CATALOG_LIMIT` to a value from 12 through 200 before deployment to +change the managed size. + Deploy normally: ```bash @@ -54,7 +61,8 @@ Deploy normally: ``` Deployment refreshes evidence and enables a daily systemd timer. Refreshes are -atomic; a source failure preserves the last successful snapshot. Operators can -run `./jeannie nextpath status` or `./jeannie nextpath refresh`. There are no -prompts, tokens, or browser-side source credentials. +staged; the catalog, mapping, and evidence are promoted only after the complete +run succeeds, so a source failure preserves the last successful set. Operators +can run `./jeannie nextpath status` or `./jeannie nextpath refresh`. There are +no prompts, tokens, or browser-side source credentials. diff --git a/cmd/nextpath/internal/career/catalog.go b/cmd/nextpath/internal/career/catalog.go index 2449ae0..288bfe5 100644 --- a/cmd/nextpath/internal/career/catalog.go +++ b/cmd/nextpath/internal/career/catalog.go @@ -6,6 +6,7 @@ import ( _ "embed" "encoding/json" "fmt" + "os" "sort" "my-homelab-configs/cmd/nextpath/internal/assessment" @@ -36,12 +37,29 @@ type Match struct { } func DefaultCatalog() (Catalog, error) { + return decodeCatalog(defaultCatalogJSON) +} + +// Load reads an automatically generated catalog, falling back to the embedded +// curated catalog only when no runtime path is configured. +func Load(path string) (Catalog, error) { + if path == "" { + return DefaultCatalog() + } + data, err := os.ReadFile(path) + if err != nil { + return Catalog{}, fmt.Errorf("read occupation catalog: %w", err) + } + return decodeCatalog(data) +} + +func decodeCatalog(data []byte) (Catalog, error) { var catalog Catalog - if err := json.Unmarshal(defaultCatalogJSON, &catalog); err != nil { - return Catalog{}, fmt.Errorf("decode embedded occupation catalog: %w", err) + if err := json.Unmarshal(data, &catalog); err != nil { + return Catalog{}, fmt.Errorf("decode occupation catalog: %w", err) } if catalog.Version == "" || len(catalog.Occupations) == 0 { - return Catalog{}, fmt.Errorf("embedded occupation catalog is empty") + return Catalog{}, fmt.Errorf("occupation catalog is empty") } return catalog, nil } diff --git a/cmd/nextpath/internal/career/catalog_test.go b/cmd/nextpath/internal/career/catalog_test.go index d895a9e..03b6db9 100644 --- a/cmd/nextpath/internal/career/catalog_test.go +++ b/cmd/nextpath/internal/career/catalog_test.go @@ -1,6 +1,8 @@ package career import ( + "os" + "path/filepath" "testing" "my-homelab-configs/cmd/nextpath/internal/assessment" @@ -34,6 +36,21 @@ func TestDefaultCatalogRanksInterestFitWithoutClaimingEmployability(t *testing.T } } +func TestLoadUsesGeneratedRuntimeCatalog(t *testing.T) { + path := filepath.Join(t.TempDir(), "catalog.json") + data := `{"version":"generated-test","occupations":[{"onet_soc":"11-1111.00","title":"Generated Career","interest_order":["I","R","C"],"summary":"Generated from public data.","try_first":"Try it.","source_url":"https://example.test"}]}` + if err := os.WriteFile(path, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + catalog, err := Load(path) + if err != nil { + t.Fatal(err) + } + if catalog.Version != "generated-test" || len(catalog.Occupations) != 1 || catalog.Occupations[0].Title != "Generated Career" { + t.Fatalf("unexpected generated catalog: %+v", catalog) + } +} + func TestRankIsDeterministicForTies(t *testing.T) { catalog, _ := DefaultCatalog() matches := Rank(assessment.Result{}, catalog, len(catalog.Occupations)) diff --git a/cmd/nextpath/internal/web/server.go b/cmd/nextpath/internal/web/server.go index 14a3c1c..9ac7abc 100644 --- a/cmd/nextpath/internal/web/server.go +++ b/cmd/nextpath/internal/web/server.go @@ -30,6 +30,7 @@ type Config struct { SessionTTL time.Duration Logger *slog.Logger OpportunityStorePath string + CatalogPath string } type careerResult struct { @@ -232,7 +233,7 @@ func (server *Server) results(writer http.ResponseWriter, request *http.Request) server.internalError(writer, "score assessment", err) return } - catalog, err := career.DefaultCatalog() + catalog, err := career.Load(server.config.CatalogPath) if err != nil { server.internalError(writer, "load occupation catalog", err) return diff --git a/cmd/nextpath/main.go b/cmd/nextpath/main.go index d6b1726..cd72665 100644 --- a/cmd/nextpath/main.go +++ b/cmd/nextpath/main.go @@ -24,6 +24,7 @@ func main() { SecureCookies: strings.EqualFold(os.Getenv("NEXTPATH_SECURE_COOKIES"), "true"), SessionTTL: 12 * time.Hour, OpportunityStorePath: envOr("NEXTPATH_OPPORTUNITY_STORE", "./data/opportunity.json"), + CatalogPath: os.Getenv("NEXTPATH_CATALOG"), }) slog.Info("NextPath listening", "address", address) if err := http.ListenAndServe(address, server.Handler()); err != nil && !errors.Is(err, http.ErrServerClosed) { diff --git a/docs/nextpath-architecture.md b/docs/nextpath-architecture.md index 3e7ef7c..f3c7700 100644 --- a/docs/nextpath-architecture.md +++ b/docs/nextpath-architecture.md @@ -116,6 +116,24 @@ Remote source data is cached with retrieval timestamps and source attribution. Job listings are short-lived examples, are linked to their publisher, and do not become training data or evidence of guaranteed employment. +### Automated catalog expansion + +The 12 hand-reviewed careers remain regression seeds and the offline fallback, +not the production catalog ceiling. The daily Jeannie refresh automatically +builds a 75-career catalog by joining the O*NET 31.0 occupation and RIASEC +files, the official NCES CIP 2020-to-SOC 2018 crosswalk, Arizona IPEDS 2024 +program completions, and Arizona Projections Central records. A generated +career is eligible only when it has a complete interest profile, at least one +exact six-digit CIP program with Arizona completions, and positive projected +annual openings. This keeps every visible recommendation connected to the +education and labor evidence used later in the workflow. + +The NCES crosswalk is a conceptual relationship, not proof that every graduate +enters the occupation. NextPath therefore exposes mapping coverage and raw +counts instead of presenting the join as an observed placement rate. Operators +can set `LAB_NEXTPATH_CATALOG_LIMIT` from 12 through 200; the managed default is +75. + Jeannie refreshes the cache daily without credentials or prompts. It combines public IPEDS annual files, Department of Labor-sponsored Projections Central state projections, and Ayla's public feed of government and official hiring @@ -126,6 +144,11 @@ inputs; failures preserve the last successful snapshot. With no complete snapshot, the results page says the outlook is unavailable rather than presenting a synthetic percentage. +Catalog, mapping, and opportunity outputs are generated under a private systemd +runtime directory. Jeannie promotes all three persistent files only after the +entire refresh succeeds. A download, parsing, rate-limit, or evidence failure +therefore leaves the last complete catalog/evidence set in service. + ## Recommendation boundary Deterministic code performs assessment scoring, eligibility filtering, diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index e9393c3..5f4d116 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -6015,6 +6015,10 @@ nextpath_action() { local action="${1:-status}" local install_dir="${LAB_NEXTPATH_INSTALL_DIR:-/data/homelab-nextpath}" local opportunity_store="${install_dir}/data/opportunity.json" + local catalog_store="${install_dir}/data/catalog.json" + local catalog_mapping_store="${install_dir}/data/catalog-mapping.json" + local catalog_cache="${install_dir}/data/source-cache" + local catalog_limit="${LAB_NEXTPATH_CATALOG_LIMIT:-75}" require_debian_server "nextpath ${action}" case "${action}" in @@ -6062,6 +6066,10 @@ deploy_nextpath() { local backup_dir="${install_dir}/backups" local backup_timestamp="" local opportunity_store="${install_dir}/data/opportunity.json" + local catalog_store="${install_dir}/data/catalog.json" + local catalog_mapping_store="${install_dir}/data/catalog-mapping.json" + local catalog_cache="${install_dir}/data/source-cache" + local catalog_limit="${LAB_NEXTPATH_CATALOG_LIMIT:-75}" local elapsed=0 require_debian_server "deploy-nextpath" @@ -6081,6 +6089,10 @@ deploy_nextpath() { true|false) ;; *) echo "LAB_NEXTPATH_SECURE_COOKIES must be true or false." >&2; return 1 ;; esac + if ! [[ "${catalog_limit}" =~ ^[0-9]+$ ]] || ((catalog_limit < 12 || catalog_limit > 200)); then + echo "LAB_NEXTPATH_CATALOG_LIMIT must be between 12 and 200." >&2 + return 1 + fi for required in go curl systemctl python3; do if ! command -v "${required}" >/dev/null 2>&1; then echo "NextPath deployment requires ${required} on Debian." >&2 @@ -6125,8 +6137,12 @@ deploy_nextpath() { ) sudo install -o "${service_user}" -g "${service_user}" -m 0550 \ "${REPO_ROOT}/scripts/nextpath-opportunity-refresh.py" "${release_dir}/scripts/nextpath-opportunity-refresh.py" + sudo install -o "${service_user}" -g "${service_user}" -m 0550 \ + "${REPO_ROOT}/scripts/nextpath-catalog-refresh.py" "${release_dir}/scripts/nextpath-catalog-refresh.py" sudo install -o "${service_user}" -g "${service_user}" -m 0440 \ "${REPO_ROOT}/apps/nextpath/data/soc-cip-map.json" "${release_dir}/data/soc-cip-map.json" + sudo install -o "${service_user}" -g "${service_user}" -m 0440 \ + "${REPO_ROOT}/cmd/nextpath/internal/career/occupations.json" "${release_dir}/data/occupations.json" sudo -u "${service_user}" ln -sfn "${release_dir}" "${install_dir}/current" sudo tee /etc/systemd/system/nextpath-opportunity-refresh.service >/dev/null < dict[str, int]: return history +def ipeds_completion_histories(mapping: dict[str, Any], cache_dir: Path) -> dict[str, dict[str, int]]: + target_cips = {cip for spec in mapping["mappings"].values() for cip in spec["cip6"]} + by_year: dict[str, dict[str, int]] = {} + for year in IPEDS_YEARS: + directory = cached_download(f"{IPEDS_URL}/HD{year}.zip", cache_dir / f"HD{year}.zip") + completions = cached_download(f"{IPEDS_URL}/C{year}_A.zip", cache_dir / f"C{year}_A.zip") + arizona = {row["UNITID"] for row in zip_rows(directory) if row.get("STABBR") == "AZ"} + totals = {cip: 0 for cip in target_cips} + for row in zip_rows(completions): + cip = row.get("CIPCODE", "").replace(".", "") + if row.get("UNITID") not in arizona or cip not in target_cips or row.get("MAJORNUM") != "1": + continue + awards = integer(row.get("CTOTALT")) + if awards >= 0: + totals[cip] += awards + by_year[str(year)] = totals + return { + onet: {year: sum(totals.get(cip, 0) for cip in spec["cip6"]) for year, totals in by_year.items()} + for onet, spec in mapping["mappings"].items() + } + + def integer(value: Any, default: int = -1) -> int: try: return int(value) @@ -194,10 +216,20 @@ def projected_openings(body: dict[str, Any]) -> tuple[int, str, float]: return count, period.strip("-"), float(row.get("PercentChange", 0)) -def public_market_evidence(onet: str, job_query: str) -> tuple[int, str, float, int]: - soc = onet.split(".", 1)[0] - projections = get_json(f"{PROJECTIONS_CENTRAL}/04/{urllib.parse.quote(soc, safe='-')}") - openings, period, growth = projected_openings(projections) +def arizona_projections() -> dict[str, dict[str, Any]]: + rows: dict[str, dict[str, Any]] = {} + page = 0 + while True: + body = get_json(f"{PROJECTIONS_CENTRAL}/04?page={page}") + for row in body.get("rows", []): + rows[row.get("OccCode", "")] = row + if page + 1 >= int(body.get("pager", {}).get("total_pages", 1)): + return rows + page += 1 + + +def public_market_evidence(projection: dict[str, Any], job_query: str) -> tuple[int, str, float, int]: + openings, period, growth = projected_openings({"rows": [projection]}) query = urllib.parse.urlencode({ "search": job_query, "limit": 1, @@ -207,16 +239,21 @@ def public_market_evidence(onet: str, job_query: str) -> tuple[int, str, float, return openings, period, growth, int(jobs.get("pagination", {}).get("total", 0)) -def refresh(mapping_path: Path, output_path: Path) -> None: +def refresh(mapping_path: Path, output_path: Path, source_cache_root: Path | None = None) -> None: mapping = json.loads(mapping_path.read_text()) - source_cache = output_path.parent / "source-cache" / "ipeds" + source_cache = (source_cache_root or output_path.parent / "source-cache") / "ipeds" observed = datetime.now(timezone.utc) occupations: dict[str, Any] = {} education, zip_coordinates = arizona_education_options(mapping, source_cache) + histories = ipeds_completion_histories(mapping, source_cache) + projections = arizona_projections() for onet, spec in mapping["mappings"].items(): - history = ipeds_completion_history(set(spec["cip6"]), source_cache) + history = histories[onet] graduates = history[str(IPEDS_YEARS[-1])] - openings, period, growth, postings = public_market_evidence(onet, spec["job_query"]) + soc = onet.split(".", 1)[0] + if soc not in projections: + raise ValueError(f"no Arizona projection found for {onet}") + openings, period, growth, postings = public_market_evidence(projections[soc], spec["job_query"]) if graduates <= 0: raise ValueError(f"no Arizona completions found for {onet}") occupations[onet] = { @@ -263,8 +300,9 @@ def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--mapping", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--source-cache", type=Path) args = parser.parse_args() - refresh(args.mapping, args.output) + refresh(args.mapping, args.output, args.source_cache) if __name__ == "__main__": diff --git a/tests/jeannie/test_nextpath_opportunity_refresh.py b/tests/jeannie/test_nextpath_opportunity_refresh.py index db7f7c0..30eb75f 100644 --- a/tests/jeannie/test_nextpath_opportunity_refresh.py +++ b/tests/jeannie/test_nextpath_opportunity_refresh.py @@ -5,6 +5,7 @@ import pathlib import tempfile import unittest import zipfile +from unittest import mock ROOT = pathlib.Path(__file__).resolve().parents[2] @@ -54,6 +55,27 @@ class NextPathOpportunityRefreshTests(unittest.TestCase): {str(year): 103 for year in MODULE.IPEDS_YEARS}, ) + def test_ipeds_histories_scan_each_annual_export_once_for_all_careers(self): + with tempfile.TemporaryDirectory() as temporary: + cache = pathlib.Path(temporary) + for year in MODULE.IPEDS_YEARS: + self.write_zip(cache / f"HD{year}.zip", f"HD{year}.csv", ["UNITID", "STABBR"], [ + {"UNITID": "1", "STABBR": "AZ"}, + ]) + self.write_zip(cache / f"C{year}_A.zip", f"C{year}_A.csv", ["UNITID", "CIPCODE", "MAJORNUM", "CTOTALT"], [ + {"UNITID": "1", "CIPCODE": "11.0101", "MAJORNUM": "1", "CTOTALT": "10"}, + {"UNITID": "1", "CIPCODE": "15.0101", "MAJORNUM": "1", "CTOTALT": "20"}, + ]) + mapping = {"mappings": { + "15-1252.00": {"cip6": ["110101"]}, + "17-2112.00": {"cip6": ["150101"]}, + }} + with mock.patch.object(MODULE, "zip_rows", wraps=MODULE.zip_rows) as rows: + histories = MODULE.ipeds_completion_histories(mapping, cache) + self.assertEqual(histories["15-1252.00"]["2024"], 10) + self.assertEqual(histories["17-2112.00"]["2024"], 20) + self.assertEqual(rows.call_count, len(MODULE.IPEDS_YEARS) * 2) + def test_extracts_arizona_projection(self): body = {"rows": [{ "Area": "Arizona", "AvgAnnualOpenings": "1,234", "BaseYear": "2024", "ProjYear": "2034", diff --git a/tests/jeannie/test_nextpath_pipeline.py b/tests/jeannie/test_nextpath_pipeline.py index b2cd00b..39ba16c 100644 --- a/tests/jeannie/test_nextpath_pipeline.py +++ b/tests/jeannie/test_nextpath_pipeline.py @@ -16,6 +16,14 @@ class NextPathPipelineTests(unittest.TestCase): self.assertIn("GOTOOLCHAIN=local go test ./cmd/nextpath/...", pipeline) self.assertIn("NEXTPATH_ACCOUNT_STORE=${account_store}", pipeline) self.assertIn("NEXTPATH_OPPORTUNITY_STORE=${opportunity_store}", pipeline) + self.assertIn("NEXTPATH_CATALOG=${catalog_store}", pipeline) + self.assertIn("nextpath-catalog-refresh.py", pipeline) + self.assertIn("--catalog-output /run/nextpath-refresh/catalog.json", pipeline) + self.assertIn("--mapping-output /run/nextpath-refresh/catalog-mapping.json", pipeline) + self.assertIn("--source-cache ${catalog_cache}", pipeline) + self.assertIn("RuntimeDirectory=nextpath-refresh", pipeline) + self.assertIn("/run/nextpath-refresh/opportunity.json ${opportunity_store}", pipeline) + self.assertIn("LAB_NEXTPATH_CATALOG_LIMIT", pipeline) self.assertIn("nextpath-opportunity-refresh.timer", pipeline) self.assertIn("nextpath_action()", pipeline) self.assertNotIn("CareerOneStop API token", pipeline) @@ -27,6 +35,10 @@ class NextPathPipelineTests(unittest.TestCase): self.assertIn("annual_in_state_tuition", refresh) self.assertIn("institution_completion_rate_percent", refresh) self.assertIn('print(f"Arizona education options: {programs}")', pipeline) + self.assertLess( + pipeline.index("nextpath-catalog-refresh.py --seed-catalog"), + pipeline.index("nextpath-opportunity-refresh.py --mapping /run/nextpath-refresh/catalog-mapping.json"), + ) self.assertLess( pipeline.index("systemctl start nextpath-opportunity-refresh.service"), pipeline.index("systemctl restart nextpath.service"),