feat(ai): bulk AI jobs, SBOM analysis, ASVS assessment, and security digest #69
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/ai-advice-job"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Builds on the AI layer from #67. Everything is off until AI is enabled in System Settings → AI, and nothing the model returns changes a record without a
person acting on it.
Features
SBOM analysis (Components page of a product, deep tier)
ASVS assessment (Benchmark page, deep tier)
Security digest (AI settings, fast tier)
Bulk jobs (AI settings)
product.
Token efficiency
Reliability
batch.
so advice or analysis someone regenerated in the meantime is kept.
the transaction was open.
API
GET/POST /ai/products/{id}/{sbom|benchmark}(writer on the product to generate;?force=trueto regenerate)POST /ai/products/{id}/benchmark/apply{categories: [...]}GET/POST /ai/digests(admin)GET/POST /ai/jobs,GET /ai/jobs/estimate,GET /ai/jobs/{id},POST /ai/jobs/{id}/cancel(admin;kind=finding_advice,sbom_analysisorbenchmark)advice_job_schedule,advice_job_min_severity,sbom_job_schedule,benchmark_job_schedule,digest_schedule,digest_slackThe database migrates automatically:
ai_jobs,product_analysesandai_digestsare new, andai_settingsandai_usagesget new columns.Testing
go build,go vetandgo test ./...pass; the AI package also passes under-raceon repeated runs.and benchmark prompts, apply validation and org scoping, and the digest (quiet periods, alerts to owners/admins only, Slack delivery, no double-send).
npm run lintandnpm run buildpass.ojoreports no vulnerabilities.Adds a job in System Settings -> AI that generates advice for every active finding at or above a chosen severity, on demand or daily/weekly. Findings that are mitigated, duplicates, false positives, risk accepted or out of scope are excluded, and findings whose advice is still current are skipped. - Anthropic runs go through the Message Batches API (half price); other providers run with two workers through the normal tier routing - the monthly token limit is applied up front, keeping the most severe findings; an estimate is shown before running - queued findings keep their earlier advice visible; a result is written only if the row is still queued under the job, so advice regenerated by hand in the meantime wins - jobs hold a database lease with a heartbeat; every replica runs the scheduler, which resumes jobs whose runner died (including waiting on a submitted batch) and starts scheduled runs under a settings-row lock - batch requests are recorded in ai_usages with batch=true - a failed usage write is logged instead of discarding a paid-for response Endpoints (admin): GET/POST /ai/jobs, GET /ai/jobs/estimate, GET /ai/jobs/{id}, POST /ai/jobs/{id}/cancel; settings gain advice_job_schedule and advice_job_min_severity.SBOM analysis (deep tier, per product): a prioritized upgrade plan grouped by package, license issues and overall dependency risk, built from the product's vulnerable components (grouped by package and version), license violations and ecosystem counts. Shown on the product's Components page. ASVS assessment (deep tier, per product): a suggested level for each of V1-V14 with rationale, gaps and evidence, from open findings grouped by CWE and the current benchmark. Shown on the Benchmark page; levels change only when a writer applies selected chapters. Security digest (fast tier): what changed since the last digest (new and fixed findings, riskiest products, expiring risk acceptances, SBOM changes), sent to owners and admins as alerts and optionally posted to the org-wide Slack configurations. Quiet periods skip the model; scheduled sends are claimed under the settings-row lock so replicas don't duplicate. Bulk jobs are now generic over a per-kind spec (finding_advice, sbom_analysis, benchmark), each with its own daily/weekly schedule in the AI settings, reusing the batch API, leases and resume logic. Analyses are reused when the product's input is unchanged and flagged stale otherwise. The limit check in advice and analysis starts now runs before their transaction (it read through a second connection inside it). Endpoints: GET/POST /ai/products/{id}/{sbom|benchmark}, POST /ai/products/{id}/benchmark/apply, GET/POST /ai/digests; /ai/jobs and /ai/jobs/estimate take a kind. Settings gain sbom_job_schedule, benchmark_job_schedule, digest_schedule and digest_slack.🔎 ojo scan results
No findings.
Codecov Results 📊
✅ Patch coverage is 100.00%. Project has 5549 uncovered lines.
Generated by Codecov Action
Summary
This PR builds on the AI layer from #67 and adds four things:
ProductAnalysis): an SBOM upgrade plan, and an ASVS assessment that a writer can apply.The last commit (
b13f3d7) addresses an earlier review. It adds restoring previous results throughprev_status/prev_input_hash, digest statuses, Slack escaping and webhook-URL redaction, and batch chunking. The code matches the title and most of the description. Two parts don't hold up: the "aggregates only" claim about what is sent to the model (Finding 4), and the ASVS bullet in the description, which repeats the SBOM line ("vulnerable components grouped by package…") instead of describing the CWE-grouped input.Findings
Blocking — a batch job can poll forever and block that job kind for the org.
internal/ai/job.go:504-535:awaitBatchesonly leaves its loop when every batch reports ended. WhenBatchEndedreturns an error, the code logs it and keeps polling.CancelBatch, which fails the same way, and the loop keeps waiting. Because only one job per kind runs per org, that kind is blocked until someone edits the database.finish(..., AIJobError, …)soreleaserestores the queued rows. Add a test with afakeBatchwhoseBatchEndedalways errors.Should fix — resuming during results processing records usage twice and pushes progress past 100%. Job resume (
job.go:347) andstore(job.go:410-444) don't account for results the dead replica already stored.queued, sostoretreats them as superseded (:430). TheAIUsagerow is created before that check (:421), so each of these results is recorded a second time. That inflatesMonthTokensand can trip the monthly limit early.job.Completedis not reset on resume, soCompleted++(:444) can exceedTotal.job_idcolumn onAIUsagewith a unique index or an existence check. On resume, recomputeCompleted/Failedinstead of adding to the stored counts.Should fix — panics in worker goroutines are not recovered. The
recoveratjob.go:301only covers the goroutine runningrunJob. A panic in the sequential workers (job.go:569, which callcomplete,storeandspec.updates) or inkeepLeasestill crashes the process. The resumed job would then crash each replica that takes it over, which is exactly what commitb13f3d7says can no longer happen. Fix: adddefer recover()in each worker goroutine and callhalt()with the error.Should fix — the docs say only aggregates are sent, but the prompts include free text.
README.md:179and the PR description say product analyses send "aggregates, not raw data". The prompts actually include:internal/ai/analysis.go:146) and as the example title per CWE group (:263):163):291):277)On a self-hosted system, admins rely on this text to decide whether to enable a cloud provider. Either document exactly which fields are sent, or drop the free-text fields.
Nit — Apply can break the frontend when nothing was applied.
ApplyBenchmarkreturns{"applied": null}when nothing matched (analysis.go:450,var applied []string). The UI lets a writer select any category the model returned, including ones with an invalid level.ProductAnalysisPanel.tsx:132then fails onres.applied.length. Fix: initialise withapplied := []string{}.Nit —
AIUsage.Batchhas no default.internal/models/ai.go:81has nogorm:"default:false"tag, althoughb13f3d7says "ai_usages.batch/tier get defaults for existing rows". OnlyTiergot one. On PostgreSQL, AutoMigrate adds a nullable column, so existing rows hold NULL and won't matchbatch = false.Nit — scheduled digests block the scheduler.
job.go:667: the scheduler callsSendDigestsynchronously, and a model call can take up to 10 minutes. With several orgs this delaysresumeOrphansand other orgs' scheduled runs. Run it throughs.async.Nit — job-runner queries look up rows by ID alone.
heartbeat(job.go:191) andstopReason(job.go:223) use only the job ID. This is commented as deliberate, butr.job.OrganizationIDis already available, and addingorganization_id = ?costs nothing and followsAGENTS.md. The cross-org queries inresumeOrphans/startScheduledare unavoidable and documented.Nit — frontend permission check differs from the backend.
web/src/pages/Benchmark.tsx:46andProductComponents.tsx:36decidewritablefrom the org role (canWrite(me?.role)). The backend usesEffectiveRole, so a product-member writer who is an org reader is allowed by the API but sees no Analyze/Apply buttons. The pages already worked this way before this PR.Things I checked that are fine:
organization_id, including the advice/analysis joins and the digest joins throughfindings.BatchIDs,Runner,HeartbeatAt,InputHashandPrev*are all taggedjson:"-".SecretBox. The URL is removed from*url.Errorbefore it is stored, andapiErrordoesn't include it.adminmiddleware orEffectiveRole(...).AtLeast(RoleWriter).SubmitBatchcarries over model, system, messages, output config (effort and schema) and fallbacks.Completeness
AIJob,ProductAnalysisandAIDigestare registered inAllModels(). TheBatchdefault is missing (Finding 6).AIJobsPanelandProductAnalysisPanelhave none.web/hasvitestconfigured but no test files at all, so this gap predates the PR.api/openapi.yamlcovers all the new endpoints and settings. Response bodies are described only in prose, consistent with the rest of the spec.README.mdandSTATUS.mdare updated, andSTATUS.mdlists the known gaps (soft cap, the submit-to-save window). The "aggregates" wording needs correcting (Finding 4), and the PR description's ASVS bullet is copy-pasted from the SBOM one.CI and comments
codecov/patch: success (100.00% ≥ 80%)codecov/project: success (54.97%, no base report)security-scan: successtest / go: successtest / web: successtest / coverage-badge: skippedawaitBatches). I couldn't confirm which files Codecov counts.comments.jsoncontains only the two bot comments. The review thatb13f3d7responds to isn't in the file, so I can't confirm every requested change was made. Of the fixes that commit claims, I found all of them in the code except theai_usages.batchdefault (Finding 6). The panic-recovery fix only covers part of the job (Finding 3).Recommendations
Before merging:
keepLease(Finding 3).applied := []string{}(Finding 5) andgorm:"default:false"onAIUsage.Batch(Finding 6).Can wait:
writable(Finding 9).ErrBusywhile jobs run.Verdict
Merge after fixes — a batch job whose polling keeps failing never finishes and can't be cancelled, so that job kind stays blocked for the org.
Claude code review of
b13f3d7813· claude-opus-5-5