feat(ai): bulk AI jobs, SBOM analysis, ASVS assessment, and security digest #69

Merged
james merged 3 commits from feat/ai-advice-job into main 2026-11-20 01:01:13 +00:00
Owner

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)

  • Prioritized upgrade plan grouped by package: current → target version, advisories fixed, priority (now/soon/later) and risk of breaking changes.
  • Also lists license issues and gives an overall dependency risk level.
  • Sends aggregates only: vulnerable components grouped by package and version (max 150 groups), license violations and component counts per ecosystem.

ASVS assessment (Benchmark page, deep tier)

  • Suggested level for each chapter V1–V14, with confidence, rationale, gaps and evidence.
  • Built from open findings grouped by CWE and severity (max 60 groups) plus the current benchmark.
  • Levels change only when a writer selects chapters and clicks Apply.
  • Sends aggregates only: vulnerable components grouped by package and version (max 150 groups), license violations and component counts per ecosystem.

Security digest (AI settings, fast tier)

  • Covers what changed since the last digest: new and fixed findings, riskiest products, expiring risk acceptances and SBOM changes.
  • Sent to owners and admins as in-app alerts, and optionally posted to org-wide Slack configurations.
  • Runs daily, weekly or on demand. Quiet periods are recorded without calling the model.

Bulk jobs (AI settings)

  • Three kinds: mitigation advice for every active finding at or above a severity, SBOM analysis for every product, and ASVS assessment for every
    product.
  • Each kind has its own daily/weekly schedule, an estimate before running, progress and a cancel button.

Token efficiency

  • Anything whose result is still current is skipped, so repeat runs only pay for what changed.
  • On Anthropic, jobs use the Message Batches API at half price; other providers run two requests at a time.
  • With a monthly token limit, the advice job keeps the most severe findings that fit and reports how many were left out.
  • Mitigated, duplicate, false-positive, risk-accepted and out-of-scope findings are excluded.

Reliability

  • Jobs hold a database lease renewed every minute. If the replica running a job dies, another takes it over, including waiting on an already submitted
    batch.
  • Job starts and scheduled digests are claimed under a lock on the org's AI settings row, so two replicas can't both start the same run.
  • Rows waiting in a job are marked queued and keep their earlier text visible. A job result is written only if the row is still queued under that job,
    so advice or analysis someone regenerated in the meantime is kept.
  • A failed usage-log write is logged instead of throwing away a response that was already paid for.
  • The token-limit check for advice and analysis starts now runs before their database transaction; it previously read through a second connection while
    the transaction was open.

API

  • GET/POST /ai/products/{id}/{sbom|benchmark} (writer on the product to generate; ?force=true to 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_analysis or
    benchmark)
  • New settings: advice_job_schedule, advice_job_min_severity, sbom_job_schedule, benchmark_job_schedule, digest_schedule, digest_slack

The database migrates automatically: ai_jobs, product_analyses and ai_digests are new, and ai_settings and ai_usages get new columns.

Testing

  • go build, go vet and go test ./... pass; the AI package also passes under -race on repeated runs.
  • Tests cover: batch and sequential jobs, token-limit trimming, superseded results, cancel, resuming an orphaned batch, one job per org, schedules, SBOM
    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 lint and npm run build pass.
  • ojo reports no vulnerabilities.
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) - Prioritized upgrade plan grouped by package: current → target version, advisories fixed, priority (now/soon/later) and risk of breaking changes. - Also lists license issues and gives an overall dependency risk level. - Sends aggregates only: vulnerable components grouped by package and version (max 150 groups), license violations and component counts per ecosystem. **ASVS assessment** (Benchmark page, deep tier) - Suggested level for each chapter V1–V14, with confidence, rationale, gaps and evidence. - Built from open findings grouped by CWE and severity (max 60 groups) plus the current benchmark. - Levels change only when a writer selects chapters and clicks Apply. - Sends aggregates only: vulnerable components grouped by package and version (max 150 groups), license violations and component counts per ecosystem. **Security digest** (AI settings, fast tier) - Covers what changed since the last digest: new and fixed findings, riskiest products, expiring risk acceptances and SBOM changes. - Sent to owners and admins as in-app alerts, and optionally posted to org-wide Slack configurations. - Runs daily, weekly or on demand. Quiet periods are recorded without calling the model. **Bulk jobs** (AI settings) - Three kinds: mitigation advice for every active finding at or above a severity, SBOM analysis for every product, and ASVS assessment for every product. - Each kind has its own daily/weekly schedule, an estimate before running, progress and a cancel button. ## Token efficiency - Anything whose result is still current is skipped, so repeat runs only pay for what changed. - On Anthropic, jobs use the Message Batches API at half price; other providers run two requests at a time. - With a monthly token limit, the advice job keeps the most severe findings that fit and reports how many were left out. - Mitigated, duplicate, false-positive, risk-accepted and out-of-scope findings are excluded. ## Reliability - Jobs hold a database lease renewed every minute. If the replica running a job dies, another takes it over, including waiting on an already submitted batch. - Job starts and scheduled digests are claimed under a lock on the org's AI settings row, so two replicas can't both start the same run. - Rows waiting in a job are marked queued and keep their earlier text visible. A job result is written only if the row is still queued under that job, so advice or analysis someone regenerated in the meantime is kept. - A failed usage-log write is logged instead of throwing away a response that was already paid for. - The token-limit check for advice and analysis starts now runs before their database transaction; it previously read through a second connection while the transaction was open. ## API - `GET/POST /ai/products/{id}/{sbom|benchmark}` (writer on the product to generate; `?force=true` to 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_analysis` or `benchmark`) - New settings: `advice_job_schedule`, `advice_job_min_severity`, `sbom_job_schedule`, `benchmark_job_schedule`, `digest_schedule`, `digest_slack` The database migrates automatically: `ai_jobs`, `product_analyses` and `ai_digests` are new, and `ai_settings` and `ai_usages` get new columns. ## Testing - `go build`, `go vet` and `go test ./...` pass; the AI package also passes under `-race` on repeated runs. - Tests cover: batch and sequential jobs, token-limit trimming, superseded results, cancel, resuming an orphaned batch, one job per org, schedules, SBOM 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 lint` and `npm run build` pass. - `ojo` reports 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.
feat(ai): SBOM analysis, ASVS assessment, and security digest
All checks were successful
test / web (pull_request) Successful in 1m18s
codecov/project 53.51% (No base report)
codecov/patch 100.00% >= target 80%
security-scan / security-scan (pull_request) Successful in 36s
test / coverage-badge (pull_request) Has been skipped
test / go (pull_request) Successful in 4m11s
claude-review / review (pull_request) Successful in 7m51s
3cc7d8fe79
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.

<!-- ojo-scan-summary --> ### 🔎 ojo scan results No findings.

Codecov Results 📊

✅ Patch coverage is 100.00%. Project has 5549 uncovered lines.


Generated by Codecov Action

<!-- codecov-action-results --> ## Codecov Results 📊 :white_check_mark: Patch coverage is **100.00%**. Project has **5549** uncovered lines. --- *Generated by [Codecov Action](https://github.com/getsentry/codecov-action)*

Summary

This PR builds on the AI layer from #67 and adds four things:

  • Bulk AI jobs of three kinds: finding advice, SBOM analysis and ASVS benchmark. On Anthropic they go through the Message Batches API; other providers run sequentially. Jobs hold a database lease, can resume on another replica and can be cancelled.
  • Per-product analyses (ProductAnalysis): an SBOM upgrade plan, and an ASVS assessment that a writer can apply.
  • An AI security digest, sent as in-app alerts and optionally to Slack.
  • Schedules for the jobs and the digest.

The last commit (b13f3d7) addresses an earlier review. It adds restoring previous results through prev_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

  1. Blocking — a batch job can poll forever and block that job kind for the org. internal/ai/job.go:504-535: awaitBatches only leaves its loop when every batch reports ended. When BatchEnded returns an error, the code logs it and keeps polling.

    • When it happens: the batch can't be found or read under the current key. For example, an admin replaces the Anthropic key with one from another workspace (a resumed job builds its provider from the current key), or the key is revoked.
    • What goes wrong: the poll returns 404/401 on every attempt, and the heartbeat keeps renewing the lease.
    • Why it can't be stopped: cancelling or disabling AI only calls 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.
    • Fix: once a stop has been requested and the cancel attempted, or after N consecutive poll errors, or after a deadline (for example 25h after the batch was submitted), stop waiting. Then call finish(..., AIJobError, …) so release restores the queued rows. Add a test with a fakeBatch whose BatchEnded always errors.
  2. Should fix — resuming during results processing records usage twice and pushes progress past 100%. Job resume (job.go:347) and store (job.go:410-444) don't account for results the dead replica already stored.

    • Double usage: when a replica dies part-way through storing a batch's results, the replica that resumes re-reads all of them. The rows already written are no longer queued, so store treats them as superseded (:430). The AIUsage row is created before that check (:421), so each of these results is recorded a second time. That inflates MonthTokens and can trip the monthly limit early.
    • Progress: job.Completed is not reset on resume, so Completed++ (:444) can exceed Total.
    • Fix: make the batch usage write idempotent per (job, subject), for example a job_id column on AIUsage with a unique index or an existence check. On resume, recompute Completed/Failed instead of adding to the stored counts.
  3. Should fix — panics in worker goroutines are not recovered. The recover at job.go:301 only covers the goroutine running runJob. A panic in the sequential workers (job.go:569, which call complete, store and spec.updates) or in keepLease still crashes the process. The resumed job would then crash each replica that takes it over, which is exactly what commit b13f3d7 says can no longer happen. Fix: add defer recover() in each worker goroutine and call halt() with the error.

  4. Should fix — the docs say only aggregates are sent, but the prompts include free text. README.md:179 and the PR description say product analyses send "aggregates, not raw data". The prompts actually include:

    • finding titles for license violations (internal/ai/analysis.go:146) and as the example title per CWE group (:263)
    • finding mitigation text under 200 characters (:163)
    • the product description (:291)
    • benchmark notes (: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.

  5. Nit — Apply can break the frontend when nothing was applied. ApplyBenchmark returns {"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:132 then fails on res.applied.length. Fix: initialise with applied := []string{}.

  6. Nit — AIUsage.Batch has no default. internal/models/ai.go:81 has no gorm:"default:false" tag, although b13f3d7 says "ai_usages.batch/tier get defaults for existing rows". Only Tier got one. On PostgreSQL, AutoMigrate adds a nullable column, so existing rows hold NULL and won't match batch = false.

  7. Nit — scheduled digests block the scheduler. job.go:667: the scheduler calls SendDigest synchronously, and a model call can take up to 10 minutes. With several orgs this delays resumeOrphans and other orgs' scheduled runs. Run it through s.async.

  8. Nit — job-runner queries look up rows by ID alone. heartbeat (job.go:191) and stopReason (job.go:223) use only the job ID. This is commented as deliberate, but r.job.OrganizationID is already available, and adding organization_id = ? costs nothing and follows AGENTS.md. The cross-org queries in resumeOrphans/startScheduled are unavoidable and documented.

  9. Nit — frontend permission check differs from the backend. web/src/pages/Benchmark.tsx:46 and ProductComponents.tsx:36 decide writable from the org role (canWrite(me?.role)). The backend uses EffectiveRole, 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:

  • Tenant scoping: every handler and service query is scoped by organization_id, including the advice/analysis joins and the digest joins through findings.
  • Secrets stay out of the API: BatchIDs, Runner, HeartbeatAt, InputHash and Prev* are all tagged json:"-".
  • Slack webhook: decrypted with SecretBox. The URL is removed from *url.Error before it is stored, and apiError doesn't include it.
  • RBAC: routes use the admin middleware or EffectiveRole(...).AtLeast(RoleWriter).
  • Batch requests: SubmitBatch carries over model, system, messages, output config (effort and schema) and fallbacks.

Completeness

  • Migrations: AIJob, ProductAnalysis and AIDigest are registered in AllModels(). The Batch default is missing (Finding 6).
  • Backend tests: broad coverage of the jobs, analyses, digest, Anthropic batch API (fake server) and handlers. Missing: a batch whose polling keeps failing (Finding 1), resuming after results were partly stored (Finding 2), and a panic in a worker (Finding 3).
  • Frontend tests: AIJobsPanel and ProductAnalysisPanel have none. web/ has vitest configured but no test files at all, so this gap predates the PR.
  • API spec: api/openapi.yaml covers all the new endpoints and settings. Response bodies are described only in prose, consistent with the rest of the spec.
  • Docs: README.md and STATUS.md are updated, and STATUS.md lists 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.
  • Leftovers: no TODOs or debug code in the diff.

CI and comments

  • Checks:
    • codecov/patch: success (100.00% ≥ 80%)
    • codecov/project: success (54.97%, no base report)
    • security-scan: success
    • test / go: success
    • test / web: success
    • test / coverage-badge: skipped
  • ojo security scan: "No findings". Nothing is introduced or touched by this PR, and nothing pre-existing is reported.
  • Coverage: the Codecov comment reports 100% patch coverage and 5,549 uncovered lines in the project. 100% is surprising for a diff of about 4,250 added lines with untested TSX and untested error branches (for example, a poll error in awaitBatches). I couldn't confirm which files Codecov counts.
  • Reviewer comments: comments.json contains only the two bot comments. The review that b13f3d7 responds 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 the ai_usages.batch default (Finding 6). The panic-recovery fix only covers part of the job (Finding 3).

Recommendations

Before merging:

  1. Make batch polling stop: after a cancel or stop, after repeated poll errors, or at a deadline (Finding 1).
  2. Record batch usage once per (job, subject) and recompute progress on resume (Finding 2).
  3. Recover panics in the sequential workers and keepLease (Finding 3).
  4. Correct the README and description wording about what is sent to the model, or remove the free-text fields from the prompts (Finding 4).
  5. Fix the small items: applied := []string{} (Finding 5) and gorm:"default:false" on AIUsage.Batch (Finding 6).

Can wait:

  • Run scheduled digests asynchronously (Finding 7).
  • Add org scoping to the job-runner lookups (Finding 8).
  • Use the product's effective role in the frontend's writable (Finding 9).
  • Consider whether bulk jobs should share the 4-request concurrency limit with interactive requests. Each sequential job takes two slots, so interactive requests may fail with ErrBusy while jobs run.
  • Add frontend tests for the new panels.

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

<!-- claude-pr-review --> ### Summary This PR builds on the AI layer from #67 and adds four things: - **Bulk AI jobs** of three kinds: finding advice, SBOM analysis and ASVS benchmark. On Anthropic they go through the Message Batches API; other providers run sequentially. Jobs hold a database lease, can resume on another replica and can be cancelled. - **Per-product analyses** (`ProductAnalysis`): an SBOM upgrade plan, and an ASVS assessment that a writer can apply. - **An AI security digest**, sent as in-app alerts and optionally to Slack. - **Schedules** for the jobs and the digest. The last commit (`b13f3d7`) addresses an earlier review. It adds restoring previous results through `prev_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 1. **Blocking — a batch job can poll forever and block that job kind for the org.** `internal/ai/job.go:504-535`: `awaitBatches` only leaves its loop when every batch reports ended. When `BatchEnded` returns an error, the code logs it and keeps polling. - **When it happens:** the batch can't be found or read under the current key. For example, an admin replaces the Anthropic key with one from another workspace (a resumed job builds its provider from the current key), or the key is revoked. - **What goes wrong:** the poll returns 404/401 on every attempt, and the heartbeat keeps renewing the lease. - **Why it can't be stopped:** cancelling or disabling AI only calls `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. - **Fix:** once a stop has been requested and the cancel attempted, or after N consecutive poll errors, or after a deadline (for example 25h after the batch was submitted), stop waiting. Then call `finish(..., AIJobError, …)` so `release` restores the queued rows. Add a test with a `fakeBatch` whose `BatchEnded` always errors. 2. **Should fix — resuming during results processing records usage twice and pushes progress past 100%.** Job resume (`job.go:347`) and `store` (`job.go:410-444`) don't account for results the dead replica already stored. - **Double usage:** when a replica dies part-way through storing a batch's results, the replica that resumes re-reads all of them. The rows already written are no longer `queued`, so `store` treats them as superseded (`:430`). The `AIUsage` row is created before that check (`:421`), so each of these results is recorded a second time. That inflates `MonthTokens` and can trip the monthly limit early. - **Progress:** `job.Completed` is not reset on resume, so `Completed++` (`:444`) can exceed `Total`. - **Fix:** make the batch usage write idempotent per (job, subject), for example a `job_id` column on `AIUsage` with a unique index or an existence check. On resume, recompute `Completed`/`Failed` instead of adding to the stored counts. 3. **Should fix — panics in worker goroutines are not recovered.** The `recover` at `job.go:301` only covers the goroutine running `runJob`. A panic in the sequential workers (`job.go:569`, which call `complete`, `store` and `spec.updates`) or in `keepLease` still crashes the process. The resumed job would then crash each replica that takes it over, which is exactly what commit `b13f3d7` says can no longer happen. Fix: add `defer recover()` in each worker goroutine and call `halt()` with the error. 4. **Should fix — the docs say only aggregates are sent, but the prompts include free text.** `README.md:179` and the PR description say product analyses send "aggregates, not raw data". The prompts actually include: - finding titles for license violations (`internal/ai/analysis.go:146`) and as the example title per CWE group (`:263`) - finding mitigation text under 200 characters (`:163`) - the product description (`:291`) - benchmark notes (`: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. 5. **Nit — Apply can break the frontend when nothing was applied.** `ApplyBenchmark` returns `{"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:132` then fails on `res.applied.length`. Fix: initialise with `applied := []string{}`. 6. **Nit — `AIUsage.Batch` has no default.** `internal/models/ai.go:81` has no `gorm:"default:false"` tag, although `b13f3d7` says "ai_usages.batch/tier get defaults for existing rows". Only `Tier` got one. On PostgreSQL, AutoMigrate adds a nullable column, so existing rows hold NULL and won't match `batch = false`. 7. **Nit — scheduled digests block the scheduler.** `job.go:667`: the scheduler calls `SendDigest` synchronously, and a model call can take up to 10 minutes. With several orgs this delays `resumeOrphans` and other orgs' scheduled runs. Run it through `s.async`. 8. **Nit — job-runner queries look up rows by ID alone.** `heartbeat` (`job.go:191`) and `stopReason` (`job.go:223`) use only the job ID. This is commented as deliberate, but `r.job.OrganizationID` is already available, and adding `organization_id = ?` costs nothing and follows `AGENTS.md`. The cross-org queries in `resumeOrphans`/`startScheduled` are unavoidable and documented. 9. **Nit — frontend permission check differs from the backend.** `web/src/pages/Benchmark.tsx:46` and `ProductComponents.tsx:36` decide `writable` from the org role (`canWrite(me?.role)`). The backend uses `EffectiveRole`, 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: - **Tenant scoping:** every handler and service query is scoped by `organization_id`, including the advice/analysis joins and the digest joins through `findings`. - **Secrets stay out of the API:** `BatchIDs`, `Runner`, `HeartbeatAt`, `InputHash` and `Prev*` are all tagged `json:"-"`. - **Slack webhook:** decrypted with `SecretBox`. The URL is removed from `*url.Error` before it is stored, and `apiError` doesn't include it. - **RBAC:** routes use the `admin` middleware or `EffectiveRole(...).AtLeast(RoleWriter)`. - **Batch requests:** `SubmitBatch` carries over model, system, messages, output config (effort and schema) and fallbacks. ### Completeness - **Migrations:** `AIJob`, `ProductAnalysis` and `AIDigest` are registered in `AllModels()`. The `Batch` default is missing (Finding 6). - **Backend tests:** broad coverage of the jobs, analyses, digest, Anthropic batch API (fake server) and handlers. Missing: a batch whose polling keeps failing (Finding 1), resuming after results were partly stored (Finding 2), and a panic in a worker (Finding 3). - **Frontend tests:** `AIJobsPanel` and `ProductAnalysisPanel` have none. `web/` has `vitest` configured but no test files at all, so this gap predates the PR. - **API spec:** `api/openapi.yaml` covers all the new endpoints and settings. Response bodies are described only in prose, consistent with the rest of the spec. - **Docs:** `README.md` and `STATUS.md` are updated, and `STATUS.md` lists 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. - **Leftovers:** no TODOs or debug code in the diff. ### CI and comments - **Checks:** - `codecov/patch`: success (100.00% ≥ 80%) - `codecov/project`: success (54.97%, no base report) - `security-scan`: success - `test / go`: success - `test / web`: success - `test / coverage-badge`: **skipped** - **ojo security scan:** "No findings". Nothing is introduced or touched by this PR, and nothing pre-existing is reported. - **Coverage:** the Codecov comment reports 100% patch coverage and 5,549 uncovered lines in the project. 100% is surprising for a diff of about 4,250 added lines with untested TSX and untested error branches (for example, a poll error in `awaitBatches`). I couldn't confirm which files Codecov counts. - **Reviewer comments:** `comments.json` contains only the two bot comments. The review that `b13f3d7` responds 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 the `ai_usages.batch` default (Finding 6). The panic-recovery fix only covers part of the job (Finding 3). ### Recommendations Before merging: 1. Make batch polling stop: after a cancel or stop, after repeated poll errors, or at a deadline (Finding 1). 2. Record batch usage once per (job, subject) and recompute progress on resume (Finding 2). 3. Recover panics in the sequential workers and `keepLease` (Finding 3). 4. Correct the README and description wording about what is sent to the model, or remove the free-text fields from the prompts (Finding 4). 5. Fix the small items: `applied := []string{}` (Finding 5) and `gorm:"default:false"` on `AIUsage.Batch` (Finding 6). Can wait: - Run scheduled digests asynchronously (Finding 7). - Add org scoping to the job-runner lookups (Finding 8). - Use the product's effective role in the frontend's `writable` (Finding 9). - Consider whether bulk jobs should share the 4-request concurrency limit with interactive requests. Each sequential job takes two slots, so interactive requests may fail with `ErrBusy` while jobs run. - Add frontend tests for the new panels. ### 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_
james referenced this pull request from a commit 2026-11-19 23:56:55 +00:00
fix(ai): address review of #69
All checks were successful
codecov/project 54.97% (No base report)
codecov/patch 100.00% >= target 80%
test / go (pull_request) Successful in 4m31s
security-scan / security-scan (pull_request) Successful in 15m37s
claude-review / review (pull_request) Successful in 19m31s
test / web (pull_request) Successful in 2m20s
test / coverage-badge (pull_request) Has been skipped
b13f3d7813
Blocking:
- Slack transport errors no longer store or return the webhook URL: the
  request URL is dropped from *url.Error before it reaches slack_error
- resuming a batch job fails the job instead of crashing the process when
  the provider changed or can't batch; runJob also recovers panics so a bad
  job can't take down each replica that resumes it

Should fix:
- rows a job queues (and rows being regenerated by hand) remember their
  finished result in prev_status/prev_input_hash and get it back if the job
  is cancelled, stops or the refresh fails, with the failure kept as a note
- jobs check that AI is still enabled before running and between items or
  polls; disabling AI cancels running batches
- digests have a status; only done and quiet digests close a period, so a
  failed digest's activity goes into the next one, failures retry after an
  hour, stuck "generating" rows are cleared, and the token limit is checked
  before a digest is created; POST /ai/digests returns 502 on failure
- Slack digest text is escaped (no <!channel> or disguised links), the
  header is cut to 150 characters and the body to Slack's section limit
- Apply works on a benchmark assessment that is queued in a bulk job;
  queued rows refresh every 30 seconds in the UI
- batches are split at 10,000 items or 100 MB, and the job tracks every
  batch ID

Nits: input-builder query errors are returned, the digest's open and new
findings exclude out-of-scope and false positives, superseded results count
toward progress, concurrent benchmark applies are serialized on the product
row, system-scheduler queries are commented as deliberately cross-org, and
ai_usages.batch/tier get defaults for existing rows.

Tests cover the Anthropic batch methods against a fake API, resume after a
provider change, cancel and failed refresh restoring earlier advice,
disabling AI mid-job, batch chunking, progress with superseded results,
Apply while queued, digest failure and retry, Slack redaction, escaping and
limits, a scheduler pass, and the job and digest handlers.
james merged commit a371fe09a0 into main 2026-11-20 01:01:13 +00:00
james deleted branch feat/ai-advice-job 2026-11-20 01:01:13 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
ColibriSec/balam!69
No description provided.