Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
119 commits
Select commit Hold shift + click to select a range
f4c314d
feat(librarian): Module C retrieval upgrades (stack base for #1088)
northdpole Sep 29, 2026
8368601
Address review feedback on OIE librarian base.
northdpole Oct 5, 2026
70af687
feat(harvester): requirement extract and GitHub URL ingest
northdpole Sep 29, 2026
583e987
feat(oie): B2 eval harness and CRE neighborhood scorer
northdpole Sep 29, 2026
7fe303e
feat(librarian): LLM SafetyGuard for C.4 adversarial / update flags
northdpole Oct 7, 2026
62d0c4b
Address review feedback on harvester and GitHub URL ingest.
northdpole Oct 5, 2026
25f07e1
Address review feedback on B2 harness scripts.
northdpole Oct 5, 2026
955528d
chore(oie): ASVS 5.0 provisional B2 sources and gold
northdpole Sep 29, 2026
86d320a
chore(oie): NIST 800-53 and remaining B2 sources/gold
northdpole Sep 29, 2026
62cedd4
feat(mappings): promote Related-orphan remaps into canonical fixtures
northdpole Sep 29, 2026
81faa70
Address review feedback on full-pipeline runner.
northdpole Oct 5, 2026
53562bf
feat(librarian): batch Module C query embeddings
northdpole Oct 7, 2026
657284b
fix(librarian): keep LLM SafetyGuard when restacking leaf-drilldown
northdpole Oct 7, 2026
ec9accd
fix(librarian): finish SafetyGuard + leaf-drilldown restack merge
northdpole Oct 7, 2026
e83b169
feat(oie): full-pipeline runner, docs, and experimental-flag notes
northdpole Sep 29, 2026
f180d0d
Add experimental OIE OWASP metadata agent for chat
cursoragent Oct 2, 2026
0b797a5
feat(librarian): promote d1-winner combo defaults (judge+cap8+top_k=3)
northdpole Sep 30, 2026
dfec9a8
Isolate OWASP meta concepts to chat and MCP only
cursoragent Oct 2, 2026
b3fce72
Add idempotent Alembic migration for OWASP agent meta tables.
northdpole Oct 14, 2026
a91d6e1
Fix OWASP agent probe gaps for chapters, people, membership, and CRE …
northdpole Oct 2, 2026
6953269
Add synth v2 probe suite and raise agent routing pass rate.
northdpole Oct 3, 2026
3c6bcff
Format owasp_agent modules with black for CI lint.
northdpole Oct 3, 2026
6da242e
Document OWASP agent setup, OIE relationship, and synth eval.
northdpole Oct 3, 2026
6d9eb6b
Black-format remaining owasp_agent modules for CI.
northdpole Oct 3, 2026
060e651
Answer OWASP entity chat probes from agent metadata.
northdpole Oct 12, 2026
8ce9b6c
Add multi-turn chat memory with New chat.
northdpole Oct 12, 2026
32aefc1
Harden OWASP agent routing for board, geo, CRE, and PG index.
northdpole Oct 14, 2026
e75479a
Route OWASP chat via multi-lane embedding similarity.
northdpole Oct 14, 2026
a69c0d3
Make OWASP agent meta embedding work on low-memory staging.
northdpole Oct 14, 2026
aeb2ebf
Add adversarial completion asker and align embed model ids.
northdpole Oct 14, 2026
033597b
Fix OWASP agent routing for chapter-in-city and project leaders.
northdpole Oct 14, 2026
34907f9
Treat named-chapter meetup asks as chapter lookup.
northdpole Oct 14, 2026
7a1cf7d
Reuse one Flask app in the adversarial completion asker.
northdpole Oct 14, 2026
3772492
feat(owasp-agent): sim-first retrieve with normalize, chapters, board…
northdpole Oct 15, 2026
1202fa4
fix(owasp-agent): stop substring event/chapter traps and city hardcodes
northdpole Oct 15, 2026
5369337
fix(owasp-agent): drop meta/normative keyword dump gates
northdpole Oct 15, 2026
b32ebbf
fix(owasp-agent): drop keyword dumps; derive project aliases on ingest
northdpole Oct 15, 2026
6a5867e
Fix first-run harvest: list tracked files, order-safe chunk joins, ch…
northdpole Oct 5, 2026
4d375d5
Add scheduled OIE runs: OWASP (10 min) and CRE expansion (daily)
northdpole Oct 5, 2026
643e6e1
Report the agent index target in scheduled agent_sync
northdpole Oct 5, 2026
eb95ff1
Chain oie_run Alembic revision after source_channel.
northdpole Oct 14, 2026
0994bed
Add signed-in admin showcase and Brevity bot skill.
northdpole Oct 6, 2026
080ffa8
Complete remaining admin showcase plan items.
northdpole Oct 6, 2026
c9f19de
Guard admin fetches on unmount and type the config catalog.
northdpole Oct 6, 2026
c102785
Fix mapping edit fields and lock HTTP OIE to dry-run.
northdpole Oct 6, 2026
dc8cb26
Drop unused ingest kwargs after HTTP OIE lock.
northdpole Oct 6, 2026
e2815e9
Run HTTP OIE start in a dry-run child process.
northdpole Oct 6, 2026
db09073
Add plan-required admin tests for disabled agent, pipeline errors, an…
northdpole Oct 6, 2026
a56f660
Isolate HTTP OIE on sqlite and surface failed starts.
northdpole Oct 6, 2026
1a6488a
Gate /admin on capabilities.admin and surface delete errors.
northdpole Oct 6, 2026
0690ed6
Treat failed changeset fetches as errors in admin review.
northdpole Oct 6, 2026
e8d7675
Drop restated admin-panel comments after Brevity review.
northdpole Oct 6, 2026
20f5733
Shorten admin login copy and drop restated MyOpenCRE blurb.
northdpole Oct 6, 2026
6859e05
Handle empty Impact keys with logs and JSON errors.
northdpole Oct 6, 2026
03612c2
Show impact warnings in Admin and format helpers.
northdpole Oct 6, 2026
5d77d3f
Keep stacked Nest agent env; agent DB is Postgres.
northdpole Oct 6, 2026
51c243c
Treat OWASP_AGENT_DB as Postgres only.
northdpole Oct 6, 2026
5a05310
Redact passwords in OWASP_AGENT_DB admin display.
northdpole Oct 6, 2026
5f3a6f3
Harden admin targets, ingest, and mapping errors.
northdpole Oct 6, 2026
40e16f5
Add admin repos.yaml editor, org expand, and one-off ingest.
northdpole Oct 6, 2026
84e9839
Harden repos.yaml org expand and yaml size limits.
northdpole Oct 6, 2026
3b58d49
Rebuild frontend bundle for repos.yaml admin editor.
northdpole Oct 6, 2026
c1bf1b5
Raise repos.yaml admin cap to 4MiB for org expands.
northdpole Oct 6, 2026
dce904e
Decouple repos.yaml config from GitHub org expansion.
northdpole Oct 6, 2026
c8f3298
Treat the OWASP agent as a built-in ingest resource.
northdpole Oct 6, 2026
2a4015d
Reject inaccessible GitHub sources at config time.
northdpole Oct 6, 2026
a477189
Redesign admin IA: dashboard, config, pipeline, graph.
northdpole Oct 6, 2026
bccae60
Rebuild frontend bundle for the admin IA redesign.
northdpole Oct 6, 2026
87824bc
Persist Add org on save and mark apply_failed on the strip.
northdpole Oct 6, 2026
2f0da3f
Drop OWASP_AGENT_DB; agent uses the main app Postgres.
northdpole Oct 6, 2026
9ab2499
Fix OIE child import path; agent index uses the main DB.
northdpole Oct 6, 2026
555c4e7
Run admin OIE on Docker Postgres; drop sqlite:// child cache.
northdpole Oct 6, 2026
61bfcf9
Align Flask/agent DB env order; always pin psycopg2 dialect.
northdpole Oct 6, 2026
1422dee
Make admin ingest run OIE end-to-end without false Module A errors.
northdpole Oct 6, 2026
0d372bc
Skip invalid harvest docs; surface agent last_sync from meta_entity.
northdpole Oct 6, 2026
3322ed0
Restore degraded stop contract; tighten admin ingest defaults.
northdpole Oct 6, 2026
1e5b4e5
Fix Graph management Accept/errors for empty OIE import runs.
northdpole Oct 6, 2026
f3ec363
Surface OIE skip reasons, flags, and graph path in pipeline logs.
northdpole Oct 6, 2026
3d820cb
Auto-pull CRE graph in admin-local when Postgres is empty.
northdpole Oct 6, 2026
15a4fa1
Wire Postgres admin bootstrap into make install and make dev.
northdpole Oct 6, 2026
f814150
Wire golden-set harvest and OWASP agent sync into Admin Config.
northdpole Oct 6, 2026
45eb358
Add Mac handover for admin/OIE/agent E2E validation.
northdpole Oct 6, 2026
afb0948
Chain admin panel tables migration after oie_run
northdpole Oct 6, 2026
aabb90b
Black-format admin_imports_api_test for CI
northdpole Oct 6, 2026
7871306
Run admin OIE ingest through Modules B and C by default.
northdpole Oct 7, 2026
bfcb1e4
Paint Module C auto-filed graph edges and nodes in the explorer.
northdpole Oct 7, 2026
0f22476
Add Module C.1 graph filing to the OIE A→B→C pipeline.
northdpole Oct 7, 2026
7b9b007
Default Module C.1 auto-filing off behind an admin Config toggle.
northdpole Oct 7, 2026
18ed280
Restore clarify followup test dropped in admin rebase.
northdpole Oct 12, 2026
5308183
style: format files flagged by CI (black, prettier)
northdpole Oct 22, 2026
9262fde
test: fix stale admin config assertion, env leaks between tests, and …
northdpole Oct 22, 2026
44dc468
chore(oie): trim #1088 for the staging rollout
northdpole Nov 1, 2026
692bc35
Merge remote-tracking branch 'origin/wip/oie-pipeline-eval-harness' i…
northdpole Nov 1, 2026
4074ac7
chore(harvester): trim #1115 for the staging rollout
northdpole Nov 1, 2026
1524c9f
Merge branch 'trim/1115' into trim/1116
northdpole Nov 1, 2026
f694b1c
chore(oie): trim #1116 and guard destructive eval scripts
northdpole Nov 1, 2026
71b6abd
Merge branch 'trim/1116' into trim/1117
northdpole Nov 1, 2026
866b86f
chore(oie): trim #1117 for the staging rollout
northdpole Nov 1, 2026
abe9547
Merge branch 'trim/1117' into trim/1118
northdpole Nov 1, 2026
fb4c782
chore(oie): trim #1118 for the staging rollout
northdpole Nov 1, 2026
adac09b
Merge branch 'trim/1118' into trim/1119
northdpole Nov 1, 2026
1a7c875
Merge branch 'trim/1119' into trim/1120
northdpole Nov 1, 2026
98d5c50
style: black-format llm_safety_guard.py
northdpole Nov 1, 2026
287cc1d
trim(#1120): fix merge-conflict markers, guard full pipeline, drop de…
northdpole Nov 1, 2026
b756876
Merge branch 'trim/1120' into trim/1125
northdpole Nov 1, 2026
8f1b203
Merge branch 'trim/1125' into trim/1127
northdpole Nov 1, 2026
d0e661c
trim(#1127): drop adversarial asker/batch scripts and canned CRE foll…
northdpole Nov 1, 2026
b8ecf3f
Merge branch 'trim/1127' into trim/1137
northdpole Nov 1, 2026
005ebcd
trim(#1137): drop brevity-bot skills and stale handover doc, restore …
northdpole Nov 1, 2026
769401f
refactor(owasp-agent): move the meta-embedding push out of sync_all i…
northdpole Nov 1, 2026
c9dae24
chore: drop generated frontend bundle (rebuild at deploy)
northdpole Nov 1, 2026
b07a6d9
chore(owasp-agent): type embed_sync and its test
northdpole Nov 1, 2026
d86f12f
Merge branch 'trim/1127' into trim/1137
northdpole Nov 1, 2026
81fae82
fix(owasp-agent): admin sync and scheduler stage apply the opt-in met…
northdpole Nov 1, 2026
cf93371
test(owasp-agent): sync and concepts must not import application.data…
northdpole Nov 1, 2026
f1c5640
Merge branch 'trim/1127' into trim/1137
northdpole Nov 1, 2026
823027a
test(owasp-agent): restore the environment with a plain helper instea…
northdpole Nov 1, 2026
da23c54
Merge branch 'trim/1127' into trim/1137
northdpole Nov 1, 2026
ad96712
test(owasp-agent): exercise the meta-embedding push through injected …
northdpole Nov 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
34 changes: 32 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
# Never commit your real `.env` file to version control.
# ------------------------------------------------------------------------------
# Database
# Local Docker (make docker-postgres / make admin-local):
# postgresql://cre:password@127.0.0.1:5432/cre
# `make admin-local` starts that container when the URL is unreachable and
# never falls back to SQLite for the admin showcase.

DEV_DATABASE_URL=postgresql://user:password@localhost:5432/opencre

Expand Down Expand Up @@ -41,6 +45,21 @@ CRE_ENABLE_MYOPENCRE=false

CRE_ENABLE_LOGIN=false

# Experimental OIE OWASP metadata agent (chat + MCP only — never CRE graph UI).
# Off by default. Uses the main app Postgres (DEV_DATABASE_URL / DATABASE_URL)
# for the agent index + pgvector. Reachable from /completion and MCP owasp_meta_* tools.
OWASP_AGENT_ENABLED=false

# Module C.1 graph filing (Automatically linked to). Off by default — leave Module C
# decisions in decision_queue for review; set true to auto-add high-confidence links.
OIE_GRAPH_FILING_ENABLED=false

# Nest REST API key (https://nest.owasp.org — create via GraphQL while logged in)
NEST_API_KEY=
NEST_API_BASE=https://nest.owasp.org/api/v0
# Set to 1 to crawl all www-chapter / www-project repos during sync (slow).
OWASP_AGENT_CRAWL_REPOS=0

# Embeddings

NO_GEN_EMBEDDINGS=false
Expand All @@ -52,14 +71,25 @@ GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_SECRET_JSON=path/to/secret.json
LOGIN_ALLOWED_DOMAINS=example.com

# GCP
# GCP / Gemini (optional — any LiteLLM provider works for Module B)

GCP_NATIVE=false
GEMINI_API_KEY=your-gemini-api-key
VERTEX_CHAT_MODEL=gemini-2.5-flash
VERTEX_EMBED_CONTENT_MODEL=gemini-embedding-001

# Noise / Relevance Filter (Module B)
# Other chat providers (LiteLLM). Set the key that matches CRE_NOISE_FILTER_LLM_MODEL.
# OPENAI_API_KEY=sk-...
# ANTHROPIC_API_KEY=sk-ant-...
# GROQ_API_KEY=gsk_...
# MISTRAL_API_KEY=...
# OPENROUTER_API_KEY=...

# Noise / Relevance Filter (Module B) — LiteLLM model id (provider/model)
# Examples: gemini/gemini-2.5-flash-lite | openai/gpt-4o-mini |
# anthropic/claude-haiku-4-5 | groq/llama-3.3-70b-versatile
# Any chat model LiteLLM supports; mid-size models usually work best
# (cheap + reliable for this classify gate — avoid tiny completion stubs).

CRE_NOISE_FILTER_LLM_MODEL=gemini/gemini-2.5-flash-lite
CRE_NOISE_FILTER_BATCH_SIZE=10
Expand Down
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,16 @@ standards_cache.sqlite
!docs/Mid_eval_blog_gsoc2026/module_B_mideval_blog.md
!docs/Final_eval_blog_gsoc2026/module_B_final_blog.md
!application/utils/librarian/README.md
!application/utils/owasp_agent/README.md
!docs/gsoc_2026_module_c/*.md
!docs/gsoc_2026_module_a/*.md
!docs/Final_eval_blog_gsoc2026/*.md
!docs/gsoc_2026_module_b/module_a_contract.md
!docs/gsoc_2026_module_b/module_c_contract.md
!docs/gsoc_2026_module_b/module_b_runbook.md
!docs/gsoc_2026_module_b/final_metrics.md
!docs/oie/*.md
!scripts/oie_owasp_eval/experiments/*.md

### Dev DBDumps
*.sql
Expand All @@ -91,6 +94,8 @@ neo4j/
.mypy_cache
tmp/

import_telemetry.json

### CREs dir
cres/*
### Local project management tooling
Expand Down
79 changes: 72 additions & 7 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
.ONESHELL:

.PHONY: run test covers install-deps dev docker lint frontend clean all e2e e2e-db
.PHONY: run test covers install-deps dev dev-flask docker lint frontend clean all e2e e2e-db admin-local owasp-agent-sync owasp-agent-merge-concepts owasp-agent-synth-eval

prod-run:
gunicorn cre:app --log-file=-
Expand Down Expand Up @@ -74,11 +74,19 @@ start-worker:
. ./venv/bin/activate && FLASK_APP=`pwd`/cre.py python cre.py --start_worker

upstream-sync:
. ./venv/bin/activate && python cre.py --upstream_sync
. ./venv/bin/activate &&\
python cre.py --upstream_sync --cache_file "$(or $(DEV_DATABASE_URL),$(CRE_CACHE_FILE),$(CURDIR)/standards_cache.sqlite)"

PORT?=5000

dev-flask:
# Local app against Docker Postgres: migrate, upstream-sync if cre/node empty, Flask.
# Same entrypoint as admin showcase / OIE local (no SQLite). macOS AirPlay often
# holds :5000 — use PORT=5001 make dev if bind fails.
dev dev-flask admin-local:
bash ./scripts/run_admin_local.sh --port $(PORT) $(ADMIN_LOCAL_ARGS)

# Bare Flask without Postgres bootstrap (legacy / CI helpers). Prefer `make dev`.
dev-flask-sqlite:
. ./venv/bin/activate && INSECURE_REQUESTS=1 FLASK_APP=`pwd`/cre.py FLASK_CONFIG=development flask run --port $(PORT)

dev-flask-docker:
Expand Down Expand Up @@ -136,15 +144,28 @@ install-deps-typescript:
install-deps: install-deps-python install-deps-typescript

install-python:
virtualenv -p python3 venv
@if [ ! -d "./venv" ]; then \
if command -v virtualenv >/dev/null 2>&1; then \
virtualenv -p python3 venv; \
else \
echo "virtualenv not on PATH — using python3 -m venv"; \
python3 -m venv venv; \
fi; \
fi
. ./venv/bin/activate &&\
make install-deps-python &&\
playwright install # Python embeddings/scraping (prompt_client); NOT frontend e2e — keep when migrating to Cypress

install-typescript:
yarn add webpack && cd application/frontend && yarn build
# Yarn install only. Do not `yarn add` or `yarn build` here: webpack is
# already in package.json, and a local build rewrites
# application/frontend/www/bundle.js (tracked so Heroku can serve the UI
# without a Node compile step). That was dirtying contributor trees after
# `make install`. Rebuild with `make frontend` when you change the UI.
install-typescript: install-deps-typescript

install: install-typescript install-python migrate-upgrade
# Deps + Docker Postgres schema + CRE upstream graph when empty (see run_admin_local.sh).
install: install-typescript install-python
bash ./scripts/run_admin_local.sh --migrate-only $(ADMIN_LOCAL_ARGS)

docker-dev:
docker build -f Dockerfile-dev -t opencre-dev:$(shell git rev-parse HEAD) .
Expand Down Expand Up @@ -185,10 +206,39 @@ oie-pipeline:
[ -d "./venv" ] && . ./venv/bin/activate &&\
PYTHONPATH=. python scripts/run_oie_pipeline.py --cache_file "$(or $(CACHE_FILE),sqlite:///$(CURDIR)/standards_cache.sqlite)" $(OIE_ARGS)

# Deterministic OIE base metadata (Node then CRE document_metadata.oie). Fill-if-missing.
# Example:
# make oie-tag-base CACHE_FILE=postgresql://cre:password@127.0.0.1:5432/cre_prodclone
oie-tag-base:
[ -d "./venv" ] && . ./venv/bin/activate &&\
PYTHONPATH=. python scripts/oie_ensure_base_metadata.py \
--cache-file "$(or $(CACHE_FILE),$(or $(DEV_DATABASE_URL),postgresql://cre:password@127.0.0.1:5432/cre))" \
$(OIE_TAG_ARGS)

# Local OIE bootstrap: start cre-postgres, migrate, sync CRE hub (local|upstream).
# Examples:
# make setup-oie
# make setup-oie SETUP_OIE_ARGS='--source upstream --install-ml --calibrate'
setup-oie:
bash ./scripts/setup_oie.sh $(SETUP_OIE_ARGS)

oie-e2e-smoke:
[ -d "./venv" ] && . ./venv/bin/activate &&\
PYTHONPATH=. python scripts/run_oie_e2e_smoke.py

owasp-agent-sync:
[ -d "./venv" ] && . ./venv/bin/activate &&\
PYTHONPATH=. python scripts/owasp_agent_sync.py $(OWASP_AGENT_SYNC_ARGS)

owasp-agent-merge-concepts:
[ -d "./venv" ] && . ./venv/bin/activate &&\
PYTHONPATH=. python scripts/owasp_agent_merge_concepts.py $(OWASP_AGENT_MERGE_ARGS)

# Score fixtures/owasp_agent_synth_v2.jsonl against OWASP_AGENT_DB (see application/utils/owasp_agent/README.md).
owasp-agent-synth-eval:
[ -d "./venv" ] && . ./venv/bin/activate &&\
OWASP_AGENT_ENABLED=1 PYTHONPATH=. python scripts/owasp_agent_synth_eval.py

openapi-generate:
[ -d "./venv" ] && . ./venv/bin/activate &&\
python scripts/generate_openapi.py
Expand Down Expand Up @@ -240,6 +290,21 @@ monitor-chatbot-health-prod:
--base-url "https://opencre.org" \
--output-json "$(CURDIR)/tmp/prod-chatbot-health.json"

# Scheduled OIE jobs (Postgres only). Cron `make oie-tick` every 10 minutes: each
# job runs once per slot (owasp every 10 min, cre_expansion daily) and is a no-op
# otherwise. Overrides: OIE_JOB=owasp|cre_expansion|all, OIE_FORCE=1, OIE_DRY_RUN=1.
oie-tick:
@[ -d "./.venv" ] && . ./.venv/bin/activate || ([ -d "./venv" ] && . ./venv/bin/activate); \
export CRE_CACHE_FILE="$${CRE_CACHE_FILE:-postgresql://cre:password@127.0.0.1:5432/cre}"; \
python cre.py --cache_file "$$CRE_CACHE_FILE" --run_scheduled "$${OIE_JOB:-all}" \
$${OIE_FORCE:+--scheduled_force} $${OIE_DRY_RUN:+--scheduled_dry_run}

monitor-oie-health:
@[ -d "./.venv" ] && . ./.venv/bin/activate || ([ -d "./venv" ] && . ./venv/bin/activate); \
export CRE_CACHE_FILE="$${CRE_CACHE_FILE:-postgresql://cre:password@127.0.0.1:5432/cre}"; \
export PYTHONPATH="$(CURDIR)"; \
python scripts/monitor_oie_health.py --output-json "$(CURDIR)/tmp/oie-health.json"

verify-ga-parity-local:
@[ -d "./.venv" ] && . ./.venv/bin/activate || ([ -d "./venv" ] && . ./venv/bin/activate); \
export CRE_CACHE_FILE="$${CRE_CACHE_FILE:-postgresql://cre:password@127.0.0.1:5432/cre}"; \
Expand Down
47 changes: 47 additions & 0 deletions application/cmd/cre_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,39 @@ def backfill_gap_analysis_only(
logger.info("GA backfill complete: final_missing_pairs=%s", final_missing)


def run_scheduled_cli(args: argparse.Namespace, collection: db.Node_collection) -> int:
"""``--run_scheduled``: run the selected OIE job(s); return a process exit code.

Postgres only -- the advisory-lock lease and the run table assume it, and the
default ``standards_cache.sqlite`` must not silently become the scheduler's
database. Exit 1 when a job errored, 2 for a non-Postgres database.
"""
import json

from application.utils.oie_scheduler.runner import run_due_jobs

dialect = collection.session.get_bind().dialect.name
if dialect != "postgresql":
logger.error(
"--run_scheduled is Postgres-only (got %s); point --cache_file at "
"a postgresql:// URL (make docker-postgres for a local one)",
dialect,
)
return 2
selected = args.run_scheduled
force = bool(getattr(args, "scheduled_force", False))
outcomes = run_due_jobs(
collection,
cache_file=args.cache_file,
jobs=None if selected == "all" else [selected],
force=force,
dry_run=bool(getattr(args, "scheduled_dry_run", False)),
trigger="manual" if force else "scheduled",
)
print(json.dumps([o.to_dict() for o in outcomes], indent=2))
return 1 if any(o.failed for o in outcomes) else 0


def run(args: argparse.Namespace) -> None: # pragma: no cover
script_path = os.path.dirname(os.path.realpath(__file__))
os.path.join(script_path, "../cres")
Expand All @@ -892,6 +925,14 @@ def run(args: argparse.Namespace) -> None: # pragma: no cover
logger.info("Exported %s rows to %s", rows, csv_out)
return

if getattr(args, "run_scheduled", ""):
import sys

code = run_scheduled_cli(args, db_connect(args.cache_file))
if code:
sys.exit(code)
return

if getattr(args, "run_harvester", False):
import sys

Expand All @@ -905,6 +946,12 @@ def run(args: argparse.Namespace) -> None: # pragma: no cover
args.run_id.strip(),
repos_yaml=repos_yaml,
dry_run=getattr(args, "harvester_dry_run", False),
kinds=[
k.strip()
for k in (getattr(args, "harvester_kinds", "") or "").split(",")
if k.strip()
]
or None,
)
print(summary.to_json())
if summary.status == "degraded":
Expand Down
40 changes: 31 additions & 9 deletions application/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,30 @@

import os

from application.utils.postgres_url import (
is_postgres_url,
main_db_env_keys,
sqlalchemy_postgres_url,
)

basedir = os.path.abspath(os.path.dirname(__file__))


def _sqlalchemy_uri_from_env(raw: str) -> str:
"""Bind Postgres env URLs to psycopg2; leave sqlite and other schemes alone."""
if is_postgres_url(raw):
return sqlalchemy_postgres_url(raw)
return raw


def _first_env_url(*keys: str) -> str:
for key in keys:
raw = (os.environ.get(key) or "").strip()
if raw:
return raw
return ""


class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_RECORD_QUERIES = False
Expand All @@ -18,8 +39,8 @@ class DevelopmentConfig(Config):
DEBUG = True
ENVIRONMENT = "DEVELOPMENT"
CACHE_TYPE = "SimpleCache"
SQLALCHEMY_DATABASE_URI = (
os.environ.get("DEV_DATABASE_URL")
SQLALCHEMY_DATABASE_URI = _sqlalchemy_uri_from_env(
_first_env_url(*main_db_env_keys("development"))
or f'sqlite:///{os.path.join(basedir, "../standards_cache.sqlite")}'
)

Expand All @@ -35,8 +56,8 @@ class ProductionConfig(Config):
ENVIRONMENT = "PRODUCTION"
CACHE_TYPE = "SimpleCache"
CACHE_DEFAULT_TIMEOUT = 3000
SQLALCHEMY_DATABASE_URI = (
os.environ.get("PROD_DATABASE_URL")
SQLALCHEMY_DATABASE_URI = _sqlalchemy_uri_from_env(
_first_env_url(*main_db_env_keys("production"))
or f'sqlite:///{os.path.join(basedir, "../standards_cache.sqlite")}'
)

Expand All @@ -46,11 +67,12 @@ class CMDConfig(Config):

def __init__(self, db_uri: str):
if "://" in db_uri:
# Heroku and some tools still emit ``postgres://``; SQLAlchemy 2 expects
# ``postgresql://`` for the psycopg dialect name.
if db_uri.startswith("postgres://"):
db_uri = "postgresql://" + db_uri[len("postgres://") :]
self.SQLALCHEMY_DATABASE_URI = db_uri
# Heroku still emits ``postgres://``; SQLAlchemy 2.1 maps bare
# ``postgresql://`` to psycopg v3 — pin psycopg2 (requirements.txt).
if is_postgres_url(db_uri):
self.SQLALCHEMY_DATABASE_URI = sqlalchemy_postgres_url(db_uri)
else:
self.SQLALCHEMY_DATABASE_URI = db_uri
else:
# Flask-SQLAlchemy 3+ resolves non-absolute sqlite URLs against
# app.instance_path, not the shell cwd. CLI --cache_file should
Expand Down
Loading
Loading