mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-25 09:35:49 +08:00
f4cea19023c331c052d1585e45ec76cc4f7fcab7
24
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
5dd6124cfa |
chore(audit): recompute the claim-matrix tally after concurrent merges (#1649)
* chore(audit): recompute the claim-matrix tally after concurrent merges `main` was failing `Claim-to-gate matrix (ratchet)` and taking five open pull requests down with it. The summary block said Total 356 / GATED 351 while the table parses 358 / 353. Nothing is wrong with the rows. Two PRs each added one and merged within minutes of each other, and the hand-written summary is a separate declaration of a number the table already holds, so a resolution that keeps both rows still leaves the stanza describing the tree as it was before either landed. The gate is doing exactly what it exists to do: it reads the block back and refuses a figure that disagrees with the rows. Recomputed with `scripts/check_claim_gate_matrix.py` rather than edited by hand, and moved in all three places that publish it, since each is checked against the matrix by `tests/test_readme_figures_gate.py` and a partial fix would red the same build for the opposite reason. * chore(audit): recompute the claim-matrix tally after concurrent merges `main` was failing `Claim-to-gate matrix (ratchet)` and taking five open pull requests down with it. The summary block said Total 356 / GATED 351 while the table parses 358 / 353. Nothing is wrong with the rows. Two PRs each added one and merged within minutes of each other, and the hand-written summary is a separate declaration of a number the table already holds, so a resolution that keeps both rows still leaves the stanza describing the tree as it was before either landed. The gate is doing exactly what it exists to do: it reads the block back and refuses a figure that disagrees with the rows. Recomputed with `scripts/check_claim_gate_matrix.py` rather than edited by hand, and moved in all three places that publish it, since each is checked against the matrix by `tests/test_readme_figures_gate.py` and a partial fix would red the same build for the opposite reason. * chore(audit): recompute the claim-matrix tally after concurrent merges `main` was failing `Claim-to-gate matrix (ratchet)` and taking five open pull requests down with it. The summary block said Total 356 / GATED 351 while the table parses 358 / 353. Nothing is wrong with the rows. Two PRs each added one and merged within minutes of each other, and the hand-written summary is a separate declaration of a number the table already holds, so a resolution that keeps both rows still leaves the stanza describing the tree as it was before either landed. The gate is doing exactly what it exists to do: it reads the block back and refuses a figure that disagrees with the rows. Recomputed with `scripts/check_claim_gate_matrix.py` rather than edited by hand, and moved in all three places that publish it, since each is checked against the matrix by `tests/test_readme_figures_gate.py` and a partial fix would red the same build for the opposite reason. * chore(audit): let the gate restate the tally instead of a human editing it The stanza is the only place in the matrix that repeats a number the table already holds, so it is the only thing that drifts. Two pull requests each add a row, merge without conflicting, and the stanza is then stale by two while describing a tree neither of them produced. The file's own prose has always asked the reader to "recompute rather than editing a number here" and named no command that would, so every fix was three files edited by hand. --write restates the four figures from the parsed rows and prints what the two prose sites must carry. It refuses rather than guesses: a duplicated stanza is left alone because a writer cannot know which copy was meant, and a missing figure is not inserted because where it belongs is a judgement about the document. The prose sites are reported rather than rewritten -- a regex confident enough to edit a sentence is confident enough to mangle one. Proven against the defect rather than a fixture: with the stanza restored to 356/351 the plain run fails, --write repairs it, the plain run then passes, and a second --write is a no-op. Six cases added, including both refusals. * chore(audit): let the gate restate the tally instead of a human editing it The stanza is the only place in the matrix that repeats a number the table already holds, so it is the only thing that drifts. Two pull requests each add a row, merge without conflicting, and the stanza is then stale by two while describing a tree neither of them produced. The file's own prose has always asked the reader to "recompute rather than editing a number here" and named no command that would, so every fix was three files edited by hand. --write restates the four figures from the parsed rows and prints what the two prose sites must carry. It refuses rather than guesses: a duplicated stanza is left alone because a writer cannot know which copy was meant, and a missing figure is not inserted because where it belongs is a judgement about the document. The prose sites are reported rather than rewritten -- a regex confident enough to edit a sentence is confident enough to mangle one. Proven against the defect rather than a fixture: with the stanza restored to 356/351 the plain run fails, --write repairs it, the plain run then passes, and a second --write is a no-op. Six cases added, including both refusals. |
||
|
|
b99c744b1a |
4.4: precedent by similarity, and a re-triage that writes something (#1594)
* depth2 Phase 0: kickoff, re-derived baseline and the SIEM-scope decision Phase 0.1-0.4 of the wave-2 depth plan, which lands here locked beside the other four plans. 0.2 re-derives every figure the plan captured. All twenty reproduce exactly except the cloud/identity/SaaS/code condition count, which the plan itself flagged as approximate: measured 344 against 'about 358'. D1 records why, and the finding underneath it — no script in the tree implements that sentence, so every published value of it was hand-counted with a slightly different product set, and windowed rules contribute zero because they carry no product field at all. Phase 2.1's gate has to decide that explicitly. 0.3 captures the baselines, including 'make up-full' — the one the first depth plan recorded as never captured (its D2). 22 containers on the full profile; CORE passed 'make smoke' 10 of 10. The baseline host had nine unrelated containers on it including a foreign Postgres on 5432, and 'make up-full' failed its first bind before the port resolver's overlay landed. D2 records the sequence and, deliberately, does not claim a defect from it: the preceding state is not replayable, so it carries a clean-host reproduction as a follow-up instead. 0.4 is ADR-0015: AiSOC federates to the SIEM rather than replacing it. The README's 'Not a drop-in SIEM replacement' is now a decided position with its cost argument — compliance search needs raw-payload retention outside the 8 GB CORE budget and an availability promise this project has no measured evidence it can keep. Proposed, and nothing in this plan builds from it. * depth2 Lane F: claim migrations 151-158 and ADR 0022 * 3.3: failing test — a repeated vendor finding leaves no count A same-fingerprint repeat is collapsed by three independent layers and kept by none of them. The only trace is a source_event_ids append, which answers 'did more than one event produce this' and nothing else: it also grows on multi-event correlation, so its length is not a repeat count, and it stops at 200. alerts.first_seen and alerts.last_seen have existed since 001_init and fusion has never written either, so the window the repeats span is recorded nowhere. 5 of 7 fail on this tree with 'no statement touched alert_occurrences'. * 3.3: keep a repeated vendor finding as a linked occurrence A same-fingerprint repeat was collapsed by three layers and kept by none. The only residue was a `source_event_ids` append — capped at 200 and shared with multi-event correlation, so its length was never a repeat count — and `alerts.first_seen` / `last_seen` have existed since 001_init with no writer at all, so the window the repeats spanned was recorded nowhere. `alert_occurrences` (migration 151) is a rollup keyed (tenant_id, alert_id): an exact count that includes the surviving alert, the real first- and last-seen window, and a bounded most-recent window of the original payload ids. A vendor re-reporting one finding 79 times is one alert that says 79. A rollup rather than a row per occurrence because "one indicator, a thousand rows" is the shape the retro-hunt sweep already refuses. The payload window evicts oldest-first so the jsonb containment guard's coverage sits where Kafka redelivery actually happens, and `payload_ids_complete` goes false the moment anything is evicted. The measurement is published as its own labelled row and never added to correlation: 28.4 % repeat folding (1000 inputs -> 716 alerts, 284 folded) beside 33.3 % and 24.5 % correlation. The reduction is identical before and after this change and the docs say so — folding is not new, keeping what it folded is. What changed is that 284 inputs are accounted for instead of absent, which the suite asserts as a four-bucket balance summing to the denominator plus a requirement that each folded repeat resolve to the id of the alert that absorbed it. Writing the live suite found a defect in this change's own migration. The conventional `WITH CHECK (tenant_id = current_tenant_id())` makes the row unwritable by fusion, which is a Kafka consumer and binds no tenant session; measured as `aisoc_app` (NOBYPASSRLS), the identical session inserts into `alerts` and is refused here. Because the write is deliberately best-effort it would have failed in silence and the feature would have read as "this vendor never repeats" — migration 123's defect exactly. The policy now mirrors `alerts_tenant`, with the reasoning in the migration. Negative controls, both measured: reverting the WITH CHECK fails all six live cases; removing the containment guard takes five redeliveries of one message from a count of 2 to 7. Baselines unchanged: 33.3 % and 24.5 % reduction, zero cross-rule groups. * 4.6 and 9.4: record what has not been measured, and gate the absence 4.6 — outcome evidence. The three outcomes a buyer asks for first can only be measured by replaying somebody's real closed alerts through `make replay-eval`; the grader compares AiSOC's verdict with a human decision, so the input cannot be synthesised without the measurement becoming a comparison with a fixture written to be compared against. No design partner has offered a window, so false-positive reduction, time to verdict and escalation rate are recorded as *not measured* with the exact two-command reproduction beside them. `check_outcome_claims.py` is what makes that record worth anything. While the replay page says an outcome is unmeasured, no published surface may print a number for it — including `0`, which is the more damaging of the two, because a zero says AiSOC was measured against a real queue and reduced nothing, and it looks like data. The prohibition is read off the replay page rather than hardcoded, so a real measurement retires it without anyone editing the gate: a gate that had to be edited to admit a measurement would be edited to admit a fabrication. Its first run flagged a true sentence — a capability table row naming `escalation rate` in a list beside an unrelated "auto-refresh every 60s" — so the rule narrowed from same-line to same-clause, with both that case and a real claim in the identical row shape pinned in the self-test. A gate that flags correct content gets switched off within a week. 9.4 — the Teams half. Verified rather than assumed: the war room is built, and `POST /war-room` answers 501 naming each absent Microsoft Graph setting instead of falling back to the incoming webhook, because one shared channel per deployment puts the next incident's traffic in the last one's thread. That is already pinned by `services/teams-bot/tests/test_war_room.py`. It is maintainer-blocked on an Entra application registration with Channel.Create, ChannelMessage.Send and Group.ReadWrite.All, admin consent and a team id — recorded as a claim row so the honest refusal cannot quietly become a fallback. Matrix 335 -> 337 rows, 332 GATED, tallies moved in lockstep. * 5.2: run a scheduled hunt on the lake, and label what it emails Two gaps, both of the "built but nothing connects them" family. The scheduler could only run a hunt against a warehouse the tenant had connected: `resolve_provider` required `connected_types.intersection(provider.connector_types)`, and `_execute_hunt` converts the resulting `UnsupportedTranslation` into a hit count of **zero**. Zero hits is not an error state — no case opens, nothing logs above INFO, and `last_run_at` moves — so on every surface it was indistinguishable from "your hunt ran and found nothing". That was the answer on every deployment whose data lives in AiSOC's own lake, which is the default deployment, because AiSOC's own connectors put it there. This is the half the `credentials.py` fix could not reach. That one gave providers the tenant's connector credentials; this is a tenant who has connected nothing for credentials to come from. `LakeProvider` declares no connector types, because there is no connector to resolve — the lake's address is deployment configuration. The registry treats an empty `connector_types` as "needs no connected warehouse", checked after the connector-backed chain so a tenant's own SIEM always wins: it holds years of history AiSOC never ingested, and answering from the lake instead would be a narrower answer to the same question given without anybody choosing it. Scoping is through `compile_hunt`, which binds the tenant structurally and asserts the predicate survived — not `rewrite_for_tenant`, which exists to constrain untrusted operator SQL. An unreachable lake raises rather than returning zero, so the hunt retries instead of moving its clock. Conditions the lake schema cannot express are logged by name, because a hunt that ran with two of its four conditions dropped found fewer matches than was asked about. ADR-0015 requires the emailed hunt PDF to be labelled as hunting output. Before this, `rg -i "hunting output"` matched only the ADR itself: the renderer emitted the row's own title and nothing else. The label is now in the banner, the page title and the mail subject, with a sentence saying what the document does not claim — a reader who does not know the phrase learns nothing from the phrase alone. Delivery itself did not exist. `render_pdf`, `build_from_hunt`, `persist` and `send_mail` all worked; `aisoc_hunt_reports` and the report scheduler's `ReportArtefact` are different surfaces and were never connected, so a hunt report could be generated and downloaded and could not be sent. It ships off: `AISOC_HUNT_REPORT_RECIPIENTS` unset means nobody asked for this. A hunt that matched nothing mails nothing, a missing WeasyPrint stack sends the HTML rather than nothing, and a failing relay never costs the case. The protocol's `credentials` is widened to `| None` rather than suppressed at the call site: the scheduler genuinely passes None for such a provider, and a signature saying otherwise would be the type checker agreeing with a contract the code does not keep. Negative control: removing the empty-connector_types arm from `resolve_provider` fails the reproduction and the scheduler-wiring case. API suite 5042 passed, 174 skipped. Matrix 337 -> 339 rows, 334 GATED. * 9.2: record the device block, and correct a README row that overstated The mobile capability table read "Voice input — Transcription is on-device by construction", which is true of the module and reads as a working feature. `apps/mobile/src/lib/voice.ts` has no recogniser behind it and no screen importing it: the only file in this repository that mentions it is that README. The row now says so, and keeps the half that is real — the module takes a recogniser returning a *string*, so no audio type appears in its signature, a device with no offline model is refused rather than silently using the platform's cloud recogniser, and check_no_audio_egress.py fails the build on any capture API or binary body. That is a design that cannot leak audio. It is not a feature that works. 9.2 proper is blocked twice over and the second row says both halves: the voice path needs 9.1's recogniser and screen to exist at all, and then an Apple developer account and provisioning profile, or a Google Play account, to reach a handset somebody can speak to. The Android assembleDebug APK does install on a handset, so once 9.1 lands the Android half becomes a device question rather than a credentials one. The mobile.yml README-honesty guard is extended rather than left behind — the workflow's own header records that "we added a build so the honesty check is no longer needed" is how an ungated claim returns. It now pins both new rows and asserts its own vacuous-pass case, since a guard that greps four patterns in a file it never opened reports success. Negative control: restoring the previous wording fails the voice-input pattern. DEPTH2_PROGRESS gains deviations D3 (four Lane F items that did not reproduce as the plan describes them, with what is actually missing) and D4. * 3.2: link alerts into stories by typed evidence, not by string match Built on attack_chain_grouper rather than beside it. It chained alerts sharing a host, user or source-IP *string*, first match wins in a fixed order, with nothing on the result saying which of the three had done it. So a NAT egress address or a shared jump host welded two unrelated intrusions into one story; an alert carrying a session id — which fusion has written onto the alert row since migration 102, alongside the human resolved behind an assumed-role chain — got no more weight than one carrying a hostname, so the strongest evidence available went unused; and `ChainMember` carried a per-member severity that nothing aggregated, so the plan's "a member benign alone may be escalated by its story" had nowhere to happen and no reason to record. Links are now typed and carry a strength, and the strength decides what a link may do. Session and resolved human are strong; file hash and domain are specific; bare entity strings are weak. A weak link may not merge two detection rules, which is what keeps v21's narrowing from being undone one layer up where the published 24.5 % cannot see it. A strong or specific link may cross rules, and the assignment records which link did it so every cross-rule story is enumerated rather than tolerated. Story severity rises by exactly one tier, never past critical, and only when the story spans three or more kill-chain stages — one alert is an alert, two can be one action seen twice, three stages on one authenticated context is a narrative. Members carrying no tactic do not count toward the span, so three tactic-less detection alerts cannot escalate each other. The reason travels on the assignment, because an escalation whose cause is in a log line cannot be audited from the alert. Actor mode is `unknown` until Lane A's 1.4 supplies cadence. Two inferences were considered and rejected in the code: a credential session with no resolved human is unresolved rather than automated, and a service-account shaped username is a naming convention rather than evidence. Measured over three labelled multi-stage scenarios interleaved with unrelated traffic sharing the tenant's NAT egress address: recall 100 % on all three (4/4, 3/3, 2/2), purity 100 % (5/5 stories), 0 cross-rule stories of 63 on a detection-shaped cohort. The purity rule was found by that measurement rather than reasoned out in advance. The first cut refused a weak link only when it crossed detection rules, and the suite immediately measured 75 %: the scenario alerts carry no rule_id, so the cross-rule arm had nothing to compare and an antivirus quarantine joined a phishing-to-exfiltration story on a shared address. A weak link now also may not join a story anchored on strong evidence. The asymmetry is deliberate and tested — a strong link may still join a pile string matching had already assembled, or the tiers would be a rule about arrival order rather than about evidence. Negative controls, both measured: removing the strong-anchor refusal fails the purity measurement and its unit case; removing the cross-rule refusal fails the enumeration and its unit case. Reduction baselines unmoved: 33.3 % and 24.5 %. Fusion suite 1090 passed. Open and recorded rather than approximated: stories are still Redis-only, so the assignment evaporates after the Kafka envelope and no API read can show one, and the resolved-identity link waits on Lane A's 3.1. * Lane F: record the eleven items the lane did not reach, with measured state Deviation D5. The reproduction work for each was done before the lane ran out of time, so each row is measured state rather than a guess — which is worth more to whoever picks them up than a fresh grep. Three are worth reading before anyone starts: 4.5's read verbs already exist (987 lines, 5 verbs, 7 vendors); the gap is that run_auto_triage has no tool channel at all, so a vendor alert that auto-triages never pulls vendor evidence. 4.4's precedent already reaches triage by two routes but matches only on exact fingerprint; a complete Qdrant recall with provenance sits unused by the triage path. A naive re-triage writes nothing, because run_id is a uuid5 over the alert and workflow version and the ledger is ON CONFLICT DO NOTHING. 9.5's claim row is stale in the repository's favour: SCIM tokens and organisation members are both built and the row still says they are not. * 3.3: declare the occurrence suite's fixture DSN as the owner it is check_runtime_db_role.py failed two jobs on #1588 with one root cause: the live suite's ISOLATION_OCCURRENCES_ADMIN_DSN connects as 'aisoc', which the workflow provisions as a superuser, and a superuser ignores every RLS policy even under FORCE ROW LEVEL SECURITY. The split is deliberate and the gate is right to make it explicit. The code under test reads ISOLATION_OCCURRENCES_DSN, which is the DML-only runtime role with NOBYPASSRLS — that is what found migration 151's WITH CHECK defect in the first place, and a suite driven entirely as the owner could not have. The owner DSN exists only so fixtures can create scratch tenants, which the runtime role cannot. Declared with the marker and the reason the gate asks for, in the same shape agent-auth-live.yml already uses. * 4.4: precedent by similarity, and a re-triage that writes something Verified first, and the plan's premise was narrower than its wording. Analyst reclassification already reaches triage by two routes — `human_priors.record_human_prior` writes a human-authored outcome prior, and `context/dispositions` renders the last five analyst decisions into the preamble. Neither is rebuilt. Both match on identity: a SHA-256 over eighteen canonical fields, or a rule-id/entity string. So an analyst who closes the same finding on twelve hosts teaches triage twelve separate lessons, each reachable only by an alert identical to the one that taught it. Similarity scores the canonical evidence rather than embedding it. The obvious design is vector recall and `semantic_memory.py` is a complete Qdrant-backed one — deliberately unused, on a measurement already paid for: the only local models are generative ones pressed into embedding duty and they scored below the lexical baseline, recall@1 0.333 against 0.667, which is why /kb/query stays full-text. Reaching for embeddings here would repeat a choice already measured as worse, on the hot path, for a feature whose value is that the precedent is relevant. The canonical evidence is already a small closed typed set, and scoring overlap across it is explainable to the analyst reading the citation — which matters more here than for a knowledge-base chunk, because the output is "somebody decided this before" and an analyst has to be able to check whether they did. A prior stores the evidence it came from, because a signature is a hash and a hash cannot be compared. Priors written before this carry none and are invisible to similarity; there is nothing to backfill from. Precedent is cited and never acted on. Exact-fingerprint suppression stays the only path from memory to a closed alert: a similar alert is not the same alert, and closing one on a neighbour's verdict is the false negative `canonical_evidence` itself calls much worse than a missed repeat. The measurement found a real gap in the first cut. Two alerts whose only shared field is `severity` agree on everything they both carry and score a perfect 1.0, so a ratio alone makes "severity: high" precedent for every high alert in the tenant. A floor on the weight of shared evidence is the half the ratio cannot see. Re-triage. Nothing re-triaged, and the obvious implementation writes nothing while reporting success: the run id is uuid5(alert_row_id:WORKFLOW_VERSION) and every ledger write is ON CONFLICT (run_id, seq) DO NOTHING, so a second triage collides on seq 0 and seq 1 and leaves the ledger describing the first verdict. That pairing is correct — it is what makes a Kafka redelivery idempotent — so a re-triage needs its own identity rather than a weakened constraint. It is uuid5 over the alert, the workflow version and a fingerprint of the triggering evidence: deterministic, so a redelivered chain assignment is one run; distinct per trigger, so genuinely new evidence is another. Not a counter, which would need durable state and would make a redelivery look like new evidence. The diff is a record, not a log line, and `changed` is explicit rather than inferred from comparing two fields: a re-triage that reached the same verdict is a real outcome and must be tellable from one that moved. It closes nothing. Closure stays chokepointed at `authorize_auto_closure` inside `persist_auto_triage`, which is at the write precisely so a new caller cannot route around it. Two assertions first failed on their own prose — both modules describe closure at length in order to explain they do not reach it — so they now parse the source and strip docstrings, the same blindness check_gate_coverage had when a gate named only in a docstring counted as invoked. The writer-parity gate caught the three other writers that had not grown the new keyword, which is exactly its job. Negative controls, both measured: dropping the shared-weight floor fails the weak-field case; making the re-triage id ignore its trigger fails two identity cases. Scorecard unchanged at 0.250 deterministic balanced accuracy. Agents suite 2222 passed, 8 skipped. Matrix 340 -> 342 rows. * 9.5 prerequisite: a 'not built' claim about a console page must still be true (#1592) The claim-to-gate matrix carried, inside the caveat of a GATED row: Six console pages parity 4.5 also names — branding, SCIM tokens, retention, organisation members and grants, rule packs, delegations — are not built Three of them were built. `ScimTokensPanel` had shipped, was wired into SettingsView, and is gated by another row of the same matrix — so two rows of one document disagreed about whether a surface exists. `RBACView` had shipped and is covered by BannerHonesty.test.tsx. `UsersView` had shipped at /settings/users and was tested by nothing at all. The direction of the error is what makes it worth its own change. It reads as modesty and works as an exemption: a surface recorded as absent needs no claim row and no gate, which is exactly what that sentence was doing in a caveat. A shipped page inherited the coverage of a page that does not exist. `check_claim_gate_matrix` cannot see this. It counts rows and statuses and does not read a caveat's prose, so the row stayed GATED, accurate about its own claim, while excusing an entire surface from having one. check_unbuilt_claims.py reads every "not built" assertion scoped to console pages, resolves each named surface through a component file **and** a render site — an unrendered component is not a page, and crediting one would make the gate certify the defect it is named for — and fails on any that exist. Proven against the pre-fix tree, where it names all three. Six self-test cases in both directions, including the motivating sentence verbatim and an unrelated "not built" outside a console context that must not fire. Only one direction is checked, deliberately: claimed absent, actually present. The opposite is already covered by the gates requiring a claim row to name a job that drives the production path. UsersView.test.tsx is the gate the corrected row now names: six cases asserting on first paint as well as the error branch, since `data` is undefined in both and a suite driving only the error branch never exercises the state every page load passes through. The load-failure case asserts the absent state too — "we could not read the members" and "this organisation has no members" are different facts about an access-control surface. A member count is asserted not to render over a failed read, because `total` falls back to 0 and "0 members" beside a red error box is a number nobody measured. Writing it reproduced the mirror of a recorded trap: the first mock exposed `authApi.me` where the component calls `authApi.currentUser`, so a double less capable than the real object failed six tests with a TypeError rather than an assertion. Branding, retention, rule packs and delegations genuinely are not built and the corrected caveat says so. Matrix 340 -> 341 rows, 336 GATED. * depth2 Lane E: AI provider coverage, chat-compliance minimisation, hosted agents, repository AI config and four replayed AI rules (#1585) * depth2 Lane E: claim migrations 146-150 and ADR 0021 * test(connectors): reproduce the AI provider-coverage gap in llm_usage Depth 6.3 / wave-2 7.1. `LlmUsageConnector` accepted `openai` and `anthropic` and nothing else, so Gemini in Workspace, Copilot in M365, Copilot in GitHub and Entra consent grants to AI applications had no reader at all and the AI estate's provider-audit discovery source could only ever see two vendors. Six of the seven tests fail on this tree: four drive the real HTTP path against a mock server returning vendor-shaped payloads and get a ValueError from the constructor, one asserts the org-scoping refusal and one asserts the schema's select options match the accepted providers (`PROVIDERS` does not exist yet). Endpoints, query parameters and event names come from the vendors' current public references, each fetched and 200 before being written: the Admin SDK Reports API `gemini_in_workspace_apps` application, the GitHub organization audit log, the Office 365 Management Activity API schema (RecordType 261 CopilotInteraction, 284 AIAppInteraction) and Microsoft Graph directoryAudits. * feat(connectors): four more AI provider audit feeds in llm_usage Depth 6.3 / wave-2 7.1. Closes the gap the previous commit reproduced: the connector now reads Gemini in Workspace, GitHub Copilot, Microsoft 365 Copilot and Entra consent grants alongside OpenAI and Anthropic. Each client was written against the vendor's current public reference, every one of which was fetched and returned 200 before being committed; the module docstring names them per provider. The Workspace `gemini_in_workspace_apps` applicationName and the `ai_usage_event` / `feature_utilization` event names, the 23 published `copilot.*` audit actions, RecordType 261 CopilotInteraction and 284 AIAppInteraction, and the directoryAudits consent activities are all read values, not inferred ones. Three things the tests pin beyond "it parses": - Filtering happens server-side where the vendor supports it. Asking GitHub for an organisation's whole audit stream and discarding client-side is a rate-budget problem on a busy org, not a style one. - Where it cannot, the reader discards non-AI records by RecordType and by consent activity name. `Audit.General` is the entire Microsoft 365 general audit and `directoryAudits` is every directory change; a reader that forwarded both would replace the AI feed with a second copy of the general audit. - A consent grant's scopes are lifted out of the free-text `ConsentAction.Permissions` property into a sorted `scopes` list on the envelope. A grant whose scopes stay buried scores in the AI estate as a grant with no scope at all, which is the opposite of the truth for `Mail.Read`. M365 needs a second request because the subscription endpoint returns blob references rather than content; a reader that stopped at the first response would poll successfully forever and emit nothing. Workspace OAuth token grants are deliberately not read here — `google_workspace` already polls the `token` application, and a second reader would double-count every grant. What is missing there is classification, which is the next commit. Docs and the conformance matrix regenerated, not hand-edited. * test(fusion): reproduce the recorder reading a path no connector emits Wave-2 7.1 wiring. `test_ai_asset_recorder.py` writes `finding.evidence.scopes` into a hand-built OCSF event and asserts the recorder reads `finding.evidence.scopes`. Both halves are the test's own invention: no connector in the tree produces that path and ingest does not synthesise it, so the assertion holds whether or not the production path works. What ingest really hands fusion is the connector's normalized dict as a JSON string under `ocsf["raw_data"]`, which is why `_connector_fields` exists for the endpoint path and is not used by the provider-audit path. Driven through that real shape, both new tests fail: an Entra consent grant reaches the inventory with no scopes at all, so an AI notetaker consented into every mailbox in the organisation scores identically to one granted nothing, and the console's reason list is silent about the single fact that decides whether the grant matters. The fixtures are the real output of `LlmUsageConnector.normalize()`. The two services cannot import each other — both package their application as `app` — so they are held together by a committed artefact plus a check in each direction, the way the vendored narrative and the detection ruleset already are. * fix(fusion): read provider-audit fields where the connector puts them Wave-2 7.1 wiring. `_from_provider_audit` now reads through `_connector_fields`, the same reconstruction the endpoint path already performs, instead of off the canonical OCSF map. An Entra consent grant's scope list reaches `score_risk`, so a grant holding `Mail.Read` scores as broad and says so in its reason list. Two further corrections the real shape forced: - An OAuth grant is keyed on the **application**, not the audit record. Keying on the record id would make every re-consent a new asset and reset `first_seen_at` on each, so the inventory would grow a row per event and never show that this application has been there since May. - The OCSF-native `finding.evidence.scopes` read is kept as a fallback rather than replaced, so a producer that does emit it is still read. Trading one blind spot for another is not a fix. Negative control, recorded: with the `fields.get("scopes")` read reverted to the pre-fix path and nothing else changed, both new tests fail again (`KeyError: 'scopes'`). Restored, the fusion suite is 1063 passed / 28 skipped. The `normalize` contract is unchanged across all 87 connectors: the "is this record AI activity at all" decision is a separate `is_ai_record` predicate rather than a `None` return, which keeps the base signature intact and makes the filter — the thing that stops the Microsoft 365 AI feed becoming a second copy of the general audit — callable and testable on its own. * feat(api): enterprise AI-chat compliance logs, minimised by the schema Wave-2 7.1, second half. Reads an AI provider's compliance API for the directory, projects and activity feed, and — behind a second, narrower opt-in — classifies message content without keeping any of it. Written against Anthropic's Compliance API, the one enterprise AI-chat compliance surface with a complete public reference. Every path, scope, key prefix and response field was read from pages that each returned 200 before being committed; the client's module docstring names them. The Activity Feed record and the chat record in the tests are the vendor's published examples field for field. The minimisation is in the schema, which is the point of ADR-0021. A plan sentence saying "never full conversations" that a TEXT column permits is not a control; it holds until the first caller who binds "\n".join(messages) and succeeds silently. - No table has a column able to hold a message. Asserted against the ORM, since that is what application code binds through. - The snippet is VARCHAR(280). The collector truncates; the column is the backstop for the caller that forgets. - The snippet is masked BEFORE it is cut, so a row saying "this chat contained an AWS key" does not contain the key. A verbatim window would create a new copy of the secret in a table an operator believes is safe to keep, and label it so an attacker can find it. A per-pattern sweep asserts the value is absent for every shape in the shared list. - The label vocabulary is a CHECK constraint, and a test asserts the three copies of it (constraint, ORM, classifier) agree. - The client has no method returning message text, asserted on its public surface. - Two opt-ins, stricter one default-off: collection does not imply reading message bodies. - Off by default per tenant, through the console, vault-held key. No environment variable. A vault failure is a 503, never a plaintext row. The secret-shape patterns are the AI SDK's own, vendored by scripts/sync_vendored_ai_redaction.py and held byte-identical by its --check. A prompt and a chat message containing the same AWS key must produce the same shape name on both surfaces; a second hand-written copy is how two surfaces come to disagree about the same rows. The SDK groups e-mail and card shapes with credentials because it is answering a transmission question; _SDK_LABEL maps each shape to one of the plan's four classes rather than relabelling the shared list. Luhn is applied to the shared card shape. Without it the digits-only pattern labels order ids as payment data, and a classifier that labels everything is one nobody believes. Retention, legal hold and erasure come free and are tested: every table carries a column named exactly `tenant_id`, which is how `discover_tenant_tables` finds it. Discovery rather than a declared list is deliberate — a list is the thing that goes stale. Tests use httpx.MockTransport rather than respx, because respx is not in this service's locked dependency set and a test needing a package CI does not install is a test CI cannot run. MockTransport replaces only the network leg. Negative control, recorded: adding a `transcript: Mapped[str | None] = mapped_column(Text)` to AiChatContentLabel and changing nothing else fails two tests (the forbidden-column sweep and the unbounded-TEXT sweep). Removed, the API suite is 5074 passed / 174 skipped. Migration 146 and ADR-0021 were claimed in DEPTH2_PROGRESS.md before either file was written. * docs(depth2): record 7.1 in the progress tracker * feat(ai-estate): hosted agents and repository AI config as asset kinds Wave-2 7.2. Two new kinds on `aisoc_ai_assets` (migration 147), both scored by the one existing `score_risk` and rendered with their reasons on the AI estate page. No second scorer: the plan forbids it by name and it is the drift this repository keeps finding. **Hosted agents** come from `GET /v1/agents` with the `managed-agents-2026-04-01` beta header, read against the vendor's published reference (fetched, 200). An agent configured in a provider's control plane is invisible to every other discovery path here: endpoint telemetry never sees it, and gateway telemetry sees its traffic without knowing what it was configured to do. The client is read-only — the vendor offers create, update and archive and none of them is here, because an inventory that can reconfigure a customer's agents is a different risk conversation and 7.2 is read-only by the plan's rule. **Repository AI config** is the scan of agent-instruction files, skill directories and MCP configuration through the code-platform connectors, recording the tools and servers each references. "Which repositories point an agent at this MCP server" is a question the estate could not answer. Every byte of that scan is attacker-controlled and is treated as such. These files are checked in, editable by anyone who can land a pull request, and read by an agent verbatim as instructions — the same trust class as a retrieved runbook, which this platform already scans. So: - Nothing is stored raw. Excerpts are flattened and capped at 400 characters, with zero-width and bidirectional characters stripped, because an instruction file is exactly where a payload invisible in a diff gets hidden. - The content is scanned at capture and only the matched *pattern names* are kept — never the matching text, which would put the attacker's payload in a table the console renders, labelled so a security team looks at it. - Those names reach `score_risk`, so a flagged file raises the asset's exposure and the reason names the channel. - A hosted agent's `system` prompt goes through the identical path, for the identical reason. The patterns are **generated** from the agents guard's own `_RULES` table rather than hand-picked, by scripts/sync_vendored_ai_instruction_rules.py with a --check wired into ci.yml. A hand-copied subset drifts: a pattern added to the guard after the next incident would never reach the scanner and nothing would say so. One rule is excluded with its reason recorded — `fabricated_tool_result` matches a model-output envelope rather than a repository file, and its pattern is assembled from a set, so it renders in a different order in every process and no generated file could match itself. The generator fails if an excluded name leaves the guard, so the exclusion cannot outlive the rule and become a silent gap. Two things found while building it: - `path.lstrip("./")` eats the leading dot of a dotfolder, so `.cursor/rules/x.mdc` became `cursor/rules/x.mdc` and stopped matching — silently, as a path that simply is not an AI artefact. Every convention here lives in a dotfolder, so that one call would have turned most of the scan off. Caught by the classification table, which is why it enumerates real paths rather than a couple of examples. - `DEVICELESS_KINDS` is shared between the model and `score_risk`, so the four kinds that cannot have a device are not charged for lacking one. A hosted agent has no laptop to isolate; the reason string "containment has nowhere to act" would simply be false. The tool reader matches grants, not prose: "do not use `write_file`" in a paragraph is not a grant, and counting it would make a careful instruction file score worse than a careless one. Also: a committed JWT-shaped literal in the 7.1 classifier test is now assembled from parts. The repository's secret scan was right to refuse it, and a test fixture has no business looking like a credential. * docs(depth2): record 7.2 in the progress tracker * feat(detections): four AI rules on the provider feeds 7.1 added Wave-2 7.4, partial — four of the rule pack's targets, each earned rather than declared. Executable corpus 2,530 -> 2,534, regenerated from `scripts/project_stats.py` and propagated to the README, ROADMAP, truth table, corpus stats, marketplace index and the packaged API copy by their own generators. Nothing was hand-typed. - `llm-copilot-content-exclusion-changed` (critical) — content exclusion is the control that stops a coding assistant reading the paths an organisation declared off limits. It is changed in a settings page rather than in a pull request, so nothing else reviews it. - `llm-copilot-agent-mcp-config-changed` (high) — adding an MCP server adds a party that can instruct a hosted agent. A scope change, not a settings change, and the agent runs on the provider's infrastructure so no endpoint control sees the result. - `llm-ai-app-granted-write-scope` (high) — a consent grant letting an AI application change a mailbox, drive, site or the directory. The read equivalent is an exposure; this one can act. - `llm-copilot-bulk-resource-access` (medium) — one assistant turn that read 25 or more distinct resources. An assistant with a user's grant is an exfiltration path that authenticates as that user and looks like ordinary application traffic. Every rule is replayed through the REAL connector and the REAL engine in `services/fusion/tests/test_ai_rule_pack_replay.py`. The fixtures are the committed output of `LlmUsageConnector.normalize()` on vendor-shaped records, regenerated and drift-checked from the connectors side, because the two services cannot import each other. Nothing here is synthesized from the rule it tests. That is the whole point: 1 of 12 GitHub rules fired on real connector output while all twelve passed their own fixture replay, because a fixture generated from a rule carries the rule's own clause key and the replay is tautological. Each negative twin differs in exactly ONE decisive field — a different Copilot action, `Mail.Read` where the twin is `Mail.ReadWrite`, 24 resources where the twin is 40 — and a test asserts that property on the fixtures rather than trusting it, since a negative that also moved the actor would pass for a reason unrelated to the clause. Negative control, recorded: rewriting one rule's clause to the unprefixed vendor action (`event_type: content_exclusion_changed`), which is the exact shape of the measured GitHub failure, and re-exporting, fails that rule's positive replay while the other three stay green. Restored, all ten pass. `test_builtin_rule_catalogue.py`'s hand-typed counts moved 760 -> 764 and 2609 -> 2613 with the reason recorded beside the existing history, in the style that file already keeps. * docs(depth2): record 7.4 partial and 7.3 not delivered, with evidence * chore(detections): regenerate the curated index for the four new rules `curate_detections.py --check` is a drift gate I had not run: adding four rules moves the curated selection and the coverage page, and neither is produced by any of the seven generators I did regenerate. Caught by CI, reproduced locally with the same command, and regenerated rather than hand-edited. Worth recording because it is the shape this repository keeps finding: a published artefact with its own generator and its own `--check`, sitting outside the chain everything else in the family runs through. All eight detection drift gates now pass together. * fix(ci): correct the gitleaks fingerprints the four new rules shifted `.gitleaksignore` pins a finding by `file:rule:line`, so inserting four entries into `detections/rule-ids.lock.json` moved every line below them and five fingerprints stopped matching the findings they were triaged for. The file's own header describes this rot and says the fix is to correct the line number, never to drop the entry or relax the job, so that is what this does: the set is re-derived by running CI's exact gitleaks 8.21.2 with the allow-list removed, and all fourteen are written back. Thirteen are the same pre-existing, benign findings — the heuristic fires on rule *slugs* such as `llm-api-key-created` and `slack-token-exposed`, never on a value. One is genuinely new: `llm-copilot-bulk-resource-access` trips it on the word "access". Verified under 8.21.2 rather than the 8.30.1 on this machine, because the two disagree about this tree and only the pinned one decides. Also regenerates `apps/web/public/marketplace/{index,curated}.json` through `pnpm marketplace:sync`. `curate_detections.py --check` passing is not the whole gate: the web mirror is copied by a separate step, and a curated index that is current in one place and stale in the other is the drift that check exists to catch. * 3.3: the occurrence guard anchored a pattern pytest never writes `grep -qE '^[0-9]+ passed'` cannot match, because pytest writes its summary as `===== 6 passed in 0.67s =====`. The job reddened on a run where all six live tests passed, which is the worse direction for a guard: one that fails on a healthy suite teaches people to ignore it. The count is now unanchored and `[1-9][0-9]*` rather than `[0-9]+`, so a run that collected nothing and reported `0 passed` is still a failure. Verified in all three directions against the real summary line: the new pattern matches it, the old one does not, and `0 passed` is still refused. * 4.5: give auto-triage a bounded channel to the read verbs it already had (#1593) No read verb is added here. `investigation_reads.py` is 987 lines carrying five read-only capabilities across seven vendors — Defender, CrowdStrike, SentinelOne, Okta, Entra, Workspace, AWS — each with a capability contract, an executor, an autospec'd signature test, a closed agent allowlist and a parameter allowlist. All of that worked. What did not exist was any way for auto-triage to reach it. The verbs are bound to the investigation agent in `deep_investigation.py`, which runs only on the escalation path. `run_auto_triage` was a single `safe_ainvoke` with no tool channel, and said so in its own comment. So on the path every fused alert takes, a GuardDuty or Defender alert was triaged without ever asking GuardDuty or Defender what they knew, and `unverified_tool_claims` correctly blocked auto-close if the model so much as claimed a tool result. A deterministic pre-fetch rather than a tool-calling loop, for three reasons. Latency and cost on the hot path would otherwise be unbounded: one model call becomes N plus N vendor round trips on every fused alert with no ceiling anybody declared. The alert payload is untrusted by construction — it is fenced and injection-scanned before anything reasons over it — so a channel whose arguments the model derives from that payload is a door an injected string can aim; not choosing at all is strictly stronger than the parameter allowlist alone. And the citation is true: the result is in hand before the model is asked anything, so the ledger row exists because the call happened rather than because the model said it did. It is a bounded channel, not an absence of one: triage reaches the real verbs, the set is fixed per alert shape, and the budget is declared. `called_tools` is now whatever a vendor really answered, and only that. A read that was attempted and failed is deliberately absent, because the guard's question is whether a rationale credits a tool with a result and a read that returned nothing produced no result to credit. An empty tuple when the pre-fetch is off restores the previous behaviour exactly. The reads land as `tool_call` rows at seq 2 and up, in the same transaction as the verdict. Not before the model call, even though that is when they happened: seq 0 and 1 are the model call's and the verdict's keys and the `(run_id, seq)` uniqueness is what makes a replay idempotent. The `ts` on each row carries the real ordering. Off by default behind AISOC_TRIAGE_VENDOR_EVIDENCE: this reaches the customer's vendor API on every fused alert. A failed read renders as COULD NOT CHECK with its status, never as silence. A failed EDR read is not evidence that the host is healthy, and an absent answer rendered as nothing is read by a model as a clean one. Negative controls, both measured: removing the render call fails the prompt case; counting failed reads as called tools fails the guard case. Scorecard: deterministic balanced accuracy 0.250, auto-close precision not measured — identical to the committed baseline, which is what an off-by-default context source must do. Alert reduction unmoved at 33.3 % and 24.5 %. Agents suite 2215 passed, 8 skipped. Matrix 340 -> 341 rows. * claim matrix: the gate never read the summary block it tells you to trust The file closes by saying the counts come from this script and that you should recompute rather than edit a number here. Nothing enforced either half: main() parsed the rows, printed its own totals and returned, never once looking at the written block. Two failures were therefore invisible. A figure edited by hand drifts silently from the table above it. And a conflict resolution that keeps both sides appends a second copy of the whole block rather than merging it, which reads as an ordinary union in a diff -- this branch carries three copies today, and the gate passed. Against the tree as it stands this exits 1 naming all three blocks and the two fields the first copy lost. The matrix is repaired in the next commit. * claim matrix, roadmap, evidence pack: collapse the blocks a merge duplicated What the new gate arm names on this branch, repaired. The matrix carried three copies of its summary block; the first two had lost the PARTIAL and NO GATE lines, so the figures a reader saw first were an incomplete copy of the real ones. ROADMAP.md carried the tally paragraph twice and the evidence pack carried its index sentence twice, both byte-identical duplicates of the line above. All three are the same artefact: a conflict resolution that keeps both sides appends rather than merges, and a diff of that reads as a union. The figures themselves were right, which is why no reviewer caught it. One further duplicate came from main rather than from this branch -- the Phase A bullet in ROADMAP.md is doubled there too -- and is removed here since the branch lands there anyway. Three files, one summary block each, and the matrix now reads 344 rows: 339 GATED, 5 PARTIAL, 0 NO GATE, with ROADMAP.md and the evidence pack agreeing. * claim matrix: pin the summary arm against both shapes it was built for Eleven cases, and the control that makes them worth having: reverting check_summary_block to the permissive `return []` it effectively was fails nine of them. The two that survive are the two asserting a correct block passes, which a no-op also satisfies -- stated here so the split is not read as partial coverage. The positive case is the shipped matrix scored against counts derived from its own rows, so the arm cannot pass by agreeing with a fixture this file also wrote. Three refusals are deliberate. A file with no summary block fails rather than passing, because an unknown bucket reading as a pass is how most of the gates in this repository failed. '## Summary of deferrals' is not a match, so a neighbouring section cannot stand in for the block. And a figure appearing in running prose does not satisfy a missing line, which is what the duplicated copies on this branch had lost. * fix(agents): resolve conflict markers committed into the fused-alert worker `fused_alert_consumer.py` carried three unresolved regions on this branch — `<<<<<<< HEAD` through `>>>>>>> origin/depth2/lane-f-analyst` — so the file was not valid Python. It survived because the pull request has been DIRTY since it was opened and GitHub creates no check runs for a branch whose merge ref it cannot compute, so nothing ever imported it. All three were 4.4's precedent block landing beside 4.5's vendor evidence: a counter, an attach call and a method. Neither replaces the other, so all three keep both. * style: ruff format * docs(matrix): one Summary block, recomputed from the gate A keep-both merge resolution appends a second `## Summary` rather than merging it, and on four of these branches the surviving copy had been spliced into the middle of the table. The row parser stops at the first blank line, so the splice both hid rows and left the published figure describing a shorter table than the file holds. One block at the end, with every bullet, and all three surfaces — the matrix, ROADMAP and the evidence pack — recomputed from `check_claim_gate_matrix.py` rather than edited. * chore(api): re-sync the vendored evidence fingerprint |
||
|
|
6cfef3227d |
fix(eval): the live dispatch runs on one event loop and scores failures as 0, with the floor re-derived from fixed-harness runs (#1466) (#1472)
Two defects in the live-eval dispatch path, fixed together because each hid the other's size. Per-incident asyncio.run poisoned the LLM stack: langchain-openai caches its default async httpx client across constructions (keyed on base_url + timeout), so incident 2's fresh loop inherited a pooled connection bound to incident 1's closed loop, and the first LLM call of every subsequent incident -- recon, always -- died with 'Event loop is closed' in milliseconds and fell back to heuristics while the rest of the pipeline proceeded on the recycled client. The report then graded mode=live over investigations whose recon stage never consulted the model. Reproduced locally (incident 1 recon 9.2s of real tokens, incident 2 failing in 9ms); the loop now wraps the whole run, matching production, and recon places real calls on every incident (llm_calls 62 -> 74-78 over the 10-incident slice). Regression test executes three incidents and asserts one loop id; it fails against the old code. An incident whose investigation failed was dropped from the sample -- survivor bias that inflates the mean, and the shrunken sample then fails check_live_agent_floor's size requirement anyway, which is exactly how the qwen leg deterministically red the last two weekly runs (0.5815 over 9 of 10). Failures now score 0 groundedness with the reason recorded in a zero_scored block, so the sample always equals the dispatched prefix. Observed live: a qwen ResponderPlan validation failure -- the same family as the CI drop -- scored 0 with its pydantic error in the report. The floor file is re-derived in the same change, per the checker's own instruction: three fixed-harness local runs (0.51, 0.445, 0.44) and the CI pair re-expressed under zero-fill (0.5815 x 9/10 = 0.5234) recorded beside the pre-fix observations, which stay for provenance with the defect named. floor_mean stays 0.40 -- below the lowest cited run, and the thinner margin is deliberate: at ~0.05 mean cost per failed investigation, a run failing three of ten dips below the floor, which is the signal such a run deserves. |
||
|
|
a7b7dfc556 |
fix(security): pin the semgrep rule packs the ratchet's ceiling was measured with
The Semgrep (ratcheted) job pinned the binary exactly and then fetched five rule packs from the registry at scan time, so the ratchet compared today's tree against whatever the packs contained today — measured on #1098 as 103/39 then 104/40 across two commits that changed zero scanned files. A pinned binary against unpinned rules is half a pin. The packs are now vendored under .security/semgrep/ by scripts/vendor_semgrep_packs.py (fetch / --check / --digest / --self-test), the scan reads the committed files, a workflow step proves they match their manifest, and check_scanner_ratchet.py gains a rules-drift arm binding the ceiling to the packs' combined digest via rules_sha256 — same arms as measured_with, including could-not-establish failing rather than skipping. Re-measured deliberately with the vendored packs: 110/43 against the recorded 110/44 — the ERROR that moved is itself registry drift since 44 was measured, which is the closing exhibit. The scanner's own one-in-twenty +/-1 is a separate, still-open reason the job stays unrequired. Closes #1099 |
||
|
|
f5d46d74df |
A balanced, labelled verdict corpus the scorer accepts (depth 1.1) (#1205)
* A balanced, labelled verdict corpus the scorer accepts (depth 1.1) Every labelled set under services/agents/tests/eval_data/ is malicious by construction. synthetic_incidents.json and adversary_incidents.json are 200 attacks each and carry no expected_disposition at all, so score_replay_set.py refuses both — correctly — and nothing in this tree could measure whether the agent got the verdict right. Adds the corpus it accepts instead: 72 items in 36 twin pairs. Largest class is 50.0%, so the best constant answer scores 0.500 against the plan's 60% ceiling, and that figure is measured through score_replay rather than asserted. 36 malicious items clears the 30 a report needs before it will print a headline accuracy. 52 of 72 items (72.2%) come from cloud, identity and SaaS, covering all ten sources the plan names. Each non-malicious item has a malicious twin that fired the same rule at the same severity with the same title, so the evidence is the only thing that can separate them; because twins share severity, the two halves carry an identical severity distribution and severity alone separates nothing. The benign half is what real queues hold: admin bulk changes, scanners, CI service accounts, travel sign-ins, break-glass use with a ticket, backup jobs. All 72 items are hand-authored and every one carries is_synthetic: true. Nothing is drawn from a recorded dataset and nothing implies otherwise. The README records five public corpora considered and why each was refused; two pass on licence and fail on fit, because no public attack-telemetry set carries analyst dispositions, cloud control-plane events and a paired benign case at once. scripts/check_verdict_corpus.py holds all of it: balance, source mix, pairing, provenance carrying a licence from a redistribution allow-list, documentation-only addresses, and header counts that match the body. Its --self-test injects one violation of each rule into a copy of the shipped corpus and requires every one to be caught. The two all-malicious corpora must keep being refused, pinned in the same file that requires the new one to pass, so loosening the guard to admit a corpus breaks the test saying the old ones stay out. * docs: bring the evidence pack's tally in step with the table readme_gates cross-checks three documents against the matrix and each phrases the count differently. The merge resolution knew one phrasing and missed the evidence pack's, so the gate failed on a sentence nobody had looked at -- which is the gate working, and the reason it exists. * chore: retrigger CI (no workflow run was created for the previous head) * chore: retrigger CI |
||
|
|
83306e5b6e |
fix: close the maturity plan's remaining clauses, and say what Stable means (#1105)
* fix(retro-hunt): two cross-tenant defects the E2E found, plus the two missing E2Es
Re-reading the plan against the tree found two of its sub-clauses never
landed: "one E2E that round-trips a tenant-scoped query through POST
/lake/sql", and "one E2E from the real threatintel feed through Kafka to
an alert". Both suites stopped one layer short of the seam.
The retro-hunt one found two real defects on its first run, and both are
invisible as the schema owner — they only appear under aisoc_app, the
role a deployment actually uses.
A tenant's rows were flushed under the next tenant's RLS context.
sweep_tenant deliberately does not commit, so its rows sat pending; the
next iteration rebound app.current_tenant_id, and the first query after
that triggered SQLAlchemy's autoflush, writing the previous tenant's rows
while the current tenant's context was active. RLS refused them,
correctly, and retro-hunt persisted nothing.
And one tenant's failure stopped the rest. The loop's own comment says it
must not. The failed flush left the session needing a rollback, so every
later tenant raised PendingRollbackError and was reported failed.
Both are closed by a SAVEPOINT per tenant, driven explicitly rather than
with `async with` — the context-manager form attempts its release outside
the greenlet the async driver runs in and raises MissingGreenlet.
Proven: reverting the savepoint and the per-tenant flush fails 5 of the
8 tests.
The lake E2E covers what rewrite_for_tenant alone cannot: the caller is
authenticated, the tenant comes from the token rather than an argument,
and errors map onto status codes an operator reads. It also asserts a
write is refused *and* that the table still holds its rows, because a
refusal that reached ClickHouse would be worse than an honest accept.
Reverting the rewrite to a pass-through fails 6 of 7.
Three fixture details that each cost a round, all of them the product
being right: the lake stores IPv4 in its IPv6-mapped form, so a bare
dotted quad raises CannotParseDomainError; retro-hunt is per-tenant
opt-in, so a tenant with no settings row is correctly skipped; and
re-running a sweep collides on uq_alerts_tenant_idempotency, because the
same indicator must not open a second alert. The suite now sweeps once,
which is also what one indicator arriving once looks like.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* feat(hunt): give the hunting agent its console and MCP callers (parity 6.1)
The plan's clause was "wire hunt/agent.py to the console and MCP so
something other than its own test imports it". The agents-service route
landed earlier; neither of the two surfaces a user actually reaches did.
POST /api/v1/agents/hunt proxies onto it, for the same reason
/cases/{id}/investigate is a proxy: the console and the MCP server both
reach AiSOC through this API, and the agents service is not published.
The tenant comes from the authenticated principal and is never read from
the body — a caller-supplied tenant on a route like this is the shape
that has gone wrong here before.
aisoc_run_hunt is the nineteenth MCP tool, read-only and annotated as
such: a hunt searches, it never acts. Its payload keeps `checked` and
`matches` apart in words as well as in the boolean, because the next
reader is a language model and a hunt that could not run is not a hunt
that found nothing.
On the console, the agent is now what happens when the ES|QL translator
cannot turn a question into a query. That path previously showed a toast
and left the analyst with an empty editor; it now asks the agent to plan
one, and surfaces the honest result — including the planner's refusals
rather than swallowing them, since a plan the validator would not run is
information.
Two gates did their job. The MCP suite pins the tool *set*, so a new tool
fails until the expected surface is updated. And published-count.test.ts
compares the advertised figure against the registry in both directions
across seven documents — README, the docs portal twice, SYSTEM_DESIGN,
REALITY_REPORT, the claim matrix and the landing-page brief — so 18
became 19 everywhere at once rather than drifting in six of them.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* test(playbooks): prove http and notify reach a socket, and fix two honesty defects
Parity 5.3's "steps that do something" had suites covering the SSRF
guard's decisions, the step models' bounds and the engine's control flow.
None proved a step ever left the process.
That distinction has a history here: _handle_block_ip and
_handle_isolate_host once returned {"simulated": True} and reached no
executor at all, under a comment claiming playbooks dispatched through
the actions service. A step returning a plausible dict is
indistinguishable from one that acted, and every test asserting on the
dict passes either way.
So this drives the real handlers against a real HTTPServer and asks the
only question that separates them: did a request arrive. Proven by
replacing the http handler's call with a plausible dict — 2 of 7 fail.
The guard is tested from both sides, because a step that always calls out
is as wrong as one that never does. The refusal tests assert the refusal
*and* that nothing arrived, since a refusal that still made the request
is a refusal in name only.
Two defects found along the way.
The module header said AISOC_SSRF_ALLOW_PRIVATE relaxes the
"private/loopback" check. It does not relax loopback, and
_is_disallowed_address's own docstring two hundred lines below has always
said so. The code is the correct half — a playbook that can reach
127.0.0.1 can reach every unauthenticated service on the host running the
engine — so the header is corrected rather than the behaviour. An
operator reading it would have set the flag and been confused.
And notify's non-delivery reason said "no url" whatever the cause,
including when a url *was* supplied and the channel simply had no sender.
That sends someone debugging a silent playbook to look for a missing
field sitting right in front of them. The reason now names the real case.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* docs: say what Stable now means, and what CI proves about each piece
The maturity table had been updated to read Stable on every row without
the README ever saying what changed. A reader seeing fifteen Stable rows
has no way to tell an earned label from a relabelled one, which is the
whole thing this work was about.
The README now states the bar in four lines: no path filter, the real
production path, real infrastructure, and a negative control proven by
breaking the thing and watching the check go red. It links the
definition rather than restating it.
That cost four lines of budget and the 250-line cap is genuinely binding,
so four were displaced: three passages that said the same thing twice
(secrets, `make stats`, the synthetic-data table's closing paragraph) and
one `make doctor` sentence that listed what it checks twice over.
The architecture doc gains the table a reader actually wants: for each
capability, the workflow that grades it and what breaking it looks like —
with the measured failure counts, so the negative controls are stated as
results rather than intentions. Two rows exist because the suite behind
them found a defect no offline test could, and the table says which.
Verified: all 19 external URLs return 200, every local path resolves,
every workflow named in the new table exists, and the attribution gate
passes over both the tree and the commits.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix: three CI findings on this branch
The OpenAPI spec and llms.txt are regenerated artefacts and this branch
changed both of their sources — a new route at POST /api/v1/agents/hunt,
and the README and architecture edits. Both gates were doing their job.
The retro-hunt E2E failed on psycopg2, which is not in any lockfile. That
is the same mistake this branch already fixed once: every live job now
installs from its service's own lock precisely so a hand-curated
dependency list cannot drift, and adding a second Postgres driver for two
INSERTs of test setup would have walked straight back into it. The
fixture uses asyncpg, which is already there.
Verified against real containers rather than assumed: Postgres with all
93 migrations, ClickHouse with the shipped DDL and Redpanda, running as
the aisoc_app runtime role — 8 of 8 pass.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix: restore the public HuntRequest schema, and triage two unpatchable advisories
Two failures, one mine and one not.
**The OpenAPI break was mine.** detection_rules.py already exports a
HuntRequest, and FastAPI resolves a name collision by qualifying *both*
models with their full module path. So adding a second HuntRequest in
agents.py deleted the plain HuntRequest schema and renamed the existing
one to app__api__v1__endpoints__detection_rules__HuntRequest — breaking
every generated SDK client, for a route that had not changed. Mine is now
AgentHuntRequest/AgentHuntResponse, which is clearer anyway, and the diff
reports 0 changes against base.
**The security-audit failure is a wave of newly-published advisories, and
main has the same exposure.** main's last security-audit run was green at
|
||
|
|
180b6cbb7e |
feat(maturity): define Stable, gate the table, and earn it for graph and UEBA (#1104)
* feat(maturity): define what Stable means, and gate the table on it The Project maturity table published a status for fifteen capabilities and nothing checked any of them. No definition of Stable, Beta or Alpha existed anywhere in the repository, no gate parsed the table, and the labels appeared in no other file. Promoting a capability was a one-line edit. That is the claim shape this project exists to refuse: Phase 1.1 retracted twelve published claims nothing checked, and the maturity table was the last large claim surface with no gate behind it. The definition was read off the four rows that already held Stable rather than invented, so no existing row had to be demoted to fit a standard written after the fact. Stable requires four properties: unconditionally graded, the real production path, a proven negative control, and real infrastructure. Evidence is a registry of exact sites rather than a search over the Tested column, for the reason check_profile_service_counts records about its own list: a gate that guesses which words are claims will either miss the one that matters or flag prose forever. It runs in both directions, so an entry for a row that is no longer Stable fails too. Two discriminators were wrong on the first attempt and are worth recording. Requiring a driver import produced a false negative on the strongest evidence in the repository: run_golden_pipeline.py drives a running stack over urllib, which is more real than any direct database connection, and imports no driver at all. Real-path is now two sharper questions, whether the test replaces the system under test and whether its job runs real infrastructure. And the capability key matches on a prefix, because a row's wording carries live counts and a gate that broke on a recount would teach people to edit the gate instead of the claim. Seven self-test cases, each perturbing the real tree rather than a fixture. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * docs(maturity): correct three rows that described coverage that does not exist Found by the gate added in the previous commit, which is the point of adding it before promoting anything. The playbooks row claimed 'live Postgres suspend/resume'. test_playbook_pause_resume.py drives _FakeRows and _FakePool and opens zero connections. I verified suspend and resume by hand against a container last session; no automated test does, and the Tested column reads as though CI does. The tuning row claimed 'live overlay read'. There is no live read anywhere: the nearest thing regex-parses 001_init.sql and compares column names against a regex over the module's own source, which is text against text. The connectors row said 'full' profile. connectors has no profiles key in docker-compose.yml at all and ships in CORE, per ADR-0007. That one was wrong in the product's favour, which is the direction worth catching. Each row now says what is actually true, and each will say something stronger when the live suite that earns it lands. Verified by marking all three Stable in turn and watching the gate refuse each. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(graph): prove tenant scoping in the production reader, and take the row Stable The graph had a live Neo4j test already, and it proved a tenant-scoped MATCH behaves. What it did not do was call anything a deployment runs: if graph_service.get_entity_neighbors stopped binding tenant_id tomorrow, that test would still pass. That is not hypothetical. The docstring on get_entity_neighbors records exactly that defect — it accepted tenant_id, never bound it, and any authenticated user could read another tenant's host, user or IOC node with all of its properties by naming the id. Its unit tests assert on Cypher text through a fake session, and a text assertion cannot notice a parameter missing from the call. So every query in the new suite comes from graph_service.py and runs through app.db.neo4j.get_session. The fixture writes through the production upserts rather than raw Cypher, so the write path is graded too. Two things went wrong while building it, and both are why the suite is worth having. The first version could not catch the defect it was written for. Removing the anchor's tenant predicate left all six tests green, because the neighbour predicate masked it: reading another tenant's host matched nothing either way. The fixture now attaches a global MITRE Technique to that host, which _scoped admits for every tenant, so the anchor is exercised on its own and the injected defect fails exactly one test. The second is a real robustness fix. get_blast_radius has a plain-Cypher fallback for a Neo4j without APOC, and it was unreachable on that condition: the empty-record branch only fires when the query succeeds and returns nothing, while a missing procedure raises. The shipped compose installs APOC so this never fired here, but anyone pointing AiSOC at a managed or hardened Neo4j got a 500 instead of the degraded answer. It now matches Neo4j's stable ProcedureNotFound code rather than prose; the first attempt looked for "was not registered" and the server says "registered for this database instance", so it missed the only condition it existed for. The workflow is its own rather than a step in isolation-live.yml, because Stable requires unconditional grading and that workflow is path-filtered. Widening a filter does not make a job unconditional, and one Neo4j container is cheap enough to run always. The gate also learned that docker run starts real infrastructure. It recognised only services:, make up and docker compose, and rejected a job that starts a real Neo4j: a false negative teaches people to work around a gate rather than trust it. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(ueba): score and persist against a real Postgres, and take the row Stable UEBA's 88 unit tests never open a connection. They are good tests of the arithmetic and structurally incapable of catching the defect that shipped: EntityBaseline declared peer_group_id, migration 0001 never created the column, and score_event raised on the first scoreable event. UEBA could not write an anomaly on any deployment, and every unit test passed throughout, because the ORM model and the tests agreed with each other and neither consulted the schema. The new suite applies the migrations the service ships and then drives ScoringService.score_event through a real session, reading the row back out of the table rather than trusting the return value. The schema comes from alembic, never from Base.metadata.create_all: building it from the model under test would paper straight over the defect this exists to catch. Proven against that exact defect. Dropping peer_group_id fails four of the five tests, and the workflow does precisely that as its negative control, then repairs the schema through the migration so the repair path is exercised too. A live migration round-trip already existed in integration.yml, but it is guarded on a changes filter whose path set lists only services/ueba/alembic/, so a change to scoring.py or kafka_consumer.py never triggered it. Stable requires unconditional grading, so this job carries no paths filter. One fixture detail worth recording. Training on an identical value produces a baseline with zero variance, which the scorer correctly declines to score by deviation — its own log says so and names automation and service accounts as the entities that converge there. The first version of the fixture did exactly that, so it was testing the unscoreable branch while claiming to test detection. The values now vary by a few percent, deterministically rather than seeded, so a failure reproduces from the test name alone. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * style: ruff Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(playbooks): prove the pause against real Postgres, and take the row Stable The offline suite is 15 tests against _FakeRows and _FakePool. It is a useful test of the module's logic and cannot prove the thing the feature is named for, because every property that matters belongs to the database. Surviving a restart is a claim about rows on disk, and a fake that lives in the test process cannot have any. Single resolution on a double-tap is enforced by a partial unique index in migration 081, which the fake re-implements in Python — a hand-written re-implementation of a constraint is the double-more-capable-than-the-real-thing shape that caused four of six defects in one live-QA pass. The new suite drives the real module against a real pool: a pause is a row, the context survives the jsonb round trip, a module reload still finds it, another tenant cannot find or resolve it, and expiry records an outcome while a pause inside its deadline is left alone. The negative control drops the partial unique index and requires the suite to go red. Measured: one test fails, the one asserting the database refuses a second waiting pause. Its sibling keeps passing, and that is correct — single resolution on resolve() is enforced by the atomic UPDATE WHERE status = 'waiting', which is a different mechanism. Two properties, two tests; a control that broke both would be telling us less. Two things learned applying the migration in CI. 081 is not independent of its chain: it calls current_tenant_id(), which 002 defines, so applying it alone fails. And the table has a real foreign key to tenants, which the fake did not — a pause referencing a tenant that does not exist was perfectly acceptable to it. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(tuning): prove the overlay against real Postgres, and take the row Stable A live read matters more here than almost anywhere, because OverlayCache fails soft. A broken read returns None, the caller turns that into the empty overlay, and the engine suppresses nothing — which is indistinguishable from a tenant who has configured no tuning at all. That is not hypothetical. The query selected rule_id and updated_by from detection_rules, which has neither. Every execution raised, the handler logged a warning, and the overlay loaded nothing on every deployment while thirty unit tests passed against a fake that answered for whatever columns it was asked about. The offline suite gained a schema check afterwards, but it regex-parses the migration and compares it to a regex over the module's own source: text against text, never a connection. This suite opens one. Tuning is written the way the console writes it, and the real engine is asked what it fires. The negative control re-injects the original defect rather than an invented one. Measured: six of the ten tests fail with those two columns back. Two things the fixture had to get right. The whole migration chain is applied in order, not the three that create the table: detection_rules gains columns across later migrations, rule_language among them, so a cherry-picked subset builds a schema no deployment has. And the det-* identifier lives in provenance->>'source_id' per migration 036, which is the mapping the original query got wrong. One test documents the fail-soft itself, so the behaviour that makes this file necessary is stated rather than implied. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * fix(maturity): connect the live suites as the runtime role, not the superuser check_runtime_db_role caught all three new workflows connecting as the owner, and it was right in a way that matters for exactly these tests: a superuser ignores every RLS policy in the schema, even under FORCE ROW LEVEL SECURITY. Every cross-tenant assertion in these suites could have been passing on the module's own predicate while RLS was never exercised at all. All three now follow the convention integration.yml already documents: the owner runs the migrations, and the suite connects as aisoc_app, which is DML-only and is the role the policies apply to. Both suites re-run green as that role, so the predicates and the policies agree. Migration 002 and UEBA's 0003 create the runtime role with a placeholder password, so each workflow sets a real one after the migrations run. Also fixes a mypy attr-defined on the module-reload fixture, where importlib.reload returns ModuleType and the checker cannot see the module-level _pool the test patches deliberately. The attribution gate was failing on a footer appended to the pull-request body rather than on anything in the commits; the body is corrected. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(scim): drive the real app against real Postgres, and take the row Stable The offline suite is 40 good tests whose harness cannot certify the capability, for two reasons. It runs on sqlite+aiosqlite with @compiles shims translating JSONB, UUID, INET and ARRAY into something SQLite accepts. Those four types are where Postgres and SQLite disagree most, and a shim that makes a column accept a value is not evidence the real column stores or queries it — this repository has shipped exactly that defect before. And it mounts the router on its own bare FastAPI(), so the production middleware, exception handlers and dependency graph are not what the assertions run through. The new suite uses app.main:create_application against real Postgres, as the aisoc_app runtime role so RLS genuinely applies, with tokens minted by the production minter. The negative control removes the tenant predicate from the Users list and requires the suite to go red: one test fails, the one asserting a SCIM token sees only its own tenant. Without it, "the user I created is listed" would pass equally well against a surface that returns everything to everyone. check_scim_contract and check_whitelabel_metering move here from isolation.yml, which is path-filtered. A static gate behind a filter does not satisfy the unconditional property. Two findings worth recording. The suite's teardown deleting its tenants failed because audit_log rows are immutable by design — a trigger raises on DELETE — which is correct behaviour an audit trail should have, found by trying. And building the application per test left engines bound to closed event loops, so the application is built once per module while each test still gets its own tenants. The gate learned something too. It flagged this very file for using sqlite+aiosqlite, because the string appears in the docstring explaining why the offline harness is inadequate. The interceptor check now parses the module and skips docstrings and comments rather than grepping prose — the same mistake as searching for a socket option in a function whose docstring exists to say why it must not be set. And its first self-test case hardcoded a capability that this work later promoted, so the injection became a no-op and the case silently stopped testing anything. It now picks a still-Beta row out of the table, and reports honestly if none is left. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(connectors): drive the real scheduler, and take the row Stable The defect this suite exists for is the reason connecting a source never pulled data on any deployment: reload_jobs added every poll job with next_run_time=None, which APScheduler 3.x registers as PAUSED. The scheduler started, the job list looked right, last_sync stayed null for every instance, and nothing logged an error — nothing had gone wrong, exactly. The jobs were never going to run. No mock catches that. A test asserting add_job was called with the right arguments passes whether or not APScheduler will ever fire it; only a real AsyncIOScheduler knows what next_run_time=None means. The contract tests this row was certified by gate the shape a connector must satisfy, which is a different and much weaker claim. So the suite starts the real ConnectorScheduler, with a real connector row in real Postgres and real HTTP servers standing in for the vendor and for ingest. The stubs are sockets rather than patched methods, so the connector's own client and the real IngestClient are both on the path. Five assertions: a job exists, it is not paused, an event reaches ingest, it carries its tenant header, and last_sync is written. The negative control re-injects next_run_time=None. Measured: four of the five fail. Three things the fixtures had to get right, each of which would have failed for a reason unrelated to the scheduler. The column is is_enabled, not status or enabled, and fetch_enabled_connectors filters on it. OktaConnector takes domain and api_token, so passing base_url made the scheduler log bad_config and skip the poll — correct of it, and the reason the field names here come from the connector rather than from a convention. And the connector is module-scoped: the stub ingest accumulates everything it receives, so a connector per test had a later test comparing accumulated events against a tenant that had only just been created. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * fix(maturity): three CI findings from the first run of the new live jobs Each is a real gap the local runs could not show, which is the argument for the jobs existing. SCIM needed python-multipart. create_application() mounts routes declaring Form parameters for branding asset upload, and FastAPI resolves those at import, so the whole application fails to build without it. The offline suite never hit this because it mounts the SCIM router alone — the same harness difference this work replaced. UEBA needed the runtime role to exist. Its migration 0003 GRANTs to aisoc_app but does not create it: the role comes from the API's 002_rls.sql, which a standalone UEBA database never runs. A deployment sharing one database already has it. CodeQL caught an `if True:` left in the SCIM fixture from restructuring it onto a single engine — py/constant-conditional-expression, alert #982. Removed rather than suppressed; it was dead scaffolding, not a construct worth defending. All four other new live jobs passed on the first run: graph, playbook pause, tenant tuning and the connector scheduler. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(actions): prove governance permits and refuses, and take the row Stable What Stable asserts for a governed capability is not that the product acts on its own. Response actions require a human approver by design. What it asserts is that the machinery is proven, including that it correctly refuses — so the refusing half of this suite matters more than the executing half. The vendor is a real socket rather than a mock, and the reason is specific. Simulation mode never constructs the client, so a wrong argument name is invisible until a live call: SearchSIEMExecutor passed max_results when the client takes max_count, and CreateNotableEventExecutor passed title/description/fields when it takes event_data. Every live call raised TypeError and every test passed. A mock accepts whatever it is handed; a real server simply never gets called when the client fails to construct. Building this reproduced the vacuous-pass shape twice, which is the part worth recording. The first version passed all seven tests with governance never consulted at all. The registry is empty until register_builtin_executors runs, as main.py does at startup, so every dispatch answered executor_not_found and returned failed — and "not executed" is just as true of an action that never reached the gate as of one the gate refused. With the 73 builtins registered it still passed for the wrong reason: without credentials in the exact shapes the client factories read, every executor answers simulated. The credentials now come from the executors' own _credential_keys rather than from a convention. And the negative control had to be sharpened twice. Removing only the approval branch left the suite green, because the DRY_RUN downgrade still held the action. It now removes all three branches — BLOCKED, QUEUED_APPROVAL and the DRY_RUN downgrade — and the refused isolate_host actually attempts its CrowdStrike OAuth call against the stub, failing the assertion that a refusal never reaches the vendor. Verified by extracting the workflow's own injection script and running it. The maturity gate gained a narrow, verified category for this: a suite whose real infrastructure is a socket it owns rather than a container. For this question a socket is better evidence, because "did anything leave the process" is answered more directly by a handler that records every request than by a container. It is checked rather than trusted — the gate requires the named test to actually bind an HTTPServer, with a self-test case proving the flag cannot be claimed by a suite that binds none. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * docs(actions): correct two reachability entries, one of which was wrong The plan asked me to resolve these two so the allowlist would shrink. It does not shrink, and the reason is worth more than the number would have been. I deleted both modules and their tests, and immediately broke two gates. autonomy_evidence_rules.py is not unwired at all: it is the source of truth for what counts as a graded disposition, and two gates read it without importing it — check_replay_contract_parity.py compares its GRADED_DISPOSITIONS, ABSTENTION_VERDICTS and MALICIOUS spellings against the benchmark's, and sync_vendored_autonomy_evidence.py --check byte-compares the API's vendored copy, because a safety control defined twice is off in whichever copy is more generous. An import-graph checker cannot see either consumer. Its entry now says so and is permanent. unified_autonomy.py is genuinely off the production path, and parity 2.1 already decided against it: the per-tenant closure policy in migration 078 is what run_auto_triage reads, and approval_matrix.evaluate_contract is what dispatcher.py calls. Its entry now records that it is superseded rather than pending a decision. It stays on disk. A third authority on "may this execute without a human" is a safety question rather than a tidiness one, and I had just finished demonstrating that the import graph understates what depends on a module in this directory. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(lake): run against the shipped DDL, and take the row Stable The existing live ClickHouse case writes its own CREATE TABLE aisoc.raw_events, a hand-maintained subset of what services/api/clickhouse/001_init.sql creates. A test that builds its own schema cannot notice the real one has drifted, which is the same shape as asserting on a producer against a copy of itself. Writing this proved the point on the first run: the suite inserted `message` and `raw_event`, and the shipped table has neither — the payload columns are raw_payload and ocsf_json. A hand-written schema would have accepted both happily. The new suite executes 001_init.sql verbatim, then drives rewrite_for_tenant, which is what stands between an operator's SQL and every other tenant's events. Two properties beyond the happy path: an operator naming another tenant's id still gets only their own rows, so the injected predicate conjoins rather than replaces; and SQL the parser cannot handle is refused rather than passed through, since returning the original would hand an unfiltered query to the lake. The negative control makes rewrite_for_tenant a pass-through. Measured: three of six fail, including the fail-closed test — which is why that one belongs in the set, since a pass-through is exactly what "return the original when the rewrite cannot be applied" means. No paths filter. The previous arrangement filtered on a set that omitted lake_hunt.py, lake_rate_limit.py and endpoints/lake.py, so editing the lake's own query surface never re-graded it. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(retro-hunt): grade the consumer with the flag on, and take the row Stable The sweep already cleared the hardest property: its live suite re-implements nothing, driving the production writer and the production sweep against a real ClickHouse. The consumer had no coverage at all, and the path filter omitted retro_hunt_consumer.py entirely — so the loop that decides whether a fault is worth retrying was never graded by anything. That gap has shipped here before in its worst form. UEBA's Kafka consumer had no except at all: a handler exception exited the async for, finally stopped the consumer, and the container sat at running with restarts 0 and /health returning 200, permanently, with the exception never logged. A consumer detached from its topic while health says 200 is indistinguishable from an idle one. The new suite produces three events to a real broker — well-formed, undecodable, empty — and asserts the parser tells them apart, that a parsed event becomes a usable indicator, and that a permanent fault has its own type rather than being plain Exception. Poison is a third class, distinct from transient and permanent: skip the message, keep the loop. RETRO_HUNT_ENABLED stays default-False, and the reasoning is now written where an operator reads the flag. A retro-hunt replays every new indicator against a tenant's entire history, so arming it on upgrade would change what a deployment does to its own lake without anyone asking — the same reasoning as the retention purge worker below it. The definition gained the matching principle, with the condition that makes it honest rather than an excuse: a flag's default is an operational choice like a compose profile, but the gate must grade the capability with the flag ON. A default-off feature whose tests also run with it off is not opt-in, it is untested. The workflow sets it true, and that line is load-bearing. Negative control: make the parser accept undecodable bytes. Two tests fail. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * fix(playbooks): ship the 62-playbook pack inside the agents image (parity 5.3) The http and notify steps already act — they make real calls through the SSRF guard — and the osquery step exists. The outstanding half of 5.3 was packaging, and it was worse than unfinished. playbooks/packs/v1/ holds 62 production playbooks and the agents image shipped **zero** of them. The Dockerfile's build context is services/agents and a context cannot reach outside itself, so PlaybookStore's walk-up resolution found nothing: in a container it resolves /playbooks/packs/v1, which does not exist. Nothing said so. The loader's pack branch is guarded by `if self._pack_root.exists()`, which makes an absent pack indistinguishable from an empty one — a deployment's playbook library was 62 entries shorter than the repository's, silently. Measured both ways against a container-shaped tree: before, the path resolves outside the image and yields 0 playbooks; after, 62. The fix is the pattern already used for services/fusion's 2,603-rule compiled ruleset: commit the data inside the package, where the existing COPY app/ ./app/ picks it up. Two copies drift, so sync_vendored_playbook_packs.py --check compares them in both directions — a file added to the vendored copy and not to the source fails too, because a one-directional gate passes while drift accumulates in the direction things actually change. Three regression tests guard the shape rather than the symptom: the pack resolves inside the package, it is not empty, and the store actually parses it. Resolving a path and loading what is at it are different claims, and the count is a floor so adding a playbook does not fail the build while removing the pack still does. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(hunt): wire the agent and read tenant data, taking the last Alpha row Stable Parity 6.1, both halves. The NL hunting agent was complete, tested, and its only importer repo-wide was its own test — a passing test on a function nothing calls is indistinguishable from a working feature until someone traces the call graph. It now has a route: POST /hunt on the agents service, going through safe_ainvoke so the LLM input contract applies exactly as it does at every other call site. The model never writes a query; plan_hunt asks for a plan, validates every attempt, and the refusals are returned rather than swallowed, because "the model proposed something I would not run" is information an analyst should see. The scheduler is the half that mattered more. Its only implemented telemetry provider was `synthetic`, so every scheduled hunt on every deployment ran against a fixture corpus: findings about events no customer had, and nothing about the events they did. `ingest` existed as a name and returned an empty list. The new lake provider reads the tenant's own recorded events out of ClickHouse and is now the default. Two rules shape it, both about honesty rather than correctness. An unreachable lake returns nothing and says so — there is no fallback to the fixture, because a hunt that quietly reports synthetic findings is worse than one reporting nothing, since an operator cannot tell them apart and one is fabricated data presented as their own estate. And the tenant predicate is bound, not formatted. Two tests assert exactly that: the reader raises when the lake is down, and the scheduler turns that into an empty run rather than the corpus. Two things the live run surfaced. source_ip and dest_ip are IPv6 columns and clickhouse-driver raises AddressValueError decoding the zero-length packed address an unset column yields — a row with no IP is the common case for identity and SaaS events, so the natural read crashed on ordinary data; the query casts with IPv6NumToString. And the nested vendor payload is flattened *under* the canonical fields rather than over them, so a vendor key cannot shadow `host` or `user`. The hunt tests live in their own file because both services call their package `app`, and running from services/api resolves app.hunt to nothing. Both allowlist entries removed from check_module_reachability.py. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * feat(triage): grade the agent per commit and the ledger live, taking the last row Stable Two halves, and the agent one closes what REALITY_REPORT calls the hard ceiling on the project's credibility: no pull request had ever been graded on agent behaviour. mitre_accuracy is an offline keyword extractor, and both jobs that dispatch the real LangGraph ran only on a schedule or on demand. live-agent-smoke now runs on every pull request. It is deliberately small — one incident, the smallest bundled model — and asks one question: did the agent place a real LLM call and come back with something schema-valid. It is not an accuracy measurement; the scheduled deep run is that. The distinction matters because the harness has been fooled before. With the model pins unset every agent caught its provider error and used its deterministic fallback, and the run reported mode: live with a groundedness of 0.8050 at 0.11s per investigation — flattering, and faster than a network round trip. --wet-require-live could not see it because records existed and the stack had imported. llm_calls_placed is what closes that hole, and this job asserts on it directly, reading it from under groundedness where the harness writes it. The ledger's offline test drives a _FakeConn and opens no connection. It is a reasonable test of branching and it cannot prove the three things the ledger is for: that the rows exist, that RLS applies, and that a foreign key refuses an event for a run nobody started. The live suite proves all three, and its signatures came from the module rather than from a guess — the first version called start_run with arguments it does not take and queried run_id on a table keyed by id. No hosted provider has ever been exercised. That stays a separate, unmade claim, and it is written into the row rather than left implied. The gate's own self-test needed fixing twice for the same reason. It first hardcoded a capability that later earned promotion, so the injection became a no-op; then every row became Stable and the version that promoted a Beta row had nothing to perturb. It now works from whichever end has material — promote an unearned row, or take an earned row's evidence away — because both exercise the rule that a Stable row without evidence is refused. Every capability row in the maturity table is now Stable, and each one names evidence the gate verifies. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * fix(maturity): guard the live suites, close a file handle, and complete four dep lists Five CI findings from the first full run, each real. The offline isolation job collects tests/isolation/ with no stores running. The live suites skipped in their fixtures, so any test not taking one ran anyway — the lake's fail-closed test and both refuse-to-fabricate tests failed there, which is a failure about the harness reported against a capability. Each suite now skips as a module when its store is not configured. Four jobs were one import short. The pattern is the same every time: a suite that drives the real service pulls in the real service's whole import chain, not just the file under test. The ledger suite needs langgraph because app.investigator imports it; the SCIM suite needs neo4j, redis and clickhouse-driver because create_application mounts every router. CodeQL caught an open() with no context manager in the lake fixture, alert #983. Replaced with Path.read_text rather than suppressed. And mypy caught `unbacked` bound to a list of rows in one branch of the self-test and to a bool in the other — exactly what a type checker is for. The second has its own name now. Also reconciles PARITY_PROGRESS.md. Fifteen items are ticked, each one documented as shipped in that file's own per-phase sections or closed by this work and said so in the commit. Thirty-two stay open, several of them partial, because a partial item reads better unticked than ticked with a footnote. A note records the rule so the next person does not have to infer it. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * fix(maturity): install live jobs from each service's lockfile Four rounds of "ModuleNotFoundError: no module named X" went by before I stopped curating pip lists by hand. A suite that drives the real service pulls in the real service's whole import chain — the ledger suite needs langgraph because app.investigator imports it, the SCIM suite needs neo4j, redis and clickhouse-driver because create_application mounts every router — and guessing that set one package at a time is the anti-pattern this repository already removed from its images. A dependency set that differs from the lock means the job tests software nobody ships. Every live job now runs `poetry install` against its own service, with test-only extras added on top. The lake job installs two, because one of its suites drives app.hunt from services/agents. The governed-actions suite needed a different guard: its infrastructure is a socket it owns, so there is no env var to key on. It now skips when app.live_actions is not importable — and `find_spec` raises ModuleNotFoundError when the parent package is absent entirely rather than returning None, so the obvious `is not None` check turned a skip into the collection error it was written to prevent. Verified both ways: the suite skips from the repo root and passes from services/actions. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * fix(maturity): apply the whole migration chain in the pause + ledger job It started as a cherry-picked 001/002/081 — enough for the pause table, with 002 included because 081's RLS policy calls current_tenant_id() and a migration applied alone does not have it. Then the ledger suite joined the job and failed on `relation "investigation_runs" does not exist`, because its tables arrive later in the chain. A cherry-picked subset builds a schema no deployment has, which is the opposite of the point. Applying everything costs seconds and cannot be wrong in this direction. Verified locally against a container carrying all 93 migrations: both suites pass, 16 tests. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * fix(make): print the port the console was actually published on Found in a clean-room install. scripts/resolve_port_conflicts.py moves a published port when the host already holds it, and on that machine 3000 was taken: the console served happily on 15000 and `make up` printed http://localhost:3000. A first-run URL that refuses the connection is a first impression of a product that does not start, from a stack that is entirely healthy. console_url now reads the port out of docker-compose.ports.yml, which is what compose acted on — re-probing would answer a different question and could disagree. An explicit AISOC_CONSOLE_URL still wins, so a reverse-proxied deployment is unaffected. The expression is fragile in a way worth pinning, and two attempts produced `*** unterminated call to function 'shell'` rather than a wrong answer: a sed capture group's \( \) unbalances the parentheses make counts, and a literal # anywhere in the command starts a make comment that swallows the closing paren. Three tests cover the default, the remap and the override, and they fail the build if the Makefile stops parsing — which a test checking only the value would not have caught. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> --------- Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> |
||
|
|
80bad222b0 |
feat(eval): set the groundedness floor from the runs, and gate on it (#1008)
The floor exists now because there are runs to derive one from. Before this series `live-agent-eval.yml` had never produced a measurement — its first dispatch failed in 92 seconds on an agent class that exists nowhere in `services/agents` — so the two claim-matrix rows resting on a floor had no distribution, and any number written into them would have been invented. What the runs say. The four agents decode greedily at temperature 0, so the measurement is a point mass on a fixed machine: seven local runs over the 10-incident prefix returned 0.5561 to four decimal places, and sixteen over the 20-incident prefix returned 0.5364. The only variation observed is across machines, and it is not small: two GitHub-runner runs of the same slice returned 0.5821 and 0.5329, a spread of 0.0492, because a quantised model decoding greedily on a different kernel diverges at the margins. The floor is 0.40 on the 10-incident slice, set from that spread rather than from the local stability, which would have been the misleading number to use. It sits 0.1329 below the lowest run observed anywhere and about 2.7 times the cross-runner spread, deliberately conservative because the runner-side sample is only two runs. It still fails anything a quarter worse than today. `scripts/check_live_agent_floor.py` asserts it, and refuses four ways a green run could mean nothing: * a report tagged anything but `mode: live`, because the harness degrades to deterministic substrate numbers and a floor asserted against those would certify a model that was never called; * a report recording zero LLM calls placed. This is not hypothetical. A sample run whose workflow set a model env var nothing reads sent every agent at a gateway alias the local server had never heard of; every call failed, every agent used its deterministic fallback, and the report came back tagged `live` with a groundedness of 0.8050 at 0.11 seconds per investigation — faster than a network round trip, and flattering. `--wet-require-live` could not see that shape, and now does: the harness raises when no call was placed across the run, and the report carries `llm_calls_placed` beside the mean so a reader can tell the model's output from the fallback's; * fewer incidents scored than the floor was derived over, because a mean over a smaller sample is a different measurement; * a different model, unless `--allow-model` says so deliberately. The floor lives in `services/agents/tests/eval_data/live_agent_floor.json` with the runs behind it — model, host, slice, run count, and every observed mean. The loader refuses a declaration missing its provenance, one with no observations, and one whose floor sits above the lowest run it cites, which would red every run from the day it landed. The workflow's slice default drops from 20 to 10 and its timeout rises to 90 minutes. Both are measured: 20 incidents overran a 60-minute job, and a timeout reports as `cancelled` rather than `failed`, so a weekly run that measured nothing would not have looked like a failure. Every number here is a locally-served `qwen2.5:0.5b` over a 10-incident slice. No hosted provider was involved in any of it, and this floor describes none. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> |
||
|
|
6a96ed3c00 |
feat(security): watch a running container, not just its declared defaults (#1000)
`tests/test_no_default_egress.py` names the gap it leaves in as many words:
Neither this nor the static gate says anything about what the *running
containers* do. That needs egress-blocked integration, which the Helm
chart's default-deny NetworkPolicy addresses at deploy time and nothing
addresses in CI.
A declaration can be right and an import path clean while the built image
reaches out anyway — a base image's entrypoint, a package that phones home on
first use, a scheduler thread that only starts under the real command, a
client constructed after startup rather than during it. None of those are
visible to either existing half, because neither ever runs the container.
`scripts/check_container_egress.py` runs it. Images built from the commit
under test start on a docker network created with `--internal`, so there is
no route off the host whatever they try, with a DNS sinkhole as their only
resolver. Every name asked for is recorded and classified with the same
public/private predicate the services enforce air-gap policy with.
Observation, not only prevention. A block alone cannot tell "made no call"
apart from "made a call that failed", and the distinction is the whole point.
Two controls, because zero observations is what a correct run and a blind
probe both look like — and that is not hypothetical here. The API's
unconfigured startup dials Postgres on loopback, which needs no name
resolution, so a correct run legitimately records zero lookups:
* `--negative-control` runs a canary with the *identical* network and `--dns`
flags a probed container gets and requires the sinkhole to record its
lookup. It tests the property actually in doubt — that a container on this
network resolves through this sinkhole — rather than whether some service
happens to dial a configured URL during startup, which is a weaker claim.
* A service container that emitted no log line and asked for no name is a
finding, not a pass. Whatever that proves, it is not that the image
declines to phone home.
The workflow also shows the gate going red against an image that does dial
out, the way `golden-pipeline.yml` proves itself by stopping fusion.
Measured against the real images built from this tree:
canary observed egress-control.example.com
api (aisoc-core-api) 0 public, 0 internal, 14 log line(s)
leaky (deliberate) 1 public name in 20s: telemetry.example.net -> exit 1
containment a direct dial to a public IP is blocked by --internal
Stated limits, in the module docstring rather than implied: a dial straight
to a public IP literal asks no DNS, so it is prevented by the `--internal`
network and statically checked by `check_default_egress.py` but not observed
here; the window is bounded and printed; and only the services named on the
command line are covered, with an empty set refused rather than passed.
The gate keeps its own copy of the private-suffix tuple because it runs where
no service package is importable, and a test parses the service module's own
tuple and requires them equal — two copies of a security predicate that
nothing compares are two predicates.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
|
||
|
|
2231eb6d9d |
fix(security): close the version-drift arm for the one scanner it skipped (#999)
The ratchet's version-drift arm read:
if version and measured_with and version != measured_with:
and `_tfsec_counts` returned `None` for the version, because tfsec's JSON
report carries no version field. The `version and` conjunction turned that
`None` into a pass, so the `measured_with: "1.28.13"` sitting in
`.security/allowlist.yml` was never compared against anything. A tfsec bump
that left the finding counts identical went through unnoticed — which is the
whole failure the arm exists to prevent, on the one scanner of the three
whose counts nothing else could vouch for.
Nothing in the tree said so. The `None` was bare and unexplained, while the
allow-list header states flatly that `measured_with` "is compared against the
version the report declares", and the claim-to-gate matrix says the ratchet
fails "on a scanner version that is not the one the ceiling was measured
with" for all three scanners without qualification.
Three changes, the first of which is the structural one:
* **A version that could not be established is no longer a version that
matches.** A ceiling declaring `measured_with` against a report whose
version is unknown now fails and says what to pass. This is general: any
future scanner whose report omits a version fails loudly rather than
quietly skipping the comparison.
* **The running version comes from the binary's own `--version`.** The
workflow already ran `/tmp/tfsec --version` and threw the output away. It
now captures it, hard-fails when it disagrees with the pinned `VERSION`
exactly as the gitleaks job has always done, and passes it to the ratchet
as `--tool-version`. The binary's own answer is the robust source: a pinned
download URL says what was asked for, and a cached or substituted binary
would still satisfy it. When a report carries a version *and* a
`--tool-version` is supplied, the two must agree — checked in both
directions, because two sources for one fact that never meet will drift.
* **`_versions_pinned` can now see a curled binary's pin.** It only matched
`pip install name==X.Y.Z`, so tfsec was invisible to it and printed
`workflow pin=—`. That mattered beyond cosmetics:
`test_every_ceiling_pins_the_version_the_workflow_installs` iterates over
what that function returns, so the scanner it could not see was silently
exempt from the cross-check keeping the pin and the ceiling honest. It now
binds a shell `VERSION=` assignment to the enclosing `- name: Install <tool>`
step, so the pin is attributed to the right tool rather than to whichever
assignment came last.
Proven against the pre-fix tree at `origin/main`, same inputs:
PRE-FIX missing version -> 0 problem(s) (SILENT PASS)
_versions_pinned -> {semgrep, checkov}; tfsec absent
POST-FIX missing version -> 1 problem(s)
_versions_pinned -> {semgrep, checkov, tfsec}; tfsec present
`--list` on the real tree goes from `tfsec ... workflow pin=—` to
`tfsec ... workflow pin=1.28.13`. Five tests added; 35 pass.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
|
||
|
|
d7c1cf82eb |
docs(audit): the seventh lettered deferral nobody was tracking (#989)
`docs/audit/DEFERRED_SUBPHASES.md` exists because six commitments had their scope recorded only by a filename pointing at a gitignored file that was never committed. The audit that wrote it read `ROADMAP.md` and stopped there, so two more lettered deferrals stayed invisible: 6b in `docs/decisions/0005-storage-consolidation.md` and 8b in `services/agents/app/llm/prompt_registry.py`, both still pointing at the tracker that does not exist. Both are open and both now have a section. 6b: the storage cost model has a drift gate and no consumer — neither `cost_dashboard.py`, the costs page nor the managed-instance billing section mentions storage. 8b: the prompt registry holds three prompts, one module reads it, and ten modules under `services/agents/app/` still declare their own `_SYSTEM_PROMPT`. Re-verifying the other statuses against the tree closed one and corrected two. 11b closed — `scripts/check_sdk_surface.py` is the gate that section described, recorded with what it still does not prove. 9b's durable approval-timer table landed in `062_approval_timers.sql`, so the remaining gap is console-raised approvals, which nothing expires. 10b's checkpoint durability landed with one adopter of 84 connectors. 3.5+, 5b and 7b+ were re-checked and are unchanged. `scripts/check_deferral_tracker.py` derives the set of deferrals from the tracked tree in both directions and fails any file still pointing a reader at the tracker that was never committed. Proven against `origin/main`, where it exits 1 naming 6b, 8b and both dangling pointers. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> |
||
|
|
f55be02ff6 |
feat(gates): give the scanner allow-list a reader and the scanners a ratchet (#987)
* feat(gates): give the scanner allow-list a reader and the scanners a ratchet security.yml described Semgrep, checkov and tfsec as "report-and-ratchet" and named .security/allowlist.yml as where the triaged baseline lives. Neither half was true. All three ran under continue-on-error, printed a number, and nothing compared that number to anything, so a change adding twenty findings and one removing twenty produced the same green tick. And a repository-wide search for the allow-list's path returned two documents talking about it and not one line of code that opens it — its header declares a schema, requires a reason and an expiry on every entry, and says expired entries fail CI, enforced by nothing. check_gate_coverage.py would have caught this had the orphan been a script; it inventories scripts/ against the workflows. A control file in YAML with no caller is the same defect one file type over. scripts/check_scanner_ratchet.py is that reader. The counts move out of a workflow comment and into the allow-list as ceilings, and a run that disagrees with them fails in every direction that matters: more findings than the ceiling is a regression; fewer also fails, with the measured number in the message, so the ceiling comes down in the same change that removes the finding rather than leaving room for it to drift back up; zero against a non-zero ceiling is a scanner that did not run, which is the shape that turned a 404'd Trivy pin into a green tick scanning nothing. Coverage is checked in both directions, because a ceiling left behind by a deleted scanner guards nothing while still looking like a control. The three scanners are pinned exactly. For a ratchet the scanner version is the behaviour: an unpinned install re-baselines the count on upstream's release schedule, which is indistinguishable from a change in this tree. The gate compares the version the report declares against the one the ceiling records and refuses to compare across them. tfsec moves to a pinned binary for the two reasons the Trivy job already records — the action's version tags proved unreliable, and the ratchet needs the report on disk. The allow-list is read by a strict parser over the documented subset rather than PyYAML, because the always-run half of this gate lives in a job that installs ruff and mypy and nothing else; a test asserts that parser agrees with yaml.safe_load on the real file. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * fix(security): re-measure the ceilings and split the two IaC scanners The first CI run of the ratchet did its job on its first try: semgrep came back 101 findings (40 at ERROR) against the 92/35 the workflow header had published, and checkov came back 219 against 91. Neither number was a regression introduced here. The semgrep figure was simply old, and the checkov one had always been the terraform total quoted for a job that also scanned infra/helm. A count nothing compares to anything drifts, and nobody finds out — which is what this gate exists to stop, so the measured numbers replace the remembered ones. tfsec produced no number at all, because it shared a job with checkov and the ratchet step is hard: the first scanner to breach its ceiling ended the job before the second one ran. A gate that can stop another gate from measuring reports on whichever half happened to run first, so the two scanners now have a job each. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> --------- Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> |
||
|
|
155ee3918e |
fix(enrichment): point the two remaining callers at the service that serves it (#977)
`/api/v1/enrichment/lookup` does not exist. Measured against a running stack,
and absent from the OpenAPI document:
/api/v1/enrichment/lookup -> 404
/api/v1/enrichment/bulk -> 404
PR #965 fixed the single-IOC console path. Two callers still targeted it.
Repointed, not built
--------------------
Checked first: `services/enrichment` serves `POST /enrich` and
`POST /enrich/bulk` on port 8082, and two clients in `services/agents`
already call it — `app/tools/enrichment.py` and `app/investigator/tools.py`.
Adding an API proxy would have been a third path to the same service, so the
callers move instead.
**`playbook/engine.py::_handle_enrich`** posted `{"ioc": …}` to
`{API_URL}/api/v1/enrichment/lookup`. Both halves were wrong: the path is not
served, and the service that is reads `{"value": …, "ioc_type": …}`. It now
posts to `{ENRICHMENT_SERVICE_URL}/enrich` with the fields that service
reads.
A failure now raises `PermanentStepFailure` naming the indicator and saying
the failure says nothing about it. Enrichment is a `full`-profile service, so
on a CORE deployment this step *will* fail, and "the enrichment service is
not running" must not reach a playbook author as "nothing is known about this
indicator". A step with no indicator is a skip and makes no request at all.
**`api.ts::bulkLookup`** targeted `/api/v1/enrichment/bulk` with a body
(`{ iocs: [...] }`) that neither the API nor the enrichment service reads,
and had **zero callers**. Deleted rather than repointed: an exported helper
aimed at a route that does not exist is a loaded gun, because whoever wires
it up first gets a rejected promise and, following the shape `lookup` used to
have, renders it as a clean verdict. A bulk lookup can be written against
`/api/v1/threat-intel/indicators` when something needs one, and the comment
left in its place says so.
The console rewrites stay and now point somewhere real. `ENRICHMENT_HOST`
fell back to `http://localhost:8083`, which inside the web container is the
console itself — a rewrite that answers from the wrong server rather than
failing. It is `http://enrichment:8082` now, the Compose service and its
port, and `ENRICHMENT_URL` is already in
`scripts/resolve-runtime-routes.mjs`, so a pulled image can be pointed
elsewhere without a rebuild.
The shape, gated
----------------
`scripts/check_failure_is_not_a_verdict.py` flags a `catch`, a rejection
handler or a `??` fallback that assigns a **verdict word** — clean, safe,
benign, `malicious: false`. Those are claims about the subject, and a failure
knows nothing about the subject. Setting an error state, rendering "not
checked", rethrowing, logging or assigning an empty list are not flagged: an
empty list is a claim about the store, not about the indicator.
Run against a detached worktree at
|
||
|
|
c7ed1437e7 |
feat(gates): hold the investigation ledger's replay contract in both directions (#973)
The claim matrix row for "Investigation Ledger stores every step" names `ci.yml :: api tests (audit_hash, audit immutability)` as its gate. That gate covers a different table: `test_audit_hash.py` tests the hash chain over `audit_log`, written by the API's audit middleware. The ledger is `investigation_events`, created by migration 008 and written by `services/agents/app/investigator/ledger.py` over raw asyncpg. Nothing held the ledger's own contract. Its only test covered tenant resolution against a stub connection; no test touched `/replay`, `/events` or `/explain`; and the cited hermetic e2e is one Playwright spec in the `screenshots` project, run from a monthly cron rather than from any pull request. `scripts/check_ledger_replay_contract.py` holds the three trees that have to agree for a step to survive from the agent that took it to the analyst reading it back: * the `EventOut` response model against the console's `LedgerEvent`, both directions; * every path `ledgerApi` requests against the router's decorators, and every declared ledger route against its consumers or a recorded reason; * every column the three ledger tables carry against the writer, plus the sequencing no generic column gate can assert — `seq` stamped on every append, `UNIQUE (run_id, seq)` kept, and every handler reading a collection of events ordering by `seq` rather than by the clock. The opposite column direction — a column the writer writes that no migration creates — is `check_raw_sql_columns.py`'s, which landed on main while this was being written and makes that comparison generically over `services/*/app`, this writer included. Duplicating it would be two places to keep in step rather than two checks, so this delegates and checks the delegation: if that gate stops existing or stops reading the writer's tree, `COLUMN-DELEGATION-MISSING` fires here. A verdict is refused on zero parsed fields, routes, client paths, columns or handlers, and the counts print on every run. `services/api/tests/test_investigation_replay.py` exercises the three routes through `TestClient`. Its stub returns rows in the order the emitted SQL asks for and in storage order otherwise, which is the guarantee Postgres gives, so removing `ORDER BY seq` from `replay_run` turns the file red instead of passing over a reordered replay. Proof, each injected and reverted: renaming `EventOut.input_hash` reds field parity in both directions; deleting the `/replay` decorator reds route parity; adding a column to migration 008 the writer never writes reds column parity, and dropping one it does write reds the delegate; removing `ORDER BY seq` fails five API tests and the gate. The empty-tree refusal exits 2. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> |
||
|
|
a6e42a6f45 |
feat(gates): prove no service reaches the public internet by default (#972)
The README says AiSOC runs entirely on your infrastructure with no data exfiltration. Three gates covered corners of that: the CLI makes no calls when telemetry is unconfigured, the Helm chart denies egress by default, and the agents' redactor keeps raw PII out of anything that leaves. None of them answered the platform-wide question, which the claim-to-gate matrix has carried as an open gap. Two halves, because either alone is satisfied by the other's blind spot. scripts/check_default_egress.py reads every service's declared settings defaults and fails on a public host no air-gap guard covers. It found one: services/purple-team declared an ATT&CK STIX bundle URL on a public CDN that nothing in the service ever read. Deleted rather than exempted -- dead config still publishes an external default. tests/test_no_default_egress.py boots each service in its own subprocess under a socket guard, imports app.main with a minimal environment and drives the ASGI lifespan. Attempts are recorded as well as refused, so a startup fetch wrapped in except Exception is still caught. Both are bidirectional. The host predicate is lifted out of the service's own airgap.py rather than reimplemented, so the gate cannot fork from the enforcement it reports on; a rename there fails the gate loudly. Every allow-list entry names the guard that justifies it, and an entry whose guard is deleted, renamed or left calling nothing stops applying. Neither half says anything about what the running containers do. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> |
||
|
|
ff4129fd1f |
feat(gates): hold raw SQL to the same column contract the ORM already has (#970)
* feat(gates): hold raw SQL to the same column contract the ORM already has `detection_rule_proposals` has never had a `source` column, and three raw INSERT statements name it — rule_tuning.py writes 'auto-tuner', hunt_scheduler.py writes 'hunt-finding', detection_loop.py writes 'detection-loop'. Each raises UndefinedColumnError on the first row it tries to write, so none of the three automated proposal paths could produce a proposal on any deployment. Two things hid it. The claim-to-gate matrix recorded the tuning loop as PARTIAL with the gap "exercised in api integration, not a unit DB", which reads as thin coverage of something that runs; no job runs `services/api/tests/` against a real database at all — `Python — Tests` declares no postgres service and sets a deliberate non-database DSN, and the one API test either live-Postgres workflow runs is test_mssp_portfolio_isolation.py. And the only test over the insert asserted `"detection_rule_proposals" in sql`, a substring test the wrong name `aisoc_detection_rule_proposals` also satisfies — a confusion this repository has already shipped once, across three insert sites. `check_orm_migration_parity.py` catches this class for ORM-declared models. Raw `text()` SQL was invisible to it, over 107 statements naming 44 tables, 35 of which have no ORM model at all. - scripts/check_raw_sql_columns.py: ast over services/*/app/**/*.py for INSERT / UPDATE / ON CONFLICT DO UPDATE in string literals and f-strings, every table and column checked against the union of all migration sources. Two shrink-only allow-lists verified in both directions: UNMIGRATED_TABLES for tables no migration owns (the ClickHouse lake, the migration ledgers), DYNAMIC_SQL for statements assembled at runtime — which only ever excuses a statement the parser could not read, so an ordinary write beside a dynamic one is still checked. - Reuses the migration parsers rather than adding a second one, which surfaced two gaps only a column-level reader would notice: a `--` comment swallowed the column definition behind it (four on detection_rule_proposals), and a multi-clause `ALTER TABLE t ADD COLUMN a, ADD COLUMN b` read only its first clause (three columns on `alerts`, five on `aisoc_run_costs`). `RENAME COLUMN` is now applied too, so four `connectors` columns are known under the names the tree actually uses. - migration 073 adds the `source` column the three writers need. - test_wave1_loop_edges.py asserts the parsed table name equals detection_rule_proposals rather than appearing somewhere in the SQL. Proven red before green: injecting `aisoc_detection_rule_proposals` exits 1 naming the table, and renaming one column exits 1 naming the column. The self-test injects both plus a runtime-assembled statement and refuses two shapes of empty tree. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> * fix(gates): name the mssp isolation test by its repository path check_comment_paths resolves a path claim against the repository root, and the docstring wrote it as the workflow's working-directory sees it. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> --------- Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> |
||
|
|
bcc00ec792 |
feat(gates): prove the three SDKs against the spec instead of building them (#969)
* feat(gates): prove the three SDKs against the spec instead of building them
`ci.yml :: sdk-*` runs three jobs and none of them compares a client to the
API it claims to speak. What the three ticks actually establish:
sdk-go-test `packages/sdk-go` is `go.mod` plus `aisoc/models.go`, and
that file is type and const declarations — no functions,
no net/http. Build, vet and test pass trivially over it,
under a first line calling itself "a typed Go client".
sdk-ts-test `package.json` declared `codegen` writing
`src/openapi.d.ts`, which did not exist, was not ignored
and was generated by nothing. Two comments cited that
script as the reason to trust the hand-written types.
sdk-python-test Runs the client's own tests, which mock the transport. A
mock answers whatever the client asks.
That last point is why this found four operations both hand-written clients
called that the API does not serve: DELETE /api/v1/cases/{id} (`cases.py`
declares no delete route at all), PATCH /api/v1/playbooks/{id} (the route is
PUT), and GET /api/v1/detections plus /api/v1/detections/{id} — the prefix is
`/api/v1/detection/rules`, so the whole `detections` namespace 404'd in both
languages. Two of the four were pinned by a passing test.
`scripts/check_sdk_surface.py` asserts four properties. Every endpoint a
client calls must be an operation `docs/openapi.yaml` declares, comparing path
parameters by position so a differently-named argument is not drift. Namespace
parity is read against `packages/sdk-surface.json` in both directions: a
language with no recorded gap must reach the namespace, and a recorded gap
must still be a gap, so the list only shrinks. A declared `codegen` target
must exist. And it refuses a verdict on zero parsed operations, zero parsed
endpoints or a missing manifest, because "the clients are clean" and "the
parser matched nothing" must not print the same word.
`sdk-go` having no client is recorded in the manifest with its reason and
printed on every run rather than exempted quietly — and the gate re-derives
it, so the day a file there imports net/http the entry is stale and the build
fails until it is replaced by the namespaces the client reaches.
The spec is read with a line parser rather than PyYAML so the gate runs on a
bare interpreter; it was checked against `yaml.safe_load` over the real
34,319-line document and returns the identical 502 operations.
The four broken operations are corrected here, and the `codegen` declaration
is deleted along with the two comments citing it. Nothing in `packages/sdk-ts`
dependencies moved, so `pnpm-lock.yaml` is untouched.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix(gates): drop a redefined local and hoist the test module's imports
CodeQL flagged `py/multiple-definition` at
`scripts/tests/test_check_sdk_surface.py:279`: `module = _load()` ran twice in
`test_a_missing_manifest_is_refused`, the second call discarding the first.
The same test file reached for `gate_toolkit`, `pytest` and `yaml` from inside
function bodies, including through an `__import__("importlib")` dance to ask
whether PyYAML was installed. All three are now module-level, with the PyYAML
import guarded by `try`/`except ModuleNotFoundError` so the comparison against
the line parser skips rather than fails on the bare interpreter that parser
exists for.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
---------
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
|
||
|
|
03585000f1 |
fix(docs): remove the conflict markers that broke the docs build (#924)
Three documents reached `main` carrying `<<<<<<< HEAD`, `=======` and `>>>>>>> <sha>`, left behind by a hand-resolved rebase. `ROADMAP.md` and `apps/docs/docs/compliance/evidence-pack.md` had identical text on both sides, so one half is kept; `GAP_CLOSURE_PROGRESS.md` had two different deviation notes, so both are. `evidence-pack.md` is compiled as MDX and the docs deploy failed on it, which is the only reason this surfaced at all. The other two are prose. Nothing caught it, and the reason generalises. Every gate that reads those files is looking for something else: the claim-matrix ratchet parses table rows and a marker is not one, the README figure check looks for a number and found the first of the two duplicated lines, the link checker resolves links. A marker is invisible to all of them, and the only check that sees one is a check that looks for markers. So `scripts/check_merge_markers.py` now does, wired into `ci.yml`. It refuses a tree whose only content is its own toolkit, distinguishes a marker from the two legal Markdown constructs that look like one (a setext heading underline and a blockquote nested seven deep), and is proven against the exact three files that shipped rather than against a synthetic example. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> |
||
|
|
e78f31768c |
Move all fourteen ruff declarations to 0.16, and stop the lint gate at services/ (#861)
* Reformat the tree under ruff 0.16, excluding the subtree nobody may edit Mechanical. `ruff format` with no other change, so the diff can be read as "the formatter moved" rather than reviewed line by line: 218 files, 862 insertions against 1075 deletions, almost all of it collapsing calls that 0.4.10 wrapped and 0.16 fits inside the 140-column limit. `plans/` is excluded in `ruff.toml` rather than reformatted. It is the archived prototype subtree that `.github/workflows/codeql.yml` already excludes and `scripts/check_mypy_baseline.py` excludes from every coverage direction, and the project rules forbid editing anything under it -- so formatting it would be a diff nobody may take. 844 lint findings and ~280 unformatted files live there. They are excluded because they cannot be fixed, which is a different statement from saying the code is clean. * Move all fourteen ruff declarations to 0.16, and stop the lint gate at services/ The bump alone reds every open pull request: `ruff format --check` is a hard gate on the required `Python - Lint & Type-check` job and 0.16 formats differently from 0.4.10. The reformat is the previous commit; this one moves the pin, fixes the findings, and answers the scope question. Fourteen declarations now read `>=0.16.8,<0.17` -- seven manifests, three workflows, `.devcontainer/Dockerfile`, and the three `poetry.lock` files that resolve it (now 0.16.9, which is byte-identical to 0.16.8 on both format and lint across this tree). The three findings 0.16 reports on `services/` are fixed, not suppressed: two `C420` comprehensions become `dict.fromkeys` (both values are string literals, so the shared-value hazard does not apply) and one `UP031` percent-format becomes an f-string in a test that counts characters. All three rewrites were asserted equal to the originals before being kept. Scope. `ruff check services/` left `scripts/` -- every CI gate in this repository, the code the rest of its claims are verified by -- linted by nothing. Lint now covers `services/ scripts/ tests/ tools/`, the trees the root `ruff.toml` governs that nothing else lints, and `ruff format --check .` covers everything, because formatting has no semantic content and `.` needs no edit when a tree is added. That surfaced 17 findings outside `services/`, each fixed at the source: two `B007` loops switched to `.values()`, a `B904` re-raise in `security_audit.py` now chains `from exc`, two `E402` imports that genuinely follow a `sys.path` mutation carry a reason next to the marker, and two over-length lines were wrapped. `E501` is ignored for the two detection-spec data modules. Both open their rule table with `# fmt: off`, so the formatter is already opted out of that layout deliberately, and all 199 long lines are single dict or string literals -- 72 positive fixtures, 66 negative, 50 `match_when` clauses, 11 descriptions. Two named files, not `scripts/`. `packages/` and `plugins/` stay outside the lint gate, and the gap is a number rather than a shrug: 91 findings and 2. Two of the five packages are linted by their own workflows under their own configs, and bringing the three published SDKs under this gate means behaviour-touching fixes that belong in a change reviewed as such. * Make packages/aisoc-detections clean under the ruff its own workflow now installs `python-detections.yml` lints `aisoc_detections detections tests` under the pin this PR moved, so the package has to be clean under 0.16 too. Two findings, both fixed at the source rather than silenced: `Callable` moves to `collections.abc`, and a `# noqa: BLE001` that 0.16 correctly reports as unused becomes the sentence it was standing in for -- a detection module is third-party content, so any exception at import is the author's and becomes a DetectionError naming the file. --------- Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local> |
||
|
|
e92f8188ce |
The dependency audit never looked at the second pnpm install root (#833)
* The dependency audit never looked at the second pnpm install root pnpm audit ran in the repo root and nowhere else. apps/mobile keeps its own pnpm-workspace.yaml so its installs stop rewriting the root lock, which makes it a separate install root - and one the audit never reached. Two high advisories stood open there while the job reported a clean workspace, the same shape as the stale poetry.lock that once dropped services/slack-bot. Install roots are now read from the tree rather than listed, so a third one is covered the day it appears. Each finding names the root it came from, and a tree with no lockfile anywhere is a coverage gap rather than a clean result. The two image-size advisories are suppressed with an expiry, not fixed: no patched 1.x exists, every metro release through 0.87.1 still requires ^1.0.2, and image-size 2.x drops the callable default export Assets.js calls, so an override breaks asset resolution instead of bumping a version. Dependabot's own updater reports security_update_not_possible for the same reason. * Re-check the attribution gate when a pull request body is edited The gate reads the PR body as well as the diff and commit messages, but the default pull_request types do not include edited. So a footer added to the body after the last push was never re-checked, and a body corrected after a failure could not be revalidated: re-running a pull_request job replays the original event payload rather than fetching the current body. Found by the gate failing on this pull request, where the footer was appended automatically at creation time. --------- Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local> |
||
|
|
f3348223a8 |
Five gates said OK over nothing; the probe that found them is now a gate (#823)
* Five gates said OK over nothing; the probe that found them is now a gate Copying scripts/ into an empty git repository and running every wired check found five reporting OK over a tree containing nothing: the detection validator behind the rule count on the front page certifying zero rules as valid, a dashboard check that failed on an empty directory and passed on a missing one, "OK: 0 published Go module path(s)", every self-link healthy over zero files, and a health-probe audit printing a table header and exiting 0. Those five were fixed. The probe was a one-off, so the next gate written could reintroduce the defect freely. scripts/check_gate_contract.py is that probe made permanent. It runs all 69 inventoried checks the way a workflow runs each one, inside a git repository holding only scripts/, and requires each to exit non-zero. The inventory comes from check_gate_coverage.py rather than a second scanner here, because two scanners drift the first time either learns something the other has not. A run that failed for a reason the empty tree did not cause is INCONCLUSIVE and fails rather than counting as a refusal. Every way CI runs a script is probed and the worst result decides, because four subcommands under one name are four gates. Two properties come with it, both enforced with empty exception lists: a root resolved through git rather than from __file__, and a declared --self-test. Sixty of sixty-nine did the former; fifty-four lacked the latter. scripts/gate_toolkit.py holds the single implementation of both. Found while building it: - check_gate_coverage.py decided "inspects the repository" partly by looking for Path(__file__) -- the idiom being migrated away from -- so moving six gates onto the shared resolver dropped them out of the inventory. - The first spelling of the root property matched repo_root anywhere in the text, and check_gate_coverage.py emits it as a JSON key, so a gate rooted at __file__ read as compliant on a key in its own output. - check_route_tenant_scope.py printed "scanned 0 routes across 0 files" and then "OK: every route taking a tenant identifier authenticates" against a services/ tree with no routes in it. - security_audit.py's pnpm, python and go arms each printed "0 findings" over a tree with no manifests, and get_repo_root() fell back to cwd. * Make every gate find gate_toolkit however it is loaded Five CI jobs failed with ModuleNotFoundError: No module named 'gate_toolkit'. Sixteen test modules load a gate with importlib.util.spec_from_file_location, which executes the file without putting its directory on sys.path — so the scripts were importable as programs and not as modules, and the scripts that already import a sibling carry the same tweak for the same reason. Each gate now inserts its own directory before the import. Also corrects the claim-to-gate tally in the compliance evidence pack, which quotes it in prose and was the second place the figure lives. --------- Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local> |
||
|
|
cb55b43912 |
The one unpatchable dependency is removed, and the rest were already fixed (#791)
`scripts/security_audit_ignores.txt` fails closed: a lapsed entry aborts
`validate-ignores` before any ecosystem is scanned. The earliest entry
(ecdsa, PYSEC-2026-1325) expired on 2026-10-05, so all 42 were re-verified
against OSV and against the versions the lockfiles actually resolve, rather
than against the claims in their own reason strings.
Every entry was resolvable and none was carried forward. Most of the
justifications had stopped being true:
- Nine starlette entries blamed a `fastapi<0.137` cap in slack-bot and
teams-bot. Neither pyproject has it; both read `>=0.111,<0.142` and both
locks resolve fastapi 0.141.1 with starlette 1.6.0. The highest fix among
the nine is 1.3.1.
- Three cryptography entries blamed `<50` and `<49` caps. No such cap exists
anywhere; every pin reads `<51` and services/agents resolves 50.0.1.
- Nine langchain/langgraph entries and four langchain-core entries blamed a
blocked 0.3 to 1.x migration that has already happened.
- weasyprint, anyio, aiohttp, h2, idna and pydantic-settings each named a
version older than the one their lock resolves.
ecdsa was the one entry whose "no patched version available" was true: OSV
records the affected range as introduced at 0 with no fixed event, because
upstream states python-ecdsa offers no side-channel resistance and will not
fix CVE-2024-23342. It was also genuinely unconditional under python-jose, so
the dependency is removed rather than re-suppressed. services/api now uses
PyJWT, which it already depended on for the OIDC and SAML paths; resolving the
service drops python-jose, ecdsa and rsa. Six CI workflows installed
python-jose[cryptography] and never installed PyJWT, and reached cryptography —
a declared direct dependency of services/api — only through that extra, so they
now install both by name.
image-size was suppressed on the reading that no fix existed. Both advisories
record a vulnerable range of `<= 2.0.2`, npm has published 2.0.3 and 2.0.4, and
OSV reports both as unaffected; a null `first_patched_version` is not the same
claim as no fix existing. A pnpm override pins `>=2.0.4 <3`, which
@docusaurus/mdx-loader's `^2.0.2` accepts, clearing the workspace's only two
high-severity advisories.
While re-reading the scanner: the pnpm and Go arms recorded a failed scan as a
warning, which exits 0, so the job could print "0 findings" for an ecosystem it
never read — the same shape that once hid services/slack-bot behind a stale
lock. Both now record a coverage gap, which exit_code_for already failed on for
the Python arm. That property had no test; it does now.
Verified: all 20 Python targets exported exactly as run_pip_audit does, every
resolved pin checked against OSV — zero advisories, zero unscanned. pnpm audit
reports zero advisories with the override and two high without it. govulncheck
reports zero findings across all six Go modules.
|
||
|
|
badcdf6289 |
feat: add Redis-backed scheduler singleton + dependency CVE audit pipeline (#218)
Adds a Redis-backed singleton lock guarding the OAuth refresh, weekly digest, and hunt scheduler workers so only one API replica runs them at a time, plus a fail-closed dependency CVE audit pipeline (pnpm/pip-audit/govulncheck) with a documented ignore policy (90-day expiries, mandatory reasons). Admin merge: the only failing checks are docker compose smoke (chronic, unrelated) and the new security-audit job itself, which is failing because it's correctly surfacing a pre-existing CVE backlog in third-party deps (cryptography, starlette, langgraph, weasyprint, idna, etc.). That backlog will be drained via the dependabot PRs already open. |
||
|
|
c163fd0c56 |
feat(evals): add --suite filter, ImportError hint, and CLI tests (#109)
Quickstart video issue: `python scripts/run_evals.py --suite all` failed
with a raw `ImportError` on a fresh clone, and the `--suite` flag itself
didn't exist. This PR makes the runner match the contract the demo
script and quickstart docs already assumed.
Changes:
* Add `--suite {all|mitre_accuracy|alert_reduction|...}` argparse choice
that filters which evaluation suites run. Default is `all` to keep
prior behaviour identical for CI and the recorded video walkthrough.
* Wrap the `tests.*` substrate imports in `try/except ImportError` and
exit with code 3 + a friendly install hint pointing at
`pip install -e services/agents` when deps are missing.
* Order the suite registry (`_SUITE_RUNNERS`) so the CLI choices, the
generated report, and the human-readable banner stay in lockstep.
* Emit explicit `PASS — <suite> green` / `FAIL — <suite> regressed`
banners so the demo voice-over has something deterministic to read.
* Document new exit code `3` and `--suite` usage in the module
docstring.
* New `scripts/tests/test_run_evals_cli.py`: subprocess-driven CLI
surface tests (4 cases) covering `--suite all`, single suite,
unknown suite rejection, and the ImportError hint path (via a
meta-path finder that hides `tests.*` from the runner).
This is PR 3/7 of the demo-video stability series.
Co-authored-by: Beenu Arora <beenu@cyble.com>
|