Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(skills): let a tenant teach the agent what is normal in its own estate (#925)
Beenu Arora70b287aa1190
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 748ad20cd..d06e336dc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -927,6 +927,32 @@ jobs:# destructive tool is still refused when the policy is asked directly.run: python3 scripts/check_mcp_client_policy.py+ - name: Gate the tenant-skill contract (Phase 6)+ # A skill is authored in services/api, validated against a tool+ # vocabulary that lives in services/agents, and activated under a rule+ # written in SQL, in Python and in prose. None of those trees can+ # import the others, so the contract between them is a set of+ # declarations that agree by convention. This asserts the pivot+ # vocabulary matches in both directions, that the+ # backtest-before-activation rule survives in all three places, and+ # that both the triage state and the investigation result still record+ # which skill version guided them.+ run: python3 scripts/check_tenant_skill_contract.py++ - name: Gate the triage context freeze (Phase 6)+ # A verdict may depend on durable state only through+ # TriageContextReader, because that protocol is the seam the replay+ # freeze acts on. A context source read any other way is live during a+ # replay no matter what the snapshot says, and the report then+ # measures a world the split point does not describe while looking+ # exactly like one that worked. This asserts both readers implement+ # every source the protocol declares, and that every store the+ # snapshot holds is filtered against the split and published in the+ # method note, including the one that deliberately bypasses the+ # filter, because an unfiltered store nobody is told about is+ # indistinguishable from a leak.+ run: python3 scripts/check_triage_context_freeze.py+- name: Every check in the tree is reachable from a workflow# The gate on the gates. A conformance script with no workflow cannot# fail, which is indistinguishable from no gate at all — while itsdiff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymlindex e3344a040..2431b9d69 100644--- a/.github/workflows/integration.yml+++ b/.github/workflows/integration.yml@@ -483,6 +483,15 @@ jobs:# The union of what the four services import on this path. Same version# bounds as ci.yml's per-service jobs, because a chain that only works# on a different resolution is not the chain that ships.+ #+ # `mcp` is here because `app/main.py` imports the replay router, which+ # reaches `deep_investigation`, which imports `app.mcp.tools` at module+ # scope. It was added to the agents service and to ci.yml's agents job+ # and not to this list, and this job only runs when the replay paths+ # change, so the first pull request to touch them since was the first to+ # see the agents service fail to boot at all. That is the stale-green+ # shape: a path-filtered job cannot report a breaker it never ran for.+ # Pinned exactly, matching `services/agents/pyproject.toml`.- name: Install the four services' shared dependenciesrun: >-pip install --quiet@@ -499,6 +508,7 @@ jobs:aiokafka apscheduler qdrant-client bcryptlanggraph langchain-core langchain-openaiclick rich jsonschema+ "mcp==1.30.0"# The CLI is driven as an installed console script would be, off its own# source tree, so the command under test is the one the package ships.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b869c253b..1eebf7a4d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,8 +7,97 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **A tenant can now teach the investigation agent what is normal in its own+ estate, and every verdict that guidance steered says which version of it+ steered them** (gap-closure Phase 6.1 and 6.2).++ **The gap.** Investigation strategies were hard-coded. The ten built-ins+ encode how an attack behaves in general, which is the only thing a built-in+ can encode, and there was no way for a customer to write down the thing a+ built-in cannot know: that the encoded PowerShell on FIN-APP-03 at 03:00 is+ the finance reconciliation batch. A tenant with that knowledge had nowhere+ to put it and re-learned it by hand on every repeat.++ **What shipped.** A skill is a YAML document authored in the console,+ following the business-context pattern. It carries match conditions+ (techniques, rule ids, sources, keywords), the plan and expected pivots a+ `Strategy` carries, plus the four things that are statements about one+ organisation rather than about attackers: what is normal here, what verdict+ that normality implies, what evidence has to be in hand before the verdict is+ allowed, and what pulls the alert back to a human anyway. When a skill+ matches it supplies the investigation plan instead of the built-in and its+ guidance reaches the triage prompt; when none matches, selection is+ untouched.++ **Shaped like a detection rule, not like a settings page.** A skill steers a+ verdict, so six months after a disputed auto-close "which text was steering+ the agent that day" has to have an answer. It has an owner, a server-assigned+ version and a required expiry, and `aisoc_tenant_skill_versions` is an+ append-only history so the `skill@vN` recorded on the verdict resolves back+ to the text. `version:` is refused as a document key, because two authorities+ for what version 3 is would eventually disagree.++ **The lifecycle refusals are the point.** A content edit bumps the version,+ drops the skill to draft and detaches its reports, because a backtest is a+ statement about specific text and carrying it across an edit is how a report+ comes to describe something nobody is running. Activation requires a backtest+ of the exact version being activated, and both halves of it, since a+ candidate score with no baseline beside it is a number rather than a+ comparison. The rule is written into a database CHECK, into the store's+ refusal and onto the docs page, and `scripts/check_tenant_skill_contract.py`+ fails the build if it leaves any of the three.++ **The backtest is the Phase 1 replay, not a second one.** Two evaluations+ over the same window, seed and resample count: baseline with the tenant's+ other active skills, candidate with those plus this one. Nothing here+ re-implements replay, scoring or reporting.++ **Validation reads the tenant's real tools.** `expected_pivots` must name a+ built-in lake pivot, a Phase 4 customer-product tool whose product this+ tenant has connected, or a tool on an MCP server this tenant has registered,+ enabled and allowlisted. The customer half makes the same three reads+ `GET /agent-tools/backends` makes, so the set a skill is validated against is+ the set the agent binds rather than a second opinion about it. When the+ action registry is unreachable a known tool name is accepted and the response+ says the check could not be made, because refusing would tell an author their+ EDR is not connected when a different service was briefly down.++ **Measured:** the offline eval harness is unchanged on every axis+ (`mitre_accuracy` 0.970, macro 0.964; `alert_reduction` 0.753;+ `investigation_completeness` 0.943; `response_quality` 1.000), which is the+ expected result and the one worth stating: the synthetic corpus has no tenant+ skills, so a skill-free deployment behaves byte for byte as it did.+ `services/agents` 1390 to 1423 tests, `services/api` 2970 to 3007.+### Changed+- **A skill is a fourth context store, so the replay freeze grew to cover it,+ and the one thing that bypasses the freeze now has to say so** (gap-closure+ Phase 6.2).++ Tenant skills carry `activated_at`, so unlike organisation-memory statements+ they can be tested against the replay split and are: a skill activated after+ the split never reaches a replayed prompt. The exception is a skill backtest,+ which exists to apply a candidate to a window that closed before it was+ written. Freezing it out would measure nothing and applying it silently would+ publish an accuracy number an author could raise by restating the labels, so+ the candidate travels in `ContextSnapshot.skills_under_test`, and the report's+ method note names it and carries the caveat that the figure describes that+ window rather than forecasting new alerts.++ `scripts/check_triage_context_freeze.py` is the new control and it is the one+ that matters for what comes next: a verdict may depend on durable state only+ through `TriageContextReader`, because that protocol is the seam the freeze+ acts on. It requires both readers to implement every declared source and+ every snapshot store to be filtered by `capture_context` and to publish its+ kept and dropped counts. It was proven against seven injected regressions+ rather than observed passing, and the seventh found a real hole: a substring+ match over the method note passed when `skills_frozen` was deleted while+ `skills_dropped_after_split` remained, leaving a note that said what was+ thrown away and never what was kept.+- **The injection benchmark led with the number that describes the guard least.**Both the tuned and the held-out detection rates were published, but the tuned98.1% came first, followed by a per-surface table reading 21/21 and 14/14, anddiff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.mdindex 31492fff2..5b933f9d6 100644--- a/GAP_CLOSURE_PROGRESS.md+++ b/GAP_CLOSURE_PROGRESS.md@@ -410,8 +410,8 @@ suites' job, and anything at all against a live vendor MCP server.## Phase 6: Tenant skills and better triage context-- [ ] **6.1 Tenant-authored skills** in YAML in the console editor, validated against the tenant's actual tools.-- [ ] **6.2 Lifecycle**: draft, backtest through the Phase 1 replay, active; every investigation records the skill version that guided it.+- [x] **6.1 Tenant-authored skills** in YAML in the console editor, validated against the tenant's actual tools. Migration **070**, two tables: `aisoc_tenant_skills` (current state) and `aisoc_tenant_skill_versions` (append-only history). A skill carries match conditions, a plan and expected pivots like a `Strategy`, plus the four fields a built-in cannot have because they are statements about one organisation: guidance, verdict guidance, required evidence and escalation conditions, with owner, server-assigned version and a **required** expiry. The parser refuses unknown top-level keys rather than ignoring them, because `verdict_guidence` otherwise produces a skill that silently does half its job. Tool validation reads the tenant's own rows and their own registry: the built-in lake pivots, the Phase 4 customer-product tools whose product they have connected, and the tools on an **enabled** MCP server's allowlist, so a registered-but-disabled server contributes nothing. The customer half makes the same three reads `GET /agent-tools/backends` makes. See D26, where the gate caught Phase 4.3 landing underneath this work and a known tool name is accepted rather than refused while the registry is unknown.+- [x] **6.2 Lifecycle**: draft, backtest through the Phase 1 replay, active; every investigation records the skill version that guided it. Two refusals carry the phase: a content edit bumps the version, drops to draft and **detaches both reports**, and activation requires a backtest of the exact version plus both halves of it. The rule is written in the migration's CHECK, in the store and on the docs page, and `scripts/check_tenant_skill_contract.py` fails if it leaves any of the three. The backtest is two Phase 1 replay evaluations over one window, seed and resample count; nothing re-implements replay, scoring or reporting. Skills became the fourth frozen context store, and the deliberate backtest bypass is published rather than silent: see D27.- [ ] **6.3 Triage context**: knowledge-base runbooks with citations, the last N analyst dispositions with reasons, and identity context, all point-in-time.- [ ] **6.4 Measure it**: replay before and after on the synthetic corpus and at least one recorded history fixture, and publish the delta.@@ -537,6 +537,17 @@ Nothing yet beyond this kickoff. Each entry below will name its PR.fail against eight injected regressions rather than merely observed passing.See D21 to D23.+- [x] **Phase 6.1 and 6.2, tenant skills.** Migration **070**, two tables.+ Suites: `services/agents` 1390 to 1423 (33 new), `services/api` 2970 to+ 3007 (37 new). Claim matrix 193 rows to 198, GATED 185 to 190. Two new+ gates, `scripts/check_tenant_skill_contract.py` and+ `scripts/check_triage_context_freeze.py`, both wired into `ci.yml` and both+ **proven against injected regressions rather than observed passing**: seven+ were injected into detached copies of the tree and all seven caught, and the+ seventh found a real hole in the freeze gate before it merged. The offline+ eval harness is unchanged on every axis, which is the expected and the+ reportable result: the synthetic corpus has no tenant skills, so a+ skill-free deployment behaves as it did. See D26 and D27.- [x] **Phase 5.6, AiSOC's own MCP server.** `services/mcp` 13 tools to 18,suite 124 to 135. Every tool now publishes MCP behaviour annotations, andthe published tool count is compared against the registry across seven@@ -1312,3 +1323,87 @@ stated. `tests/published-count.test.ts` now compares all seven figures againstthe registry in both directions, proven by staling one figure and by deletinganother. `plans/cyble-aisoc/platform/README.md` also carries the old figureand is deliberately left alone: plan files are never edited.++### D26. The per-tenant tool surface 6.1 validates against landed one commit after this phase was cut++Recorded because the first version of 6.1 was built against a tree where it+did not exist, and the gate written to notice that is what caught it.++The brief said "Phase 4 just landed per-tenant tool advertisement". At the+commit this phase was cut from, `147f89cc`, it had not: that commit is 4.2's+verbs half plus 4.5's CORE decision, and 4.3 was unticked above. So the first+implementation validated `expected_pivots` against the two per-tenant surfaces+that did exist, the built-in lake pivots and Phase 5.2's MCP allowlists, and+refused a vendor read verb with a sentence saying the surface was not built.++Phase 4.3 then merged as [#916](https://github.com/beenuar/AiSOC/pull/916)+while this was in review, adding `GET /api/v1/agent-tools/backends` and six+customer tools to `KNOWN_PIVOTS`. The rebase surfaced it as a gate failure+rather than as a silent divergence: `check_tenant_skill_contract.py` compares+the two vocabularies in both directions and named all six. The validator now+reads the real thing, making the same three reads the backends route makes, so+the set a skill is checked against is the set the agent binds rather than a+second opinion about it. The gate also compares each tool's **capability**,+because a name that matched while its capability drifted would check the+tenant against a verb the agent never asks the registry for, and the skill+would save while the tool never bound.++One judgement worth keeping. The registry can be unreachable, and refusing a+skill then would tell an author their EDR is not connected because a different+service was briefly down; they would delete a correct line from their+document. So a **known** customer tool name is accepted while the registry is+unknown, `ToolInventory.customer_unknown` says so and the console surfaces it,+and a name that is no tool at all is still refused, because that is a typo+rather than an outage. Same distinction Phase 4.3 draws for the prompt:+unknown and absent send a reader to different places.++The durable lesson is the one this file keeps recording from the other+direction: **probe the tree rather than trusting a handed-down description of+it**, and write the gate that will notice when the tree moves underneath you.+Five agents have now been handed a stale migration number; this is the same+shape with a capability instead of a number, and the difference is that this+time a gate caught it before it merged.++### D27. A skill backtest has to bypass the replay freeze, and the honest move is to publish the bypass++Phase 1.5 established that a replay can only measure honestly if durable+context is frozen as of the split point. Phase 6.2 adds a store that breaks+that rule on purpose, and working out *how* to break it is most of the phase's+judgement.++A skill authored today, backtested against last quarter's closed findings, is+guidance whose author may have read the very alerts being graded. Three+options, and two are wrong:++* **Freeze it out.** The candidate is activated after the split by+ construction, so the filter drops it and the backtest measures nothing. Two+ identical reports, a delta of zero, and the feature looks broken.+* **Apply it silently.** The number is then raisable by writing a skill that+ restates the labels, and nothing on the report says so. This is the Phase 1+ leakage failure arriving by a new route: an evaluation answering its own+ question, with a method section that reads correctly.+* **Apply it and say so.** `ContextSnapshot.skills_under_test` is separate from+ `skills`, is not filtered, and is named in `as_method_note` alongside a+ sentence saying the skill was authored after the window and the result+ measures the skill against that window rather than forecasting new alerts.++The third is what shipped, and the property under test in+`test_replay_leakage.py` is not that the bypass is refused but that it is+**published**: an unfiltered store nobody is told about is indistinguishable+from a leak. `scripts/check_triage_context_freeze.py` enforces the same thing+structurally, so a later store cannot be added to the snapshot and quietly left+out of the note.++Two things worth keeping from building that gate. First, the ordinary replay+path still freezes skills, so an operator's general accuracy number is not+inflated by guidance written after the fact; the bypass belongs to the backtest+route and nowhere else, and the test asserts that by running an ordinary+`capture_context` at the same instant and watching the candidate drop.++Second, the gate's first version was too loose and the proof caught it rather+than a reviewer. It searched the method note for any key mentioning the store,+so deleting `skills_frozen` passed while `skills_dropped_after_split` remained,+leaving a note that said what the freeze threw away and never what it kept. It+now requires `<store>_frozen` and `<store>_dropped_after_split` by exact name.+Seven regressions were injected into a detached copy of the tree and all seven+are caught; the seventh is that one.diff --git a/ROADMAP.md b/ROADMAP.mdindex a6aac5c53..707ddb859 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **199 rows — 191 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **204 rows — 196 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex c2c71a5e2..517d743f8 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 191 rows+The last row is the one worth reading first. It is the honest index: 196 rows`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/console/tenant-skills.md b/apps/docs/docs/console/tenant-skills.mdnew file mode 100644index 000000000..32ef47811--- /dev/null+++ b/apps/docs/docs/console/tenant-skills.md@@ -0,0 +1,190 @@+---+title: Tenant skills+sidebar_label: Tenant skills+description: Teach the investigation agent what is normal in your estate, backtest it against your own closed findings, and activate it.+---++# Tenant skills++A skill is your own investigation approach, written down. The built-in+strategies encode how an attack behaves in general. A skill encodes what is+true in *your* estate, which is knowledge a built-in cannot have.++When a skill matches an alert it supplies the investigation plan instead of+the built-in strategy, and its guidance reaches the triage prompt. When no+skill matches, nothing changes.++## What a skill looks like++```yaml+id: finance-batch-powershell+name: Finance nightly reconciliation batch+owner: [email protected]+expires_at: 2027-01-31++match:+ techniques: [T1059.001]+ rule_ids: [rule-encoded-powershell]+ sources: [crowdstrike]+ keywords: ["svc_batch", "reconciliation"]++applies_when: >+ An encoded PowerShell alert names svc_batch on a FIN-APP host.++guidance: >+ Finance runs a nightly reconciliation batch on FIN-APP-01 through FIN-APP-06+ between 02:00 and 04:00 UTC. The job builds its command line from a config+ file, so the command line is different every night and is always encoded.++verdict_guidance: >+ In this organisation, encoded PowerShell launched by svc_batch on a FIN-APP+ host inside the batch window is a benign true positive: the rule fired+ correctly and the behaviour is sanctioned.++required_evidence:+ - The parent process is the scheduled task, not a browser or an Office application.+ - No account other than svc_batch authenticated to the host in the window.++escalate_when:+ - The host is not one of FIN-APP-01 through FIN-APP-06.+ - Any outbound connection leaves the finance VLAN.++plan:+ - List what executed on the host around the alert.+ - Establish the process lineage, which decides this alert on its own.+ - Check the account's authentication trail for the window.++expected_pivots: [process_activity, process_tree, authentication_events]+min_pivots: 2+```++### Fields the server owns++`version`, `status`, `enabled` and `tenant_id` are refused if you put them in+the document. The version is assigned on every content change so there is one+authority for what version 3 is, the status moves through the lifecycle routes+below, and the tenant comes from your credential.++### Fields you cannot leave out++| Field | Why it is required |+|---|---|+| `owner` | A skill that steers a verdict needs somebody to ask when the verdict is disputed. |+| `expires_at` | Organisational facts rot. A skill with no review date keeps steering after it stops being true, and nothing surfaces that. An expired skill is dropped by the resolver. |+| `match` | A skill with no match conditions applies to every alert in your tenant, which replaces the strategy library rather than adding to it. |+| `plan` | A skill with no plan cannot steer an investigation. |+| `expected_pivots` | Without it the run's depth cannot be graded, and an investigation cannot be told apart from a summary. |++### `expected_pivots` is validated against your tools++Every name must be a tool your agent can actually call:++- one of the built-in lake pivots (`process_activity`, `historical_execution`,+ `network_connections`, `authentication_events`, `fleet_ioc_hunt`,+ `entity_timeline`, `technique_activity`, `process_tree`, `mailbox_activity`,+ `oauth_grants`, `persistence_mechanisms`);+- one of the customer-product tools (`siem_indicator_search`,+ `edr_host_details`, `edr_host_detections`, `identity_user_activity`,+ `cloud_audit_lookup`, `endpoint_telemetry_sightings`), **and only if you have+ the product behind it connected**: the same check+ `GET /api/v1/agent-tools/backends` makes when the agent binds its toolset;+- or `mcp.<server>.<tool>` for a tool on an [MCP server](../operations/mcp-client.md)+ you have registered, **enabled**, and named on that server's allowlist.++`GET /api/v1/tenant-skills` returns the current list under `available_tools`,+so the editor can offer them rather than making you discover the vocabulary by+being refused.++:::note When the check cannot be made++If AiSOC cannot reach its action registry it does not know which vendor verbs+you have. A known customer-tool name is then **accepted** and+`available_tools.customer_unknown` comes back true, because refusing would tell+you your EDR is not connected when the real answer is that a different service+was briefly down, and you would delete a correct line from your document. A+name that is not a tool at all is still refused: that is a typo, not an outage.+:::++## Lifecycle++```+draft ──backtest──▶ backtested ──activate──▶ active ──retire──▶ retired+ ▲ │+ └──────────────── any content edit ────────────┘+```++**An edit un-backtests the skill.** Saving new text bumps the version, drops+the skill back to `draft` and detaches the reports. A backtest is a statement+about specific text, and carrying it across an edit is how a report comes to+describe something nobody is running. Reformatting that does not change the+parsed body keeps the version and the backtest.++**Activation requires a backtest of the version being activated**, and both+halves of it. The route refuses with a 409 naming which of these is wrong:++- no backtest attached;+- the backtest graded a different version;+- the skill has already expired;+- the skill is already active.++The same rule is written into a database CHECK constraint, so it holds even+against a direct fix-up, and `scripts/check_tenant_skill_contract.py` fails+the build if it disappears from either place or from this page.++## Backtesting++`POST /api/v1/tenant-skills/{skill_id}/backtest` starts **two**+[replay evaluations](../evaluation/replay.md) over the same window, seed and+resample count:++- **baseline**: your other active skills, without this one;+- **candidate**: those plus this one.++Read them side by side at `GET /api/v1/evaluations/replay/{id}`. The only+difference between the two reports is the skill.++:::caution What a backtest number does and does not say++The skill is applied to a window that closed before it was written. That is+what a backtest is, and it means the author may have seen the very alerts+being graded. The replay report names the skill under `skills_under_test` in+its method section and carries the caveat there.++Read the result as a measurement against that window, not as a forecast of+accuracy on new alerts. If you want the second, activate the skill and run an+ordinary replay over a later window: skills are then frozen at the split point+like every other context source, so only guidance that was genuinely active+during the window contributes.+:::++## What gets recorded++Every investigation a skill guides records `skill_id` and `version`, on the+triage verdict's confidence basis and on the investigation's depth record.+`GET /api/v1/tenant-skills/{skill_id}/versions` turns that pair back into the+exact text that was in force, along with who authored it, the backtest that+graded it and when it was activated.++That read is why `DELETE` is the wrong way to stop using a working skill: it+removes the version history, and the history is what explains verdicts the+skill already steered. Use `POST /{skill_id}/retire`, which keeps it.++## Routes++| Route | Permission | Notes |+|---|---|---|+| `GET /api/v1/tenant-skills` | `settings:read` | With `available_tools`. |+| `GET /api/v1/tenant-skills/{skill_id}` | `settings:read` | |+| `GET /api/v1/tenant-skills/{skill_id}/versions` | `settings:read` | Resolves a recorded `skill@vN`. |+| `POST /api/v1/tenant-skills/validate` | `settings:read` | Returns `valid: false` with the message rather than a 422, so the editor can call it as you type. |+| `PUT /api/v1/tenant-skills` | `settings:write` | The id is inside the document. |+| `POST /api/v1/tenant-skills/{skill_id}/backtest` | `connectors:write` | Reaches your SIEM with stored credentials, so the same bar as testing a connector. |+| `POST /api/v1/tenant-skills/{skill_id}/activate` | `settings:write` | |+| `POST /api/v1/tenant-skills/{skill_id}/retire` | `settings:write` | Keeps the history. |+| `DELETE /api/v1/tenant-skills/{skill_id}` | `settings:write` | Removes the history too. |++## Turning it off++`AISOC_TENANT_SKILLS_ENABLED=0` on the agents service stops skills being read+at all. The agent falls back to the built-in strategy library, which is the+behaviour before this feature existed.diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex ce137aa91..fb91f3a46 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -56,6 +56,7 @@ const sidebars: SidebarsConfig = {"console/rule-tuning","console/investigation-rail","console/public-replay",+ "console/tenant-skills",],},{diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex f6bd52b55..4c9d25681 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -207,6 +207,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| A model never composes SPL, KQL or ES-QL query text against a customer's SIEM | `plans/aisoc_gap_closure_plan.plan.md` (4.1); `apps/docs/docs/operations/agent-vendor-tools.md` (The model never writes a query) | `ci.yml` agents job (`test_customer_tools.py` asserts on the **JSON schema the model is handed**, not on the implementation, since the schema is what constrains a model: no property named query, search, spl, kql, esql, sql, free_text, field, filter, where or index on any tool, every property typed `string` or `integer` so a query cannot arrive as structured data, and `indicator_type` a closed sorted enum) + `ci.yml` api job (`test_agent_tools.py` - 23 value-shape cases in both directions, and every field token in the per-backend map asserted to match the identifier pattern the translators' own field check enforces, so a mapping that would 422 on every search cannot ship) + `ci.yml` connectors job (`Indicator.__post_init__` refuses a field name that is not an identifier, at the single choke point every translator goes through) | GATED | The field map is a reviewed table, not derived: there is no machine-readable source in this repository for what Splunk CIM calls a source address. The alternative, letting the model name the field, is the thing the boundary exists to prevent || Every tool call an investigation makes is in the Investigation Ledger | `plans/aisoc_gap_closure_plan.plan.md` (rules for every phase, LLM calls) | `ci.yml` agents job (`test_deep_investigation_customer_tools.py` captures what the driver hands `ledger.record_event` at the ledger's own function boundary and asserts one `tool_call` row per call in the trace, carrying the tool name **and its arguments**, because "the ledger shows every call" means an auditor can answer which host was read. Sequence numbers are asserted distinct and at or above 10,000: `record_event` carries `ON CONFLICT (run_id, seq) DO NOTHING`, so a collision with the graph runner's own numbering would be a silently dropped row, which is worse than an error because the ledger still looks complete) | GATED | `run_with_tools` built a trace and nothing carried it anywhere durable, so this is new rather than newly gated. The write is best-effort by design: a ledger failure must not take a completed investigation down, and `ledger_rows` on the result reports how many rows landed so "nothing to record" is distinguishable from "the ledger is not configured" || A cross-service route this program adds is asserted against the URL the serving side actually serves | `GAP_CLOSURE_PROGRESS.md` (D16) | `ci.yml` api job (`test_agent_tools.py` parses `services/api/app/main.py`, `api/v1/router.py` and the endpoint module with `ast`, composes all three prefix levels, and asserts each literal the agents service builds is in the served set. Proven able to fail from **both** sides: dropping `/api/v1` from the client's path, and renaming the router's own prefix. The helper raises rather than returning an empty set, so a parser that stopped matching cannot certify nothing. Also asserts the `impact` field the API filters on exists on `LiveActionDescriptor` **and** is populated from the contract rather than left at its default) | GATED | Covers the two routes this phase adds and the actions discovery route it consumes. It is not a repository-wide scan: the general version would need every client's URL construction to be statically resolvable, and several build theirs from settings |+| A tenant can author an investigation skill in the console and it changes the plan on matching alerts | `apps/docs/docs/console/tenant-skills.md`; `plans/aisoc_gap_closure_plan.plan.md` (6.1, 6.2) | `ci.yml` agents job (`test_tenant_skill_investigation.py::test_done_when_a_skill_changes_the_investigation_plan_on_a_matching_alert`: one alert run twice through the real `run_deep_investigation`, everything held constant except whether the tenant has an active skill, asserting on the **system prompt the tool loop was handed** rather than on the verdict, because a verdict can be unchanged by a plan that did change. The built-in the alert would otherwise select is asserted by name, so "the skill won" and "nothing selected anything" are told apart) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py`) | GATED | A skill supplies the plan **and** the triage guidance. A skill that only changed the pivot plan could not be backtested at all: the replay grades triage verdicts, so the delta would read zero on every run |+| A skill may only name a tool that tenant's agent can actually call | `apps/docs/docs/console/tenant-skills.md` (expected_pivots is validated against your tools) | `ci.yml` api job (`test_tenant_skills.py::TestToolValidation`: the inventory is built from the tenant's **enabled** MCP servers only, so a registered-but-disabled server, an empty allowlist and another tenant's server each contribute nothing; a misspelt built-in and an un-allowlisted MCP tool get different messages because the author's next action differs) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` compares `BUILTIN_PIVOTS` against the agents service's `KNOWN_PIVOTS` in **both** directions; proven able to fail by deleting a pivot from each side in turn) | GATED | Phase 4.3's per-tenant vendor-read advertisement does not exist yet, so the inventory is the built-in lake pivots plus Phase 5.2's MCP allowlists. A pivot naming a vendor read verb is refused with a sentence saying the surface is not built, rather than silently accepted |+| A skill cannot be activated without a backtest of the exact version being activated | `apps/docs/docs/console/tenant-skills.md` (Lifecycle) | `ci.yml` api job (`test_tenant_skills.py::TestLifecycle`: activation is refused with no backtest, with a backtest of a different version, when expired, and when one evaluation is used as its own baseline; a content edit is asserted to bump the version, drop the row to draft and detach both reports, while a reformat that leaves the parsed body identical keeps them) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` requires the rule in the migration's CHECK, in the store and on the docs page; proven able to fail by weakening the SQL clause) | GATED | Stated in three places on purpose. The CHECK holds against a direct fix-up; the store's refusal is what produces a sentence an operator can act on rather than a constraint name |+| Every investigation a skill guided records which version guided it, and that version resolves back to its text | `apps/docs/docs/console/tenant-skills.md` (What gets recorded) | `ci.yml` agents job (`test_tenant_skill_investigation.py`: the provenance carries id, version and owner; the investigation pins the version triage already used rather than re-resolving, since the fetch is cached and an activation between the two reads would split them) + `ci.yml` api job (`test_tenant_skills.py`: a content edit leaves both versions in `aisoc_tenant_skill_versions`, and retire keeps the history while delete removes it) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` requires the field on both `DeepInvestigationResult` and `InvestigationState`; proven able to fail by renaming it on either) | GATED | A recorded version with no history row is provenance-shaped and not provenance, so a skill row whose version is absent or zero is refused by the resolver rather than served |+| Tenant skills are frozen at the split point during a replay, and the backtest bypass is published rather than silent | `apps/docs/docs/console/tenant-skills.md` (What a backtest number does and does not say); `services/agents/app/replay/shadow.py` | `ci.yml` agents job (`test_replay_leakage.py`: a skill activated after the split never reaches the prompt, with a **sensitivity half** that runs the live reader and asserts the same poison does; the backtest candidate is asserted to reach the prompt *and* to be named in the method note with its caveat, with a sensitivity half asserting an ordinary replay of the same instant freezes it out; a skill with no activation stamp is counted the way an undated statement is) + `ci.yml` gates job (`scripts/check_triage_context_freeze.py`: every source `TriageContextReader` declares must be implemented by both readers, and every snapshot store must be filtered by `capture_context` and publish `_frozen` and `_dropped_after_split` in the method note. Proven able to fail by removing the frozen reader's method, by silencing the bypass, and by deleting one kept-count key while a neighbouring key remained, which an earlier substring version of the check missed) | GATED | A skill backtest deliberately applies a candidate authored after the window, which is what a backtest is. The figure is a statement about that window and not a forecast, and the method note says so in those words rather than leaving a reader to infer it |## Summary@@ -214,7 +219,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 191+- GATED: 196- PARTIAL: 8- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex fbff117cc..77a776362 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -6034,6 +6034,306 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/tenant-skills:+ get:+ tags:+ - tenant-skills+ summary: Every skill this tenant has authored+ operationId: list_tenant_skills_api_v1_tenant_skills_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SkillListResponse'+ security:+ - HTTPBearer: []+ put:+ tags:+ - tenant-skills+ summary: Create or update a skill from its YAML+ description: 'Save the document. A content change bumps the version and drops+ to draft.+++ ``PUT`` with no id in the path because the id is inside the document: a++ skill''s identity is the author''s slug, and taking it from a path as well++ would create two authorities that can disagree.'+ operationId: save_tenant_skill_api_v1_tenant_skills_put+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SaveSkillRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SkillModel'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/tenant-skills/{skill_id}:+ get:+ tags:+ - tenant-skills+ summary: One skill+ operationId: get_tenant_skill_api_v1_tenant_skills__skill_id__get+ security:+ - HTTPBearer: []+ parameters:+ - name: skill_id+ in: path+ required: true+ schema:+ type: string+ title: Skill Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SkillModel'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ delete:+ tags:+ - tenant-skills+ summary: Delete a skill and its history+ description: 'For a skill created by mistake. To stop using a working one, retire+ it.+++ Deleting removes the version history, which is what explains verdicts the++ skill already steered. The docs say so beside this route.'+ operationId: delete_tenant_skill_api_v1_tenant_skills__skill_id__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: skill_id+ in: path+ required: true+ schema:+ type: string+ title: Skill Id+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/tenant-skills/{skill_id}/versions:+ get:+ tags:+ - tenant-skills+ summary: Every version of one skill, newest first+ description: 'Resolve a ``skill@vN`` recorded on an investigation back to its+ text.+++ This is the read that makes the version recorded on a verdict mean++ something. Without it the pair is a number pointing at nothing.'+ operationId: list_skill_versions_api_v1_tenant_skills__skill_id__versions_get+ security:+ - HTTPBearer: []+ parameters:+ - name: skill_id+ in: path+ required: true+ schema:+ type: string+ title: Skill Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: '#/components/schemas/SkillVersionModel'+ title: Response List Skill Versions Api V1 Tenant Skills Skill Id Versions+ Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/tenant-skills/validate:+ post:+ tags:+ - tenant-skills+ summary: Parse and validate without saving+ description: 'Back the editor''s validate button with the same call the save+ makes.+++ A 200 carrying ``valid: false`` rather than a 422: the editor asks this on++ every keystroke pause, and an error status on a document the author is++ still typing is a failed request in their network tab every few seconds.++ The save route returns the 422.'+ operationId: validate_tenant_skill_api_v1_tenant_skills_validate_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SaveSkillRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ValidateResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/tenant-skills/{skill_id}/backtest:+ post:+ tags:+ - tenant-skills+ summary: Grade this skill against the tenant's own closed findings, with and+ without it+ description: 'Start the two Phase 1 replay runs that grade this version.+++ 202 for the same reason ``POST /evaluations/replay`` is: replaying a few++ hundred findings through a model twice is not a request-response++ operation. The ids come back immediately and the console polls both.+++ ``connectors:write`` rather than ``settings:write``, because what this++ actually does is reach a customer''s own SIEM with stored credentials,++ which is the bar every other route that does that clears.'+ operationId: backtest_tenant_skill_api_v1_tenant_skills__skill_id__backtest_post+ security:+ - HTTPBearer: []+ parameters:+ - name: skill_id+ in: path+ required: true+ schema:+ type: string+ title: Skill Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SkillBacktestRequest'+ responses:+ '202':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SkillBacktestResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/tenant-skills/{skill_id}/activate:+ post:+ tags:+ - tenant-skills+ summary: Put a backtested skill into service+ description: 'Activate, refusing anything that would put untested guidance in+ front of alerts.+++ The refusals live in the store and are restated by the database++ constraint, so neither this route nor a future caller can be the only++ place the rule holds.'+ operationId: activate_tenant_skill_api_v1_tenant_skills__skill_id__activate_post+ security:+ - HTTPBearer: []+ parameters:+ - name: skill_id+ in: path+ required: true+ schema:+ type: string+ title: Skill Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SkillModel'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/tenant-skills/{skill_id}/retire:+ post:+ tags:+ - tenant-skills+ summary: Take a skill out of service, keeping its history+ operationId: retire_tenant_skill_api_v1_tenant_skills__skill_id__retire_post+ security:+ - HTTPBearer: []+ parameters:+ - name: skill_id+ in: path+ required: true+ schema:+ type: string+ title: Skill Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SkillModel'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/rbac/permissions:get:tags:@@ -17835,6 +18135,44 @@ components:- tenant_id- actionstitle: AutonomyPolicyResponse+ AvailableTools:+ properties:+ builtin:+ items:+ type: string+ type: array+ title: Builtin+ customer:+ items:+ type: string+ type: array+ title: Customer+ mcp:+ items:+ type: string+ type: array+ title: Mcp+ customer_unknown:+ type: boolean+ title: Customer Unknown+ default: false+ customer_unknown_reason:+ type: string+ title: Customer Unknown Reason+ default: ''+ type: object+ title: AvailableTools+ description: 'What an author may name in ``expected_pivots`` on this tenant+ today.+++ Returned with the list so the editor can offer the vocabulary rather than++ making the author discover it by being refused. ``customer_unknown`` is++ part of the contract: an editor that read an unreachable action registry++ as "this tenant has no products" would grey out tools the tenant has.'BacktestProposalRequest:properties:window_days:@@ -28804,6 +29142,17 @@ components:- provider- detailtitle: SandboxResultResponse+ SaveSkillRequest:+ properties:+ source_yaml:+ type: string+ maxLength: 32768+ minLength: 1+ title: Source Yaml+ type: object+ required:+ - source_yaml+ title: SaveSkillRequestSavedHuntModel:properties:id:@@ -29182,6 +29531,231 @@ components:against the shape that type requires, so a model cannot pass query textby claiming it is an indicator.'+ SkillBacktestRequest:+ properties:+ connector_id:+ type: string+ format: uuid+ title: Connector Id+ since:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Since+ until:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Until+ train_fraction:+ type: number+ exclusiveMaximum: 1.0+ exclusiveMinimum: 0.0+ title: Train Fraction+ default: 0.7+ limit:+ type: integer+ maximum: 2000.0+ minimum: 1.0+ title: Limit+ default: 1000+ bootstrap_seed:+ type: integer+ title: Bootstrap Seed+ default: 20260926+ bootstrap_resamples:+ type: integer+ title: Bootstrap Resamples+ default: 1000+ type: object+ required:+ - connector_id+ title: SkillBacktestRequest+ description: Which connector and window to grade the skill over.+ SkillBacktestResponse:+ properties:+ skill_id:+ type: string+ title: Skill Id+ version:+ type: integer+ title: Version+ baseline_evaluation_id:+ type: string+ title: Baseline Evaluation Id+ candidate_evaluation_id:+ type: string+ title: Candidate Evaluation Id+ note:+ type: string+ title: Note+ type: object+ required:+ - skill_id+ - version+ - baseline_evaluation_id+ - candidate_evaluation_id+ - note+ title: SkillBacktestResponse+ description: The two runs the console polls, and how to read them together.+ SkillListResponse:+ properties:+ skills:+ items:+ $ref: '#/components/schemas/SkillModel'+ type: array+ title: Skills+ available_tools:+ $ref: '#/components/schemas/AvailableTools'+ type: object+ required:+ - skills+ - available_tools+ title: SkillListResponse+ SkillModel:+ properties:+ skill_id:+ type: string+ title: Skill Id+ version:+ type: integer+ title: Version+ status:+ type: string+ title: Status+ name:+ type: string+ title: Name+ owner:+ type: string+ title: Owner+ expires_at:+ type: string+ format: date-time+ title: Expires At+ expired:+ type: boolean+ title: Expired+ body:+ additionalProperties: true+ type: object+ title: Body+ source_yaml:+ type: string+ title: Source Yaml+ backtest_evaluation_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Backtest Evaluation Id+ backtest_baseline_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Backtest Baseline Id+ backtest_version:+ anyOf:+ - type: integer+ - type: 'null'+ title: Backtest Version+ activated_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Activated At+ created_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Created At+ updated_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Updated At+ type: object+ required:+ - skill_id+ - version+ - status+ - name+ - owner+ - expires_at+ - expired+ - body+ - source_yaml+ title: SkillModel+ description: One skill as the console sees it.+ SkillVersionModel:+ properties:+ skill_id:+ type: string+ title: Skill Id+ version:+ type: integer+ title: Version+ name:+ type: string+ title: Name+ owner:+ type: string+ title: Owner+ expires_at:+ type: string+ format: date-time+ title: Expires At+ body:+ additionalProperties: true+ type: object+ title: Body+ source_yaml:+ type: string+ title: Source Yaml+ backtest_evaluation_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Backtest Evaluation Id+ backtest_baseline_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Backtest Baseline Id+ authored_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Authored At+ activated_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Activated At+ retired_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Retired At+ type: object+ required:+ - skill_id+ - version+ - name+ - owner+ - expires_at+ - body+ - source_yaml+ title: SkillVersionModel+ description: One immutable version, which is what a recorded ``skill@vN`` resolves+ to.SourceLinkResponse:properties:vendor:@@ -31664,6 +32238,37 @@ components:- role_id- role_nametitle: UserRoleOut+ ValidateResponse:+ properties:+ valid:+ type: boolean+ title: Valid+ skill_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Skill Id+ name:+ anyOf:+ - type: string+ - type: 'null'+ title: Name+ expected_pivots:+ items:+ type: string+ type: array+ title: Expected Pivots+ available_tools:+ $ref: '#/components/schemas/AvailableTools'+ error:+ anyOf:+ - type: string+ - type: 'null'+ title: Error+ type: object+ required:+ - valid+ title: ValidateResponseValidationError:properties:loc:diff --git a/scripts/check_route_auth.py b/scripts/check_route_auth.pyindex 289f417f4..01681aa9c 100644--- a/scripts/check_route_auth.py+++ b/scripts/check_route_auth.py@@ -214,6 +214,13 @@ IN_BAND_CREDENTIAL_ROUTES: dict[str, tuple[str, str]] = {"constant time and fails closed when unset. Deliberately no session fallback, unlike the other dual-mode routes: this one ""returns plaintext third-party credentials, and a console session is not a credential to read those",),+ "services/api/app/api/v1/endpoints/tenant_skills.py::resolve_tenant_skills": (+ "service_token_valid",+ "the agents service reads its tenant's active investigation skills here on the path of an investigation and holds no session; "+ "the shared X-AiSOC-Service-Token is compared in constant time and fails closed when unset. No session fallback, on a simpler "+ "ground than the MCP registry's: this route exists for one caller, and a route with one caller should accept one kind of "+ "credential. The console reads the same rows through GET /tenant-skills, which returns more",+ ),}diff --git a/scripts/check_route_tenant_scope.py b/scripts/check_route_tenant_scope.pyindex 3369424e0..84fb611cb 100644--- a/scripts/check_route_tenant_scope.py+++ b/scripts/check_route_tenant_scope.py@@ -204,6 +204,13 @@ IN_BAND_CREDENTIAL_ROUTES: dict[str, tuple[str, str]] = {"than a narrowing of one, because a service token carries no tenant to intersect with, and this route refuses a ""console session outright so no user's scope can reach it",),+ "services/api/app/api/v1/endpoints/tenant_skills.py::resolve_tenant_skills": (+ "service_token_valid",+ "the agents service reads its tenant's active investigation skills here and holds no session; the shared service "+ "token is the credential, compared in constant time and failing closed when unset. The named tenant is the scope "+ "rather than a narrowing of one, for the same reason as the MCP registry above, and the RLS context is set from "+ "that same value so the policy and the query predicate cannot disagree",+ ),}#: Routes that are public by design. Each entry is (service, reason) and thediff --git a/scripts/check_tenant_skill_contract.py b/scripts/check_tenant_skill_contract.pynew file mode 100644index 000000000..f2fe3b215--- /dev/null+++ b/scripts/check_tenant_skill_contract.py@@ -0,0 +1,289 @@+#!/usr/bin/env python3+"""Pin the three things a tenant skill spans that no single module can enforce.++Gap-closure Phase 6.1 and 6.2.++A skill is authored in ``services/api``, validated against a tool vocabulary+that lives in ``services/agents``, and activated under a rule that is written+in SQL, in Python and in prose. None of those three trees can import the+others: both services package their code as top-level ``app``, and a CHECK+constraint is not importable at all. So the contract between them is a handful+of declarations that agree by convention, and conventions drift.++Three properties, each checked in both directions+--------------------------------------------------+**1. The tool vocabulary.** ``services/api/app/services/tenant_skills/tools.py``+declares what the authoring validator will accept: ``BUILTIN_PIVOTS`` for the+lake, ``SIEM_SEARCH_TOOL`` and ``CUSTOMER_TOOL_CAPABILITIES`` for Phase 4's+typed surface onto the customer's own products. ``KNOWN_PIVOTS`` in+``services/agents/app/investigator/strategies.py`` is what the agent can+actually bind, and ``VENDOR_READ_TOOLS`` in+``services/agents/app/tools/customer_tools.py`` is the capability each+customer tool resolves to. Both directions have a distinct failure:++* a tool in agents and not in the API makes a legitimate skill unauthorable,+ and the author is told their tool does not exist when it does;+* a tool in the API and not in agents lets a skill name one that is gone, and+ the failure surfaces as an investigation that quietly never reaches a pivot+ it declared, which the depth record then grades as shallow.++The capabilities are compared too, not just the names. A tool whose capability+drifted would be validated against a verb the tenant does not have, so the+skill would save and the tool would never bind.++This check has already earned its keep: it caught the six customer tools Phase+4 added to ``KNOWN_PIVOTS`` while this phase was in flight, which is exactly+the drift it was written for.++**2. Activation requires a backtest of the exact version.** This is the rule+that stops a report describing text nobody is running, and it is stated in+three places on purpose: the database CHECK, the store's refusal, and the+docs page an operator reads. A rule that survives in two of the three is a+rule somebody removed from the third and nobody noticed.++**3. The version reaches the investigation.** A skill that steers a verdict+without recording which version steered it is provenance-shaped and not+provenance. The gate requires the deep-investigation result to carry a+``tenant_skill`` field and the triage state to carry one too, because a skill+applied on one path and unrecorded on the other is exactly the half-wired+shape this program keeps finding.++Nothing is imported. The gate runs on a bare interpreter, and importing+either service would drag in httpx, SQLAlchemy and the whole worker stack to+compare a set of strings.+"""++from __future__ import annotations++import argparse+import ast+import re+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_if_requested # noqa: E402++self_test_if_requested(__file__)++_API_TOOLS_FILE = "services/api/app/services/tenant_skills/tools.py"+_AGENT_PIVOTS_FILE = "services/agents/app/investigator/strategies.py"+_AGENT_CUSTOMER_FILE = "services/agents/app/tools/customer_tools.py"++_MIGRATION = "services/api/migrations/070_tenant_skills.sql"+_STORE = "services/api/app/services/tenant_skills/store.py"+_DOC = "apps/docs/docs/console/tenant-skills.md"++_DEEP_RESULT = ("services/agents/app/investigator/deep_investigation.py", "DeepInvestigationResult")+_STATE = ("services/agents/app/models/state.py", "InvestigationState")+_PROVENANCE_FIELD = "tenant_skill"++#: The SQL that says an active row must name a backtest of its own version.+#: Matched on the three clauses rather than on the whole constraint text, so+#: reformatting the migration does not fail the gate and removing a clause+#: does.+_SQL_CLAUSES = (+ r"status\s*<>\s*'active'",+ r"backtest_evaluation_id\s+IS\s+NOT\s+NULL",+ r"backtest_baseline_id\s+IS\s+NOT\s+NULL",+ r"backtest_version\s*=\s*version",+)+++def _read(root: Path, relative: str) -> str:+ path = root / relative+ if not path.is_file():+ raise SystemExit(f"FAIL: {relative} is missing; the tenant-skill contract cannot be checked")+ return path.read_text(encoding="utf-8")+++def _string_members(source: str, name: str, relative: str) -> set[str]:+ """Read a module-level frozenset/tuple/set/list of string literals."""+ tree = ast.parse(source, filename=relative)+ for node in ast.walk(tree):+ if isinstance(node, ast.Assign):+ targets: list[ast.expr] = list(node.targets)+ elif isinstance(node, ast.AnnAssign):+ targets = [node.target]+ else:+ continue+ if not any(isinstance(t, ast.Name) and t.id == name for t in targets):+ continue+ value: ast.expr | None = node.value+ if isinstance(value, ast.Call) and value.args:+ value = value.args[0]+ if isinstance(value, ast.Tuple | ast.List | ast.Set):+ members = {e.value for e in value.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)}+ if members:+ return members+ raise SystemExit(f"FAIL: {name} was not found as a literal collection of strings in {relative}")+++def _string_constant(source: str, name: str, relative: str) -> str:+ tree = ast.parse(source, filename=relative)+ for node in ast.walk(tree):+ if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in node.targets):+ if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):+ return str(node.value.value)+ raise SystemExit(f"FAIL: {name} was not found as a string constant in {relative}")+++def _tool_capabilities(source: str, name: str, relative: str) -> dict[str, str]:+ """Read ``{tool_name: capability}`` from a flat or a nested mapping.++ The API side is flat; the agents side nests the capability inside a dict+ that also holds the argument name and the model-facing description. One+ reader for both, so the gate cannot be defeated by either side changing+ shape.+ """+ tree = ast.parse(source, filename=relative)+ for node in ast.walk(tree):+ targets: list[ast.expr]+ if isinstance(node, ast.Assign):+ targets = list(node.targets)+ elif isinstance(node, ast.AnnAssign):+ targets = [node.target]+ else:+ continue+ if not any(isinstance(t, ast.Name) and t.id == name for t in targets):+ continue+ if not isinstance(node.value, ast.Dict):+ continue+ out: dict[str, str] = {}+ for key, value in zip(node.value.keys, node.value.values, strict=False):+ if not isinstance(key, ast.Constant) or not isinstance(key.value, str):+ continue+ if isinstance(value, ast.Constant) and isinstance(value.value, str):+ out[key.value] = value.value+ elif isinstance(value, ast.Dict):+ for k2, v2 in zip(value.keys, value.values, strict=False):+ if (+ isinstance(k2, ast.Constant)+ and k2.value == "capability"+ and isinstance(v2, ast.Constant)+ and isinstance(v2.value, str)+ ):+ out[key.value] = v2.value+ if out:+ return out+ raise SystemExit(f"FAIL: {name} was not found as a mapping of tool name to capability in {relative}")+++def _class_fields(source: str, class_name: str, relative: str) -> set[str]:+ tree = ast.parse(source, filename=relative)+ for node in ast.walk(tree):+ if isinstance(node, ast.ClassDef) and node.name == class_name:+ fields = {item.target.id for item in node.body if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name)}+ if not fields:+ raise SystemExit(f"FAIL: {class_name} in {relative} declares no annotated fields")+ return fields+ raise SystemExit(f"FAIL: class {class_name} was not found in {relative}")+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--self-test", action="store_true", help="prove the gate refuses an empty tree")+ parser.parse_args(argv)++ root = repo_root()+ failures: list[str] = []+ checked = 0++ # 1. Tool vocabulary, both directions, names and capabilities.+ api_source = _read(root, _API_TOOLS_FILE)+ api_builtin = _string_members(api_source, "BUILTIN_PIVOTS", _API_TOOLS_FILE)+ api_customer = _tool_capabilities(api_source, "CUSTOMER_TOOL_CAPABILITIES", _API_TOOLS_FILE)+ api_siem = _string_constant(api_source, "SIEM_SEARCH_TOOL", _API_TOOLS_FILE)+ api_names = api_builtin | set(api_customer) | {api_siem}++ agent_pivots = _string_members(_read(root, _AGENT_PIVOTS_FILE), "KNOWN_PIVOTS", _AGENT_PIVOTS_FILE)+ agent_source = _read(root, _AGENT_CUSTOMER_FILE)+ agent_customer = _tool_capabilities(agent_source, "VENDOR_READ_TOOLS", _AGENT_CUSTOMER_FILE)+ agent_siem = _string_constant(agent_source, "SIEM_SEARCH_TOOL", _AGENT_CUSTOMER_FILE)+ checked += len(api_names) + len(agent_pivots) + len(agent_customer)++ unauthorable = sorted(agent_pivots - api_names)+ unreachable = sorted(api_names - agent_pivots)+ if unauthorable:+ failures.append(+ f"KNOWN_PIVOTS holds {unauthorable} and {_API_TOOLS_FILE} does not: a skill naming one of these "+ f"is refused at authoring time although the agent can call it"+ )+ if unreachable:+ failures.append(+ f"{_API_TOOLS_FILE} holds {unreachable} and KNOWN_PIVOTS does not: a skill may name one of these "+ f"and the investigation will never reach it, which the depth record grades as shallow"+ )++ if api_siem != agent_siem:+ failures.append(+ f"the federated-SIEM tool is called {api_siem!r} in {_API_TOOLS_FILE} and {agent_siem!r} in "+ f"{_AGENT_CUSTOMER_FILE}: a skill would be validated against a name nothing binds"+ )+ for tool in sorted(set(api_customer) | set(agent_customer)):+ api_capability = api_customer.get(tool)+ agent_capability = agent_customer.get(tool)+ if api_capability != agent_capability:+ failures.append(+ f"customer tool {tool!r} resolves to capability {api_capability!r} in {_API_TOOLS_FILE} and "+ f"{agent_capability!r} in {_AGENT_CUSTOMER_FILE}: the validator would check this tenant against a "+ f"verb the agent never asks the registry for, so the skill saves and the tool never binds"+ )++ # 2. Activation requires a backtest of the exact version, in all three places.+ migration = _read(root, _MIGRATION)+ for clause in _SQL_CLAUSES:+ checked += 1+ if not re.search(clause, migration, re.IGNORECASE):+ failures.append(+ f"{_MIGRATION} no longer constrains `{clause}`: the database would accept an active skill "+ f"whose attached backtest graded different text"+ )++ store = _read(root, _STORE)+ checked += 1+ if "backtest_version" not in store or "activate_skill" not in store:+ failures.append(+ f"{_STORE} no longer checks the backtest version in activate_skill: the database constraint would "+ f"become the only refusal, and its message is a constraint name rather than a sentence"+ )++ doc = _read(root, _DOC)+ checked += 1+ if not re.search(r"backtest", doc, re.IGNORECASE) or not re.search(r"activat", doc, re.IGNORECASE):+ failures.append(+ f"{_DOC} no longer documents that activation requires a backtest: an operator reading the docs "+ f"would not know why their activate call is refused"+ )++ # 3. The version reaches both paths.+ for relative, class_name in (_DEEP_RESULT, _STATE):+ checked += 1+ if _PROVENANCE_FIELD not in _class_fields(_read(root, relative), class_name, relative):+ failures.append(+ f"{class_name} in {relative} no longer carries `{_PROVENANCE_FIELD}`: a skill would steer a "+ f"verdict on that path with no record of which version steered it"+ )++ if not checked:+ print("FAIL: the gate compared nothing, which is indistinguishable from a clean result")+ return 1++ if failures:+ print(f"FAIL: {len(failures)} tenant-skill contract problem(s)\n")+ for failure in failures:+ print(f" - {failure}")+ return 1++ print(+ f"OK: {len(api_names)} tool name(s) agree across both services, including {len(api_customer)} "+ f"customer-product tool(s) whose capabilities also match; the backtest-before-activation rule holds "+ f"in the migration, the store and the docs; and both the triage state and the investigation result "+ f"record which skill version guided them."+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/check_triage_context_freeze.py b/scripts/check_triage_context_freeze.pynew file mode 100644index 000000000..7490535af--- /dev/null+++ b/scripts/check_triage_context_freeze.py@@ -0,0 +1,242 @@+#!/usr/bin/env python3+"""A context source a replay cannot freeze makes every replay report unreliable.++Gap-closure Phase 6.2, and the control Phase 6.3 needs before it adds three+more stores.++The property+------------+``app.workers.triage_persistence.TriageContextReader`` is the seam the replay+freeze acts on. A verdict may depend on durable state only through that+protocol, because ``FrozenTriageContextReader`` is what serves the state as it+stood at the split point. A source read any other way is live during a replay+no matter what the snapshot says, and the report then measures a world the+split point does not describe, while looking exactly like one that worked.++Phase 1 shipped that seam with two methods. Phase 6.2 added a third and Phase+6.3 adds more. Each addition is three edits that have to land together, and+each has its own silent failure:++* the protocol declares the method, and ``LiveTriageContextReader`` implements+ it: **missing here and production has no source at all**;+* ``FrozenTriageContextReader`` implements it: **missing here and the reader+ raises mid-replay, or worse, falls through to a live read**;+* ``ContextSnapshot`` holds the store, ``capture_context`` filters it against+ the split, and ``as_method_note`` publishes what it kept and dropped:+ **missing here and the freeze is real but unaudited, so a reader cannot+ tell how much of the context was checked**.++What this reads, and in both directions+----------------------------------------+Structurally, with ``ast``. Nothing is imported: these modules pull in httpx,+structlog and the whole worker stack to compare a list of method names.++Forward: a protocol method that either implementation lacks.++Reverse, which is the direction that actually drifts: a *snapshot field* that+``capture_context`` does not accept, or that ``as_method_note`` does not+report. A field added to the snapshot and populated by hand somewhere would+otherwise never be filtered against the split, and the method note would keep+printing a confident provenance block that silently omits it.++``skills_under_test`` is the one exemption, and it is named rather than+inferred. It is the skill backtest's deliberate bypass of the split, and it is+required to appear in ``as_method_note`` with its caveat precisely because it+is not filtered. The gate checks that too, so the bypass cannot become silent.+"""++from __future__ import annotations++import argparse+import ast+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_if_requested # noqa: E402++self_test_if_requested(__file__)++_PERSISTENCE = "services/agents/app/workers/triage_persistence.py"+_SHADOW = "services/agents/app/replay/shadow.py"++_PROTOCOL = "TriageContextReader"+_LIVE = "LiveTriageContextReader"+_FROZEN = "FrozenTriageContextReader"+_SNAPSHOT = "ContextSnapshot"+_CAPTURE = "capture_context"+_METHOD_NOTE = "as_method_note"++#: Snapshot fields that are bookkeeping about the freeze rather than a store+#: it holds. ``split_at`` is the instant itself; the counters are what the+#: method note exists to publish.+_NOT_A_STORE = frozenset(+ {+ "split_at",+ "undated_statements",+ "undated_skills",+ "dropped_statements",+ "dropped_priors",+ "dropped_skills",+ }+)++#: Stores that deliberately bypass the split filter, with the reason. Each+#: must still appear in the method note, because an unfiltered store that is+#: not published is indistinguishable from a leak.+_DELIBERATE_BYPASS = {+ "skills_under_test": (+ "the skill backtest applies a candidate authored after the window on purpose; the method note names and caveats it"+ ),+}+++def _module(root: Path, relative: str) -> ast.Module:+ path = root / relative+ if not path.is_file():+ raise SystemExit(f"FAIL: {relative} is missing; the triage context freeze cannot be checked")+ return ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+++def _class(tree: ast.Module, name: str, relative: str) -> ast.ClassDef:+ for node in ast.walk(tree):+ if isinstance(node, ast.ClassDef) and node.name == name:+ return node+ raise SystemExit(f"FAIL: class {name} was not found in {relative}")+++def _async_methods(node: ast.ClassDef) -> set[str]:+ return {item.name for item in node.body if isinstance(item, ast.AsyncFunctionDef) and not item.name.startswith("_")}+++def _annotated_fields(node: ast.ClassDef) -> list[str]:+ return [item.target.id for item in node.body if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name)]+++def _function(tree: ast.Module, name: str, relative: str) -> ast.FunctionDef:+ for node in ast.walk(tree):+ if isinstance(node, ast.FunctionDef) and node.name == name:+ return node+ raise SystemExit(f"FAIL: function {name} was not found in {relative}")+++def _keyword_params(fn: ast.FunctionDef) -> set[str]:+ return {arg.arg for arg in (*fn.args.args, *fn.args.kwonlyargs)}+++def _method_note_keys(node: ast.ClassDef, relative: str) -> set[str]:+ """Every string key ``as_method_note`` can place in its dict."""+ for item in node.body:+ if not isinstance(item, ast.FunctionDef) or item.name != _METHOD_NOTE:+ continue+ keys: set[str] = set()+ for sub in ast.walk(item):+ if isinstance(sub, ast.Dict):+ keys |= {k.value for k in sub.keys if isinstance(k, ast.Constant) and isinstance(k.value, str)}+ # `note["skills_under_test"] = ...` is a subscript assignment, not+ # a dict literal, and reading only literals would miss exactly the+ # conditional half this gate cares most about.+ elif isinstance(sub, ast.Subscript) and isinstance(sub.slice, ast.Constant) and isinstance(sub.slice.value, str):+ keys.add(sub.slice.value)+ if not keys:+ raise SystemExit(f"FAIL: {_METHOD_NOTE} in {relative} publishes no keys, so the freeze is unaudited")+ return keys+ raise SystemExit(f"FAIL: {_SNAPSHOT}.{_METHOD_NOTE} was not found in {relative}")+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--self-test", action="store_true", help="prove the gate refuses an empty tree")+ parser.parse_args(argv)++ root = repo_root()+ failures: list[str] = []+ checked = 0++ persistence = _module(root, _PERSISTENCE)+ shadow = _module(root, _SHADOW)++ protocol_methods = _async_methods(_class(persistence, _PROTOCOL, _PERSISTENCE))+ if not protocol_methods:+ raise SystemExit(f"FAIL: {_PROTOCOL} declares no methods, so this gate would certify anything")+ live_methods = _async_methods(_class(persistence, _LIVE, _PERSISTENCE))+ frozen_methods = _async_methods(_class(shadow, _FROZEN, _SHADOW))+ checked += len(protocol_methods)++ for label, implemented, relative in (+ (_LIVE, live_methods, _PERSISTENCE),+ (_FROZEN, frozen_methods, _SHADOW),+ ):+ missing = sorted(protocol_methods - implemented)+ if missing:+ failures.append(+ f"{label} in {relative} does not implement {missing}, which {_PROTOCOL} declares. "+ f"A context source the {'frozen' if label == _FROZEN else 'live'} reader lacks is one "+ f"{'a replay cannot freeze' if label == _FROZEN else 'production never reads'}"+ )+ extra = sorted((live_methods & frozen_methods) - protocol_methods)+ if extra:+ failures.append(+ f"{_LIVE} and {_FROZEN} both implement {extra}, which {_PROTOCOL} does not declare. "+ f"A reader method outside the protocol is one the worker reaches by duck typing, so nothing "+ f"requires the next implementation to have it"+ )++ snapshot = _class(shadow, _SNAPSHOT, _SHADOW)+ stores = [f for f in _annotated_fields(snapshot) if f not in _NOT_A_STORE]+ if not stores:+ raise SystemExit(f"FAIL: {_SNAPSHOT} holds no stores, so this gate would certify anything")+ capture_params = _keyword_params(_function(shadow, _CAPTURE, _SHADOW))+ note_keys = _method_note_keys(snapshot, _SHADOW)+ checked += len(stores)++ for store in stores:+ if store not in capture_params:+ failures.append(+ f"{_SNAPSHOT}.{store} is a store that {_CAPTURE} does not accept, so nothing filters it "+ f"against the split and a replay would read it as whatever the caller built by hand"+ )+ if store in _DELIBERATE_BYPASS:+ if store not in note_keys:+ failures.append(+ f"{_SNAPSHOT}.{store} bypasses the split filter ({_DELIBERATE_BYPASS[store]}) and "+ f"{_METHOD_NOTE} does not publish it. An unfiltered store nobody is told about is "+ f"indistinguishable from a leak"+ )+ continue+ # Exact key names rather than a substring search over the note. A+ # loose match passes on a neighbouring key: dropping `skills_frozen`+ # while `skills_dropped_after_split` remains leaves a note that says+ # what was thrown away and never says what was kept, and an+ # "anything mentioning skills" test reports that clean. Proven by+ # injecting exactly that removal.+ for suffix, why in (+ ("frozen", "how much context the replay was given"),+ ("dropped_after_split", "whether the freeze did anything at all"),+ ):+ if f"{store}_{suffix}" not in note_keys:+ failures.append(+ f"{_METHOD_NOTE} does not publish `{store}_{suffix}`, so a reader cannot tell {why} for {_SNAPSHOT}.{store}"+ )++ if not checked:+ print("FAIL: the gate compared nothing, which is indistinguishable from a clean result")+ return 1++ if failures:+ print(f"FAIL: {len(failures)} triage-context-freeze problem(s)\n")+ for failure in failures:+ print(f" - {failure}")+ return 1++ print(+ f"OK: {_PROTOCOL} declares {len(protocol_methods)} context source(s), both readers implement all of "+ f"them, and {len(stores)} snapshot store(s) are each filtered by {_CAPTURE} and published by "+ f"{_METHOD_NOTE}."+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/agents/app/agents/auto_triage_agent.py b/services/agents/app/agents/auto_triage_agent.pyindex a1a1944f2..7316aa4bc 100644--- a/services/agents/app/agents/auto_triage_agent.py+++ b/services/agents/app/agents/auto_triage_agent.py@@ -47,6 +47,12 @@ logger = structlog.get_logger()AUTO_CLOSE_THRESHOLD: float = float(os.getenv("AISOC_AUTO_CLOSE_THRESHOLD", "0.85"))+#: Ceiling on the tenant-skill block in the triage prompt. The API caps each+#: field at authoring time; this is the floor under a body written before+#: those caps existed, and under a skill whose individually-legal fields sum+#: to more prompt than the evidence gets.+_MAX_SKILL_PROMPT_CHARS = 4000+class AutoTriageError(RuntimeError):"""Raised when the LLM auto-triage call or its response parsing fails.@@ -151,6 +157,14 @@ def _build_alert_context(state: InvestigationState) -> str:sanitised and length-capped — the statements interpolate alert-derivedvalues like a process name, so they are tenant-authored but notoperator-typed.++ ``state.tenant_skill`` sits beside it on the same reasoning and with the+ same treatment. It is typed into the console by a user holding+ ``settings:write``, which is the same trust class, and it is capped for+ the reason that applies regardless of trust: the prompt budget is shared+ with the evidence the verdict is supposed to rest on. The block the+ resolver rendered is used verbatim rather than re-rendered here, so the+ text that steered the verdict is the text the provenance record names."""raw = state.raw_alertparts = [@@ -184,10 +198,18 @@ def _build_alert_context(state: InvestigationState) -> str:telemetry = wrap_untrusted("\n".join(parts), label="alert_telemetry")+ preamble: list[str] = []+ skill = state.tenant_skill or {}+ skill_guidance = str(skill.get("triage_guidance") or "").strip()+ if skill_guidance:+ preamble.append(sanitize_text(skill_guidance)[:_MAX_SKILL_PROMPT_CHARS])memory = render_for_prompt(state.organisation_memory)- if not memory:+ if memory:+ preamble.append(sanitize_text(memory))++ if not preamble:return telemetry- return f"{sanitize_text(memory)}\n\n{telemetry}"+ return "\n\n".join([*preamble, telemetry])def _close_truncated_json(fragment: str) -> str:@@ -410,6 +432,14 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:f"LLM confidence: {confidence:.2f}",f"Rationale: {rationale}",]+ # Which version of which skill was in the prompt that produced this+ # verdict. On the basis rather than only in a log line, because this is+ # the field a disputed auto-close is explained from, and a log line is+ # gone long before the dispute arrives.+ skill_ref = str((state.tenant_skill or {}).get("ref") or "")+ if skill_ref:+ owner = str((state.tenant_skill or {}).get("owner") or "unrecorded")+ state.confidence_basis.append(f"Tenant skill applied: {skill_ref} (owner: {owner})")state.add_finding(f"Auto-triage: verdict={verdict}, confidence={confidence:.2f}, latency={elapsed_ms}ms")state.add_finding(f"Auto-triage rationale: {rationale}")diff --git a/services/agents/app/api/replay_router.py b/services/agents/app/api/replay_router.pyindex c4e17caa4..4d2098dde 100644--- a/services/agents/app/api/replay_router.py+++ b/services/agents/app/api/replay_router.py@@ -76,10 +76,18 @@ class FrozenContext(BaseModel):anywhere. A human-authored prior suppresses a matching repeat withoutre-triage, so seeding priors from ground truth would score the groundtruth.++ ``skills`` is filtered against the split on ``activated_at`` like every+ other store. ``skills_under_test`` is not, and that is the whole of a+ skill backtest: the candidate is applied to a window that closed before it+ was written. The snapshot counts and names it separately, and the method+ note carries the caveat, so the bypass is published rather than assumed."""statements: list[dict[str, Any]] = Field(default_factory=list)priors: dict[str, dict[str, Any]] = Field(default_factory=dict)+ skills: list[dict[str, Any]] = Field(default_factory=list)+ skills_under_test: list[dict[str, Any]] = Field(default_factory=list, max_length=8)class ReplayRequest(BaseModel):@@ -148,6 +156,8 @@ async def run_replay(body: ReplayRequest, principal: ScopedPrincipal) -> ReplayRsplit_at=split.split_at,statements=body.context.statements,priors=body.context.priors,+ skills=body.context.skills,+ skills_under_test=body.context.skills_under_test,)try:diff --git a/services/agents/app/context/tenant_skills.py b/services/agents/app/context/tenant_skills.pynew file mode 100644index 000000000..271edf933--- /dev/null+++ b/services/agents/app/context/tenant_skills.py@@ -0,0 +1,415 @@+"""Read the tenant's active skills and turn the matching one into a plan.++Gap-closure Phase 6.1 and 6.2, agents half.++A skill is the customer's own investigation approach, authored in the console.+This module is what makes it steer anything: it reads the active set over the+same round trip organisation memory already uses, picks the one that matches+an alert, and renders it two ways.++* :meth:`ResolvedSkill.strategy` produces a real+ :class:`~app.investigator.strategies.Strategy`, so the deep-investigation+ loop, the depth record and ``check_investigation_depth.py`` all work on a+ tenant skill exactly as they work on a built-in. Nothing downstream needs to+ know a skill is involved.+* :meth:`ResolvedSkill.triage_guidance` produces the prompt block for+ auto-triage, which is the path a replay measures.++Both, because a skill that only changed the pivot plan could not be+backtested: the replay grades triage verdicts, and a plan that never reaches+the verdict would show a delta of zero on every run and look like a skill that+does nothing.++Why a skill outranks a built-in strategy+----------------------------------------+The plan says so, and the reason is that the two are different kinds of claim.+A built-in strategy encodes how an attack behaves in general. A skill encodes+what is true in *this* estate, which is knowledge the built-in cannot have and+cannot be argued out of. When both match, the specific one wins. When no skill+matches, selection is untouched, which is the property the existing strategy+tests assert.++How the text is contained+-------------------------+Skill text is first-party: it is typed into the console by a user holding+``settings:write``, the same trust class as organisation-memory statements and+business-context rules, and unlike a knowledge-base document or an MCP reply+it is not something an attacker can write by planting a log line. So it is+sanitised and capped rather than nonce-fenced, and it is worded as guidance+rather than as instruction: a skill is a reason to consider a verdict, never a+reason to stop looking. The cap matters independently of trust, because the+prompt budget is shared with the evidence the verdict is supposed to rest on.+"""++from __future__ import annotations++import os+import time+from dataclasses import dataclass, field+from typing import Any++import httpx+import structlog++from app.investigator.prompt_sanitizer import sanitize_text+from app.investigator.strategies import Strategy++logger = structlog.get_logger()++__all__ = [+ "MAX_SKILLS_IN_PROMPT",+ "ResolvedSkill",+ "clear_cache",+ "enabled",+ "fetch_skills",+ "select_skill",+ "skills_from_payload",+]++_API_URL = os.getenv("API_SERVICE_URL", "http://api:8000")+_TIMEOUT_S = float(os.getenv("AISOC_TENANT_SKILLS_TIMEOUT_S", "5"))++#: Skills change at human speed: authoring, a backtest and an explicit+#: activation. This sits on the path of every fused alert, so it is cached for+#: the same reason organisation memory is.+_CACHE_TTL_S = float(os.getenv("AISOC_TENANT_SKILLS_TTL_S", "120"))++#: How many skills may be resolved for one tenant at all. A cap exists because+#: the resolver runs per alert and a tenant with three hundred active skills+#: would pay for all of them on every one.+MAX_SKILLS_IN_PROMPT = 50++#: Per-field caps applied at render time. The API caps these at authoring+#: time too; this is the floor under a body written before those caps existed.+_MAX_BLOCK_CHARS = 1200+_MAX_ITEM_CHARS = 400++_cache: dict[str, tuple[float, list[dict[str, Any]]]] = {}+++def enabled() -> bool:+ return os.getenv("AISOC_TENANT_SKILLS_ENABLED", "1").strip().lower() not in {"0", "false", "no", "off"}+++def clear_cache() -> None:+ """Drop cached skills. Tests, and the activation path."""+ _cache.clear()+++@dataclass(frozen=True)+class ResolvedSkill:+ """One active skill, as the agent uses it."""++ skill_id: str+ version: int+ name: str+ owner: str+ plan: tuple[str, ...]+ expected_pivots: tuple[str, ...]+ min_pivots: int = 2+ applies_when: str = ""+ guidance: str = ""+ verdict_guidance: str = ""+ required_evidence: tuple[str, ...] = ()+ escalate_when: tuple[str, ...] = ()+ techniques: tuple[str, ...] = ()+ rule_ids: tuple[str, ...] = ()+ sources: tuple[str, ...] = ()+ keywords: tuple[str, ...] = ()+ activated_at: str | None = None+ expires_at: str | None = None++ @property+ def ref(self) -> str:+ """The pair recorded on an investigation, and the one the history table resolves."""+ return f"{self.skill_id}@v{self.version}"++ @property+ def strategy_id(self) -> str:+ """Namespaced so a tenant skill can never collide with a built-in id.++ Without the prefix a skill called ``generic-triage`` would occupy the+ fallback's identity in the depth cache and in every log line, and a+ reader could not tell which of the two produced a run.+ """+ return f"tenant:{self.skill_id}"++ def strategy(self) -> Strategy:+ """The skill as a :class:`Strategy`, so the loop needs no special case."""+ return Strategy(+ id=self.strategy_id,+ name=self.name,+ applies_when=self.applies_when or "This tenant authored a skill matching this alert.",+ rationale=self._rationale(),+ plan=self.plan,+ expected_pivots=self.expected_pivots,+ min_pivots=self.min_pivots,+ techniques=self.techniques,+ keywords=self.keywords,+ )++ def _rationale(self) -> str:+ parts = [+ f"Tenant skill {self.ref}, authored by {sanitize_text(self.owner)[:200]}. "+ f"This is what this organisation knows about alerts of this shape."+ ]+ if self.guidance:+ parts.append(sanitize_text(self.guidance)[:_MAX_BLOCK_CHARS])+ return " ".join(parts)++ def system_guidance(self) -> str:+ """Investigation guidance: the strategy block plus what the skill adds."""+ blocks = [self.strategy().system_guidance()]+ extra = self._organisation_block(include_verdict=False)+ if extra:+ blocks.append(extra)+ return "\n\n".join(blocks)++ def triage_guidance(self) -> str:+ """The triage-prompt block. Empty when the skill says nothing a verdict uses."""+ return self._organisation_block(include_verdict=True)++ def _organisation_block(self, *, include_verdict: bool) -> str:+ lines: list[str] = []+ if self.guidance:+ lines.append(sanitize_text(self.guidance)[:_MAX_BLOCK_CHARS])+ if include_verdict and self.verdict_guidance:+ lines.append(f"Verdict guidance: {sanitize_text(self.verdict_guidance)[:_MAX_BLOCK_CHARS]}")+ if self.required_evidence:+ rendered = "\n".join(f" - {sanitize_text(item)[:_MAX_ITEM_CHARS]}" for item in self.required_evidence)+ lines.append(+ "Evidence this organisation requires before that verdict is safe. If you could not "+ "establish one of these, say which, and do not close on the guidance alone:\n" + rendered+ )+ if self.escalate_when:+ rendered = "\n".join(f" - {sanitize_text(item)[:_MAX_ITEM_CHARS]}" for item in self.escalate_when)+ lines.append("Escalate to a human regardless of the guidance above if any of these hold:\n" + rendered)++ if not lines:+ return ""+ return (+ f"Organisation skill {self.ref} applies to this alert. It is what this tenant's analysts "+ f"have written down about alerts of this shape, and it is advisory: it is a reason to "+ f"consider a verdict, never a reason to stop looking, and it never overrides direct "+ f"evidence of compromise in the telemetry.\n" + "\n".join(lines)+ )++ def as_provenance(self) -> dict[str, Any]:+ """What the ledger and the investigation record carry.++ The owner travels with the reference because the first question after+ a disputed verdict is who to ask, and resolving that from the id+ requires a database the reader of a ledger row may not have.+ """+ return {+ "skill_id": self.skill_id,+ "version": self.version,+ "ref": self.ref,+ "owner": self.owner,+ "activated_at": self.activated_at,+ "expires_at": self.expires_at,+ }+++@dataclass+class _Candidate:+ skill: ResolvedSkill+ score: int = 0+ reasons: list[str] = field(default_factory=list)+++def skills_from_payload(payload: Any) -> list[dict[str, Any]]:+ """Pull the skill rows out of an API response, tolerating a bad shape."""+ if not isinstance(payload, dict):+ return []+ rows = payload.get("skills")+ if not isinstance(rows, list):+ return []+ return [row for row in rows if isinstance(row, dict)][:MAX_SKILLS_IN_PROMPT]+++def _resolve_one(row: dict[str, Any]) -> ResolvedSkill | None:+ body = row.get("body")+ if not isinstance(body, dict):+ return None+ skill_id = str(row.get("skill_id") or body.get("id") or "").strip()+ if not skill_id:+ return None+ raw_match = body.get("match")+ match: dict[str, Any] = raw_match if isinstance(raw_match, dict) else {}++ def _tuple(value: Any, *, upper: bool = False, lower: bool = False) -> tuple[str, ...]:+ if not isinstance(value, list):+ return ()+ out = []+ for item in value:+ if not isinstance(item, str) or not item.strip():+ continue+ text = item.strip()+ out.append(text.upper() if upper else text.lower() if lower else text)+ return tuple(out)++ plan = _tuple(body.get("plan"))+ pivots = _tuple(body.get("expected_pivots"))+ if not plan or not pivots:+ # Both are required at authoring time. A body missing either was not+ # written by the parser, and a skill with no plan cannot steer.+ logger.warning("tenant_skills.malformed_body", skill_id=skill_id, hint="missing plan or expected_pivots")+ return None++ try:+ version = int(row.get("version") or 0)+ except (TypeError, ValueError):+ version = 0+ if version < 1:+ # A version of zero is not a version. The pair recorded on the+ # investigation would resolve to nothing in the history table, which+ # is provenance that looks real and is not.+ logger.warning("tenant_skills.unversioned", skill_id=skill_id)+ return None++ return ResolvedSkill(+ skill_id=skill_id,+ version=version,+ name=str(body.get("name") or skill_id),+ owner=str(body.get("owner") or ""),+ plan=plan,+ expected_pivots=pivots,+ min_pivots=max(1, min(int(body.get("min_pivots") or 2), len(pivots))),+ applies_when=str(body.get("applies_when") or ""),+ guidance=str(body.get("guidance") or ""),+ verdict_guidance=str(body.get("verdict_guidance") or ""),+ required_evidence=_tuple(body.get("required_evidence")),+ escalate_when=_tuple(body.get("escalate_when")),+ techniques=_tuple(match.get("techniques"), upper=True),+ rule_ids=_tuple(match.get("rule_ids")),+ sources=_tuple(match.get("sources"), lower=True),+ keywords=_tuple(match.get("keywords"), lower=True),+ activated_at=str(row.get("activated_at")) if row.get("activated_at") else None,+ expires_at=str(row.get("expires_at")) if row.get("expires_at") else None,+ )+++def select_skill(+ rows: list[dict[str, Any]],+ *,+ summary: str = "",+ techniques: list[str] | None = None,+ rule_id: str | None = None,+ source: str | None = None,+) -> ResolvedSkill | None:+ """Pick the skill that best matches an alert, or ``None``.++ Scoring mirrors :func:`app.investigator.strategies.select_strategy` so an+ author who understands one understands the other: a deliberate+ classification outranks a keyword. A rule id is the most specific claim an+ author can make, so it outranks a technique; a technique outranks a+ source, which is a whole product's worth of alerts; keywords are last.++ Ties break on skill id, not on list order. A tenant with two skills+ scoring equally must get the same one on every alert, or the same alert+ triaged twice produces two different plans for no reason a reader can see.+ """+ mapped = {str(t).upper() for t in (techniques or [])}+ text = (summary or "").lower()+ rule = (rule_id or "").strip()+ src = (source or "").strip().lower()++ best: _Candidate | None = None+ for row in rows[:MAX_SKILLS_IN_PROMPT]:+ skill = _resolve_one(row)+ if skill is None:+ continue+ candidate = _Candidate(skill=skill)++ if rule and rule in skill.rule_ids:+ candidate.score += 20+ candidate.reasons.append(f"rule_id={rule}")+ for technique in skill.techniques:+ # A sub-technique alert matches a skill written against the+ # parent, the same reading select_strategy uses.+ if any(m == technique or m.startswith(technique + ".") for m in mapped):+ candidate.score += 10+ candidate.reasons.append(f"technique={technique}")+ break+ if src and src in skill.sources:+ candidate.score += 5+ candidate.reasons.append(f"source={src}")+ matched_keywords = [k for k in skill.keywords if k in text]+ if matched_keywords:+ candidate.score += 2 * len(matched_keywords)+ candidate.reasons.append("keywords=" + ",".join(matched_keywords[:4]))++ if candidate.score == 0:+ continue+ if best is None or candidate.score > best.score or (candidate.score == best.score and skill.skill_id < best.skill.skill_id):+ best = candidate++ if best is None:+ return None+ logger.info(+ "tenant_skills.selected",+ skill=best.skill.ref,+ score=best.score,+ matched_on=",".join(best.reasons),+ )+ return best.skill+++async def fetch_skills(tenant_id: str | None) -> list[dict[str, Any]]:+ """Active, unexpired skills for a tenant, or ``[]``. Never raises.++ Fail-soft for the same reason organisation memory is: an investigation+ without the tenant's skill is degraded, and one that dies because a skill+ lookup failed is worse than the gap it was closing. A cached set is served+ through a brief outage rather than dropping the tenant's guidance.+ """+ if not enabled() or not tenant_id:+ return []++ cached = _cache.get(tenant_id)+ now = time.monotonic()+ if cached is not None and now - cached[0] < _CACHE_TTL_S:+ return cached[1]++ token = os.getenv("AISOC_AGENTS_SERVICE_TOKEN", "").strip() or os.getenv("AISOC_SERVICE_TOKEN", "").strip()+ if not token:+ # Loud, like the organisation-memory and MCP-registry equivalents:+ # without the shared secret the API refuses the service path, so every+ # investigation would silently run without the guidance an operator+ # authored, backtested and activated.+ logger.warning(+ "tenant_skills.no_service_token",+ reason="AISOC_AGENTS_SERVICE_TOKEN is unset, so active tenant skills cannot be read",+ )+ return []++ # Two path segments rather than one. A single `/resolved` would be matched+ # by `GET /tenant-skills/{skill_id}` on any deployment where the route+ # order changed, and the symptom would be a 404 for a tenant whose skill+ # happened not to be called "resolved".+ url = f"{_API_URL.rstrip('/')}/api/v1/tenant-skills/resolved/active"+ try:+ async with httpx.AsyncClient(timeout=_TIMEOUT_S) as client:+ response = await client.get(+ url,+ params={"tenant_id": tenant_id},+ headers={"X-AiSOC-Service-Token": token},+ )+ except httpx.HTTPError as exc:+ logger.warning("tenant_skills.unreachable", error=str(exc)[:300])+ return cached[1] if cached else []++ if response.status_code >= 400:+ logger.warning("tenant_skills.refused", status_code=response.status_code)+ return cached[1] if cached else []++ try:+ payload = response.json()+ except ValueError:+ logger.warning("tenant_skills.bad_response")+ return cached[1] if cached else []++ rows = skills_from_payload(payload)+ _cache[tenant_id] = (now, rows)+ return rowsdiff --git a/services/agents/app/investigator/deep_investigation.py b/services/agents/app/investigator/deep_investigation.pyindex a99cc8e17..b6f4751d5 100644--- a/services/agents/app/investigator/deep_investigation.py+++ b/services/agents/app/investigator/deep_investigation.py@@ -33,6 +33,8 @@ from typing import Anyimport structlog+from app.context import tenant_skills+from app.context.tenant_skills import ResolvedSkillfrom app.core.cost_governor import get_governorfrom app.investigator import ledgerfrom app.investigator.strategies import Strategy, select_strategy@@ -118,6 +120,12 @@ class DeepInvestigationResult:#: without going to the ledger to find out.mcp_tools: list[str] = field(default_factory=list)mcp_refusals: list[str] = field(default_factory=list)+ #: The tenant skill that supplied this run's plan, if one matched, and the+ #: version of it. Recorded on the result rather than derivable from+ #: ``strategy_id`` alone, because the id names which skill and a verdict+ #: disputed six months later needs to know which *text*, and the version+ #: history is what turns the pair back into text.+ tenant_skill: dict[str, Any] | None = Noneerror: str | None = None@property@@ -147,6 +155,7 @@ class DeepInvestigationResult:"ledger_rows": self.ledger_rows,"mcp_tools": self.mcp_tools,"mcp_refusals": self.mcp_refusals,+ "tenant_skill": self.tenant_skill,"error": self.error,}@@ -161,6 +170,12 @@ class DeepInvestigationResult:if self.narrative:out.append(self.narrative.strip())+ if self.tenant_skill:+ out.append(+ f"Investigation plan came from this organisation's own skill "+ f"{self.tenant_skill.get('ref')} (owner: {self.tenant_skill.get('owner') or 'unrecorded'}), "+ f"which outranks the built-in strategy for alerts of this shape."+ )if self.pivots:out.append(f"Investigation depth: {self.distinct_pivots} distinct pivots "@@ -193,6 +208,62 @@ class DeepInvestigationResult:_STRATEGY_CACHE: dict[str, Strategy] = {}+async def _resolve_tenant_skill(+ state: Any,+ *,+ tenant_id: str,+ summary: str,+ techniques: list[str],+) -> ResolvedSkill | None:+ """The tenant skill matching this alert, or ``None``.++ Prefers a skill the triage path already resolved onto the state, so one+ investigation cannot be steered by one version of a skill and triaged+ under another: the fetch is cached, but a cache expiry between the two+ reads is exactly the window in which an activation would split them. When+ the state carries no skill the resolver runs here, because deep+ investigation is also reachable from the case path, which never went+ through triage.++ Failure is a ``None`` and a log line. The built-in strategy library is the+ fallback, which is the behaviour before this phase.+ """+ carried = getattr(state, "tenant_skill", None)+ rows: list[dict[str, Any]]+ try:+ rows = await tenant_skills.fetch_skills(tenant_id)+ except Exception as exc: # noqa: BLE001 - guidance is advisory, the investigation is not+ logger.warning("deep_investigation.skill_lookup_failed", error=str(exc)[:200])+ return None++ if isinstance(carried, dict) and carried.get("skill_id"):+ pinned = [+ row+ for row in rows+ if str(row.get("skill_id")) == str(carried["skill_id"]) and int(row.get("version") or 0) == int(carried.get("version") or 0)+ ]+ if pinned:+ rows = pinned+ else:+ # The version triage used is no longer served. Saying so is the+ # point: the alternative is silently investigating under a+ # different version than the verdict will be explained by.+ logger.warning(+ "deep_investigation.skill_version_moved",+ skill=carried.get("ref"),+ hint="triage and investigation would otherwise run under different versions of this skill",+ )++ raw = getattr(state, "raw_alert", {}) or {}+ return tenant_skills.select_skill(+ rows,+ summary=summary,+ techniques=techniques,+ rule_id=str(raw.get("rule_id") or "") or None,+ source=str(raw.get("connector_type") or raw.get("source") or "") or None,+ )++_SYSTEM_PREAMBLE = """You are a senior SOC analyst investigating a security alert.You have two kinds of tool. Some query AiSOC's own event lake. Others reach@@ -377,9 +448,22 @@ async def run_deep_investigation(summary = getattr(state, "alert_summary", "") or ""techniques = list(getattr(state, "mitre_mappings", None) or [])- strategy = select_strategy(summary=summary, techniques=techniques)+ # Phase 6.2: a tenant skill outranks a built-in strategy when it matches.+ # The two are different kinds of claim: a built-in encodes how an attack+ # behaves in general, a skill encodes what is true in this estate, and the+ # specific one wins. When nothing matches, selection is exactly what it+ # was, which is what keeps the existing strategy-selection tests honest.+ skill = await _resolve_tenant_skill(state, tenant_id=tenant_id, summary=summary, techniques=techniques)+ if skill is not None:+ strategy = skill.strategy()+ system_guidance = skill.system_guidance()+ else:+ strategy = select_strategy(summary=summary, techniques=techniques)+ system_guidance = strategy.system_guidance()_STRATEGY_CACHE[strategy.id] = strategyresult = DeepInvestigationResult(strategy_id=strategy.id)+ if skill is not None:+ result.tenant_skill = skill.as_provenance()if not ENABLED:result.error = "deep investigation disabled (AISOC_DEEP_INVESTIGATION)"@@ -419,7 +503,7 @@ async def run_deep_investigation(# One `system` string that both of the bindings below extend. Two# f-strings each composing their own would mean whichever ran second# silently dropped the first one's addition.- system = f"{_SYSTEM_PREAMBLE}\n\n{strategy.system_guidance()}{coverage}"+ system = f"{_SYSTEM_PREAMBLE}\n\n{system_guidance}{coverage}"# Third-party MCP servers this tenant registered, if any. The toolset# carries its own nonce, and the standing data-only rule for thatdiff --git a/services/agents/app/models/state.py b/services/agents/app/models/state.pyindex ea01e22ca..31bd7b0c4 100644--- a/services/agents/app/models/state.py+++ b/services/agents/app/models/state.py@@ -70,6 +70,14 @@ class InvestigationState(BaseModel):# the worker's own timeline, and so a test can set it directly.organisation_memory: list[dict[str, Any]] = Field(default_factory=list)+ # The tenant skill that matched this alert, if any, and the version of it.+ # Carried for the same reason organisation memory is, plus one more: this+ # is the provenance a disputed verdict is explained from months later, so+ # it travels with the verdict rather than being recoverable only by+ # re-running the resolver against a store that has since changed.+ # `{"skill_id": ..., "version": N, "ref": "id@vN", "owner": ...}`.+ tenant_skill: dict[str, Any] | None = None+# Findings accumulated during investigationfindings: list[str] = Field(default_factory=list)ioc_enrichments: dict[str, Any] = Field(default_factory=dict)diff --git a/services/agents/app/replay/shadow.py b/services/agents/app/replay/shadow.pyindex ea22395be..dcc050ab4 100644--- a/services/agents/app/replay/shadow.py+++ b/services/agents/app/replay/shadow.py@@ -40,6 +40,25 @@ sees how much of the frozen context could actually be checked against thesplit. Silently dropping them would understate the context production gets;silently keeping them while claiming a clean point-in-time freeze wouldoverstate the guarantee.++Tenant skills, and the one thing here that bypasses the split on purpose+------------------------------------------------------------------------+Gap-closure Phase 6.2 added a fourth store. A tenant skill carries+``activated_at``, so unlike an organisation-memory statement it *can* be+tested against the split, and :func:`capture_context` drops one activated+after it exactly as it drops a late statement.++:attr:`ContextSnapshot.skills_under_test` is the deliberate exception, and it+is the honest way to do the one thing a skill backtest has to do. Measuring a+skill authored today against history from last quarter means applying guidance+whose author may have read those very alerts. Freezing it out would make the+backtest measure nothing; applying it silently would publish an accuracy+number an author could raise by writing a skill that restates the labels. So+the candidate travels in its own field, the method note names it and counts it+separately from the frozen set, and+:meth:`ContextSnapshot.as_method_note` publishes the caveat rather than+leaving a reader to work it out. A skill under test is scored, and the reader+is told the score is a statement about this window rather than a forecast."""from __future__ import annotations@@ -57,10 +76,18 @@ __all__ = ["capture_context",]-#: Keys that may carry a row's recorded time, newest-authority first. Both-#: the outcome-prior shape (``first_seen`` / ``last_seen``) and the generic-#: SQL shapes are covered so one function serves both stores.-_TIME_KEYS: tuple[str, ...] = ("last_seen", "updated_at", "created_at", "first_seen", "recorded_at")+#: Keys that may carry a row's recorded time, newest-authority first. The+#: outcome-prior shape (``first_seen`` / ``last_seen``), the tenant-skill+#: shape (``activated_at``) and the generic SQL shapes are all covered so one+#: function serves every store.+_TIME_KEYS: tuple[str, ...] = (+ "last_seen",+ "activated_at",+ "updated_at",+ "created_at",+ "first_seen",+ "recorded_at",+)class ShadowTriageWriter:@@ -164,25 +191,60 @@ class ContextSnapshot:statements: tuple[Mapping[str, Any], ...] = ()priors: Mapping[str, Mapping[str, Any]] = field(default_factory=dict)+ #: Tenant skills active as of the split. Filtered on ``activated_at``, so+ #: unlike statements these can be tested against it.+ skills: tuple[Mapping[str, Any], ...] = ()++ #: Skills applied on purpose despite being authored after the split. This+ #: is the skill backtest, and it is the only thing in this class that+ #: bypasses the freeze. See the module docstring.+ skills_under_test: tuple[Mapping[str, Any], ...] = ()+#: Statements kept because they carry no recorded time to test against the#: split. Reported so the freeze is not claimed to be tighter than it is.undated_statements: int = 0+ #: The same limit for skills. Should be zero: a skill reaching the+ #: resolver has an activation stamp by construction. Counted anyway,+ #: because "should be zero" is how the statement gap went unnoticed.+ undated_skills: int = 0+#: Rows dropped for carrying a time after the split. A non-zero value is#: the freeze doing its job and is worth seeing.dropped_statements: int = 0dropped_priors: int = 0+ dropped_skills: int = 0++ def all_skills(self) -> tuple[Mapping[str, Any], ...]:+ """Frozen skills plus anything explicitly under test.++ One accessor rather than two reads at each call site, so a caller+ cannot use the frozen set and quietly forget the candidate, which+ would make every backtest report a delta of zero.+ """+ return (*self.skills, *self.skills_under_test)def as_method_note(self) -> dict[str, Any]:"""The provenance block the replay report publishes about its own context."""- return {+ note: dict[str, Any] = {"split_at": self.split_at.isoformat(),"statements_frozen": len(self.statements),"statements_without_timestamp": self.undated_statements,"statements_dropped_after_split": self.dropped_statements,"priors_frozen": len(self.priors),"priors_dropped_after_split": self.dropped_priors,+ "skills_frozen": len(self.skills),+ "skills_without_timestamp": self.undated_skills,+ "skills_dropped_after_split": self.dropped_skills,}+ if self.skills_under_test:+ note["skills_under_test"] = [_skill_ref(s) for s in self.skills_under_test]+ note["skills_under_test_caveat"] = (+ "These skills were authored after this window closed and were applied to it on purpose, "+ "which is what a backtest is. Their author may have seen these alerts, so the result "+ "measures the skill against this window and is not a forecast of its accuracy on new alerts."+ )+ return notedef _recorded_time(row: Mapping[str, Any]) -> datetime | None:@@ -199,13 +261,28 @@ def _recorded_time(row: Mapping[str, Any]) -> datetime | None:return None+def _skill_ref(row: Mapping[str, Any]) -> str:+ """``skill-id@vN``, the pair an investigation records."""+ body = row.get("body") if isinstance(row.get("body"), Mapping) else {}+ skill_id = row.get("skill_id") or (body or {}).get("id") or "unknown"+ return f"{skill_id}@v{row.get('version', '?')}"++def capture_context(*,split_at: datetime,statements: Iterable[Mapping[str, Any]] = (),priors: Mapping[str, Mapping[str, Any]] | None = None,+ skills: Iterable[Mapping[str, Any]] = (),+ skills_under_test: Iterable[Mapping[str, Any]] = (),) -> ContextSnapshot:- """Freeze organisation memory and outcome priors as of ``split_at``."""+ """Freeze organisation memory, outcome priors and tenant skills as of ``split_at``.++ ``skills_under_test`` is passed through unfiltered by design: it is the+ candidate a backtest exists to measure, and it is counted and named+ separately in the method note so the bypass is published rather than+ assumed. See the module docstring.+ """kept: list[Mapping[str, Any]] = []undated = 0dropped_statements = 0@@ -229,13 +306,31 @@ def capture_context(continuekept_priors[str(signature)] = dict(prior)+ kept_skills: list[Mapping[str, Any]] = []+ undated_skills = 0+ dropped_skills = 0+ for row in skills:+ recorded = _recorded_time(row)+ if recorded is None:+ undated_skills += 1+ kept_skills.append(dict(row))+ continue+ if recorded > split_at:+ dropped_skills += 1+ continue+ kept_skills.append(dict(row))+return ContextSnapshot(split_at=split_at,statements=tuple(kept),priors=kept_priors,+ skills=tuple(kept_skills),+ skills_under_test=tuple(dict(row) for row in skills_under_test),undated_statements=undated,+ undated_skills=undated_skills,dropped_statements=dropped_statements,dropped_priors=dropped_priors,+ dropped_skills=dropped_skills,)@@ -267,3 +362,11 @@ class FrozenTriageContextReader:self.reads["lookup_prior"] += 1prior = self._snapshot.priors.get(signature)return dict(prior) if prior is not None else None++ async def fetch_skills(self, tenant_id: str | None) -> list[dict[str, Any]]:+ self.reads["fetch_skills"] += 1+ # Frozen set plus anything under test, copied per call for the same+ # reason statements are: the resolver reads these per alert and a+ # shared mutable list would let one alert's triage edit the next+ # alert's guidance.+ return [dict(row) for row in self._snapshot.all_skills()]diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.pyindex 67ba7391a..35fc3e1d3 100644--- a/services/agents/app/workers/fused_alert_consumer.py+++ b/services/agents/app/workers/fused_alert_consumer.py@@ -45,6 +45,7 @@ from app.agents.auto_triage_agent import run_auto_triagefrom app.agents.dispositions import AUTO_CLOSEABLE_DISPOSITIONS, NEEDS_REVIEW, normalize_dispositionfrom app.agents.triage_agent import run_triagefrom app.confidence.groundedness import score_groundedness+from app.context.tenant_skills import select_skillfrom app.core.cost_governor import Decision, get_governorfrom app.core.cost_telemetry import CostSummary, CostTrackerfrom app.graph.runner import default_budget, run_escalation@@ -110,6 +111,11 @@ _METRICS = {# symptom of that is a scorecard that stays empty rather than an error."shadow_triaged": 0,"shadow_decisions_recorded": 0,+ # Phase 6.1. An operator who authored, backtested and activated a skill+ # needs to see that it is reaching alerts; zero here with an active skill+ # is the difference between "my guidance is not helping" and "my guidance+ # was never read".+ "tenant_skill_applied": 0,"errors": 0,}@@ -545,6 +551,12 @@ class FusedAlertTriageWorker:# LLM call is going to happen. Never raises; an empty list just# means the prompt is what it was before.state.organisation_memory = await self._reader.fetch_statements(str(state.tenant_id))+ # Phase 6.1: the tenant's own skill for this shape of alert.+ # Read through the same port for the same reason: it is durable+ # state a verdict depends on, so the replay freeze has to be+ # able to reach it. Selection is per alert and cheap; the fetch+ # behind it is cached.+ await self._attach_tenant_skill(state)# Bind a CostTracker so every LLM call on this path records its# token/cost (safe_ainvoke -> record_llm_call) — previously the# highest-volume LLM spend was recorded as $0 and invisible.@@ -795,6 +807,40 @@ class FusedAlertTriageWorker:_METRICS["approvals_raised"] += 1return raised+ async def _attach_tenant_skill(self, state: InvestigationState) -> None:+ """Resolve the tenant skill matching this alert and record it on the state.++ Best-effort in exactly one direction: a lookup that fails leaves the+ state without a skill and triage proceeds as it did before. The+ opposite failure, a skill that matched and was not recorded, is the one+ that matters, because the verdict would then carry guidance with no+ provenance. So the selection and the record happen together.+ """+ try:+ rows = await self._reader.fetch_skills(str(state.tenant_id))+ except Exception as exc: # noqa: BLE001 - guidance is advisory, triage is not+ logger.warning("auto_triage_worker.skill_lookup_failed", error=str(exc)[:200])+ return+ if not rows:+ return++ raw = state.raw_alert or {}+ skill = select_skill(+ rows,+ summary=state.alert_summary or "",+ techniques=list(state.mitre_mappings or []),+ rule_id=str(raw.get("rule_id") or "") or None,+ source=str(raw.get("connector_type") or raw.get("source") or "") or None,+ )+ if skill is None:+ return++ state.tenant_skill = skill.as_provenance()+ guidance = skill.triage_guidance()+ if guidance:+ state.tenant_skill["triage_guidance"] = guidance+ _METRICS["tenant_skill_applied"] += 1+async def _maybe_suppress_from_memory(self,state: InvestigationState,diff --git a/services/agents/app/workers/triage_persistence.py b/services/agents/app/workers/triage_persistence.pyindex b968e9838..637f47980 100644--- a/services/agents/app/workers/triage_persistence.py+++ b/services/agents/app/workers/triage_persistence.py@@ -51,7 +51,7 @@ from __future__ import annotationsfrom typing import Any, Protocol, runtime_checkable-from app.context import organisation_memory+from app.context import organisation_memory, tenant_skillsfrom app.investigator import ledger as ledger_modulefrom app.investigator import siem_writebackfrom app.memory import outcomes as outcomes_module@@ -164,9 +164,14 @@ class TriageWriter(Protocol):class TriageContextReader(Protocol):"""The durable state a verdict is allowed to depend on.- Both methods must be total. Production's implementations already are:- neither ``fetch_statements`` nor ``lookup_prior`` may take triage down- when the store behind it is unreachable.+ Every method must be total. Production's implementations already are: none+ of them may take triage down when the store behind it is unreachable.++ This protocol is the seam the replay freeze acts on, so **a new context+ source belongs here or it is not point-in-time**. A source read directly+ from the worker would be live during a replay no matter what the snapshot+ said, and the report would be measuring a world the split point does not+ describe."""async def fetch_statements(self, tenant_id: str | None) -> list[dict[str, Any]]:@@ -175,6 +180,9 @@ class TriageContextReader(Protocol):async def lookup_prior(self, tenant_id: str, signature: str) -> dict[str, Any] | None:"""The durable outcome prior for an evidence signature, or ``None``."""+ async def fetch_skills(self, tenant_id: str | None) -> list[dict[str, Any]]:+ """The tenant's active, unexpired investigation skills."""+class LiveTriageWriter:"""The production sink. Every method is the call the worker used to make inline.@@ -277,3 +285,6 @@ class LiveTriageContextReader:async def lookup_prior(self, tenant_id: str, signature: str) -> dict[str, Any] | None:return await outcomes_module.lookup_prior(tenant_id, signature)++ async def fetch_skills(self, tenant_id: str | None) -> list[dict[str, Any]]:+ return await tenant_skills.fetch_skills(tenant_id)diff --git a/services/agents/tests/test_replay_leakage.py b/services/agents/tests/test_replay_leakage.pyindex 22ad5fd66..4c722f277 100644--- a/services/agents/tests/test_replay_leakage.py+++ b/services/agents/tests/test_replay_leakage.py@@ -4,10 +4,10 @@ Gap-closure Phase 1.5, and the test the phase is really about. A replay reportwhose test window fed itself is worse than no report: it is a number with amethod section that reads correctly and a result that is circular.-Three routes exist from a test-window decision back into a later test-window-decision, and they run through three different stores. Each gets its own test,+Four routes exist from a test-window decision back into a later test-window+decision, and they run through four different stores. Each gets its own test,because "no leakage" failing as one assertion tells a future reader nothing-about which of the three broke.+about which of them broke.1. **Outcome memory.** Production writes every durable verdict back as aper-signature prior, and looks a prior up *before* triage. Two findings@@ -22,6 +22,20 @@ about which of the three broke.triage prompt. Nothing in the test window writes a statement directly, butthe read is live in production and a mid-run refresh picks up whatever theconsole wrote while the replay was running.+4. **Tenant skills** (Phase 6.1). Customer-authored guidance that reaches the+ same prompt, and the one store here whose rows are *written to influence+ verdicts on purpose*. A skill activated during the test window, or authored+ after it by somebody who read it, steers every later alert it matches.+ Unlike organisation memory these rows carry ``activated_at``, so the split+ filter has something to test and the freeze can be complete rather than+ partial.++ The deliberate bypass is tested here too, in its own test rather than as an+ exception buried in another. ``skills_under_test`` is how a backtest+ applies a candidate to a window that closed before it was written, and the+ property under test is not that it is refused, it is that the method note+ **names it and carries the caveat**. An unfiltered store nobody is told+ about is indistinguishable from a leak.Every test here is checked for sensitivity-------------------------------------------@@ -43,6 +57,7 @@ from typing import Anyimport pytestfrom app.agents.dispositions import BENIGN, FALSE_POSITIVE, NEEDS_REVIEW, normalize_dispositionfrom app.context import organisation_memory+from app.context import tenant_skills as tenant_skills_modulefrom app.memory import outcomes as outcomes_modulefrom app.models.state import AgentStatus, InvestigationStatefrom app.replay.findings import HistoricalFinding@@ -352,6 +367,166 @@ def _envelope() -> dict[str, Any]:}+# --------------------------------------------------------------------------+# 4. Tenant skills+# --------------------------------------------------------------------------+++def _skill_row(skill_id: str, *, activated_at: str, guidance: str) -> dict[str, Any]:+ """One resolved-skill row in the shape the API's internal route serves."""+ return {+ "skill_id": skill_id,+ "version": 1,+ "activated_at": activated_at,+ "expires_at": "2099-01-01T00:00:00+00:00",+ "body": {+ "id": skill_id,+ "name": skill_id,+ "owner": "[email protected]",+ "expires_at": "2099-01-01T00:00:00+00:00",+ "match": {"rule_ids": ["rule-service-logon"], "techniques": [], "sources": [], "keywords": []},+ "guidance": guidance,+ "verdict_guidance": "",+ "required_evidence": [],+ "escalate_when": [],+ "plan": ["Check what executed on the host."],+ "expected_pivots": ["process_activity", "entity_timeline"],+ "min_pivots": 2,+ },+ }+++async def test_triage_reads_the_skills_frozen_at_the_split_not_whatever_is_active_now(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The skill that reaches the prompt is the snapshot's, at the split.++ Asserting on the prompt input rather than on the verdict, for the same+ reason the organisation-memory test does: a verdict can be unchanged by a+ leak that nonetheless happened, and the property under test is what the+ model was allowed to see.+ """+ captured: list[dict[str, Any] | None] = []++ async def _capture(state: InvestigationState) -> InvestigationState:+ captured.append(dict(state.tenant_skill) if state.tenant_skill else None)+ state.verdict = FALSE_POSITIVE+ state.confidence = 0.5+ state.status = AgentStatus.RUNNING+ return state++ async def _resolve(tenant_id: str) -> _StubLlmConfig:+ return _StubLlmConfig()++ async def _live_skills(tenant_id: str | None) -> list[dict[str, Any]]:+ return [_skill_row("poison-skill", activated_at="2026-06-01T00:00:00Z", guidance="POISON: activated after the split")]++ monkeypatch.delenv("AISOC_DETERMINISTIC", raising=False)+ monkeypatch.setattr(worker_module, "run_auto_triage", _capture)+ monkeypatch.setattr(worker_module, "resolve_llm_config", _resolve)+ monkeypatch.setattr(tenant_skills_module, "fetch_skills", _live_skills)+ tenant_skills_module.clear_cache()++ frozen = capture_context(+ split_at=_SPLIT,+ skills=[+ _skill_row("frozen-skill", activated_at="2026-04-01T00:00:00Z", guidance="Frozen at the split"),+ _skill_row("poison-skill", activated_at="2026-06-01T00:00:00Z", guidance="POISON: activated after the split"),+ ],+ )+ # The freeze did something, and the number says so rather than the absence+ # of a poisoned prompt implying it.+ assert frozen.dropped_skills == 1+ assert frozen.undated_skills == 0++ worker = FusedAlertTriageWorker(+ bootstrap_servers="",+ writer=ShadowTriageWriter(),+ context_reader=FrozenTriageContextReader(frozen),+ )+ summary = await worker.triage(_envelope())+ assert summary is not None++ assert len(captured) == 1 and captured[0] is not None+ assert captured[0]["skill_id"] == "frozen-skill"+ assert "Frozen at the split" in captured[0]["triage_guidance"]+ assert "POISON" not in captured[0]["triage_guidance"]++ # Sensitivity: the same worker with the live reader does see the poison.+ # Without this the test above passes just as well against a build where+ # skills never reach the prompt at all.+ live_worker = FusedAlertTriageWorker(+ bootstrap_servers="",+ writer=ShadowTriageWriter(),+ context_reader=LiveTriageContextReader(),+ )+ captured.clear()+ await live_worker.triage(_envelope())+ assert len(captured) == 1 and captured[0] is not None+ assert captured[0]["skill_id"] == "poison-skill"+ assert "POISON: activated after the split" in captured[0]["triage_guidance"]+++async def test_a_skill_under_test_reaches_the_prompt_and_is_named_in_the_method_note(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The backtest bypass works, and it is published rather than silent.++ Two assertions, and the second is the one that matters. A candidate+ authored after the window *must* reach the prompt or a backtest measures+ nothing. It must also appear in the method note with its caveat, because+ an accuracy figure produced by guidance written after the window is a+ statement about that window and not a forecast, and a reader who is not+ told cannot know which they are holding.+ """+ captured: list[dict[str, Any] | None] = []++ async def _capture(state: InvestigationState) -> InvestigationState:+ captured.append(dict(state.tenant_skill) if state.tenant_skill else None)+ state.verdict = FALSE_POSITIVE+ state.confidence = 0.5+ state.status = AgentStatus.RUNNING+ return state++ async def _resolve(tenant_id: str) -> _StubLlmConfig:+ return _StubLlmConfig()++ monkeypatch.delenv("AISOC_DETERMINISTIC", raising=False)+ monkeypatch.setattr(worker_module, "run_auto_triage", _capture)+ monkeypatch.setattr(worker_module, "resolve_llm_config", _resolve)++ candidate = _skill_row("candidate-skill", activated_at="2026-09-01T00:00:00Z", guidance="Authored after the window")+ snapshot = capture_context(split_at=_SPLIT, skills=[], skills_under_test=[candidate])++ # Not filtered, unlike everything else in the snapshot.+ assert snapshot.skills == ()+ assert snapshot.dropped_skills == 0+ assert [dict(s) for s in snapshot.skills_under_test] == [candidate]++ note = snapshot.as_method_note()+ assert note["skills_under_test"] == ["candidate-skill@v1"]+ assert "authored after this window closed" in note["skills_under_test_caveat"]+ assert "not a forecast" in note["skills_under_test_caveat"]++ worker = FusedAlertTriageWorker(+ bootstrap_servers="",+ writer=ShadowTriageWriter(),+ context_reader=FrozenTriageContextReader(snapshot),+ )+ await worker.triage(_envelope())+ assert len(captured) == 1 and captured[0] is not None+ assert captured[0]["ref"] == "candidate-skill@v1"++ # Sensitivity: an ordinary replay of the same instant freezes it out, so+ # the bypass is the backtest's and not the snapshot's default behaviour.+ ordinary = capture_context(split_at=_SPLIT, skills=[candidate])+ assert ordinary.skills == ()+ assert ordinary.dropped_skills == 1+ assert "skills_under_test" not in ordinary.as_method_note()++# --------------------------------------------------------------------------# The snapshot itself# --------------------------------------------------------------------------@@ -382,6 +557,29 @@ def test_rows_recorded_after_the_split_are_dropped_from_the_snapshot() -> None:assert snapshot.as_method_note()["statements_without_timestamp"] == 1+def test_a_skill_with_no_activation_stamp_is_counted_the_way_an_undated_statement_is() -> None:+ """Kept, and counted, rather than dropped or silently trusted.++ A resolved skill carries ``activated_at`` by construction, so this should+ never fire in production. It is tested because "should be zero" is exactly+ how the organisation-memory gap went unnoticed for a phase: the number is+ published either way, so a reader sees the limit of the freeze instead of+ inferring it from a clean-looking block.+ """+ snapshot = capture_context(+ split_at=_SPLIT,+ skills=[+ {"skill_id": "dated", "version": 1, "activated_at": "2026-04-01T00:00:00Z", "body": {}},+ {"skill_id": "undated", "version": 1, "body": {}},+ ],+ )++ assert [s["skill_id"] for s in snapshot.skills] == ["dated", "undated"]+ assert snapshot.undated_skills == 1+ assert snapshot.dropped_skills == 0+ assert snapshot.as_method_note()["skills_without_timestamp"] == 1++def test_a_snapshot_taken_at_a_different_instant_is_refused() -> None:"""A freeze from the wrong moment is not a freeze, and must not pass silently."""runner = ReplayRunner(normalizer=_Normalizer(), tenant_id=str(uuid.uuid4()))diff --git a/services/agents/tests/test_tenant_skill_investigation.py b/services/agents/tests/test_tenant_skill_investigation.pynew file mode 100644index 000000000..7c2862283--- /dev/null+++ b/services/agents/tests/test_tenant_skill_investigation.py@@ -0,0 +1,393 @@+"""A tenant skill changes the plan, and the run records which version changed it.++Gap-closure Phase 6.1 and 6.2 gate, agents half.++The phase's "done when" has three clauses and the first and third are here:+a skill authored in the console **changes the investigation plan on matching+alerts**, and **replay shows the delta**. The second, the backtest report+being attached to the activation, is asserted in+``services/api/tests/test_tenant_skills.py`` where the lifecycle lives.++What makes these tests non-vacuous+-----------------------------------+Each one holds everything constant except the skill and asserts on **what the+model was handed**, not on what it answered. A verdict can be unchanged by a+plan that did change, and a plan can look changed because a scripted model was+scripted differently. So the system prompt is captured at the boundary and+compared between two runs of the same alert, and the built-in strategy the+alert would otherwise have selected is asserted by name, so "the skill won"+and "nothing selected anything" are told apart.+"""++from __future__ import annotations++import uuid+from typing import Any++import pytest+from app.context import tenant_skills as skills_module+from app.context.tenant_skills import ResolvedSkill, select_skill+from app.investigator import deep_investigation as deep_module+from app.investigator.strategies import KNOWN_PIVOTS, select_strategy+from app.models.state import InvestigationState++_TENANT = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")+++def _row(+ skill_id: str = "finance-batch-powershell",+ *,+ version: int = 3,+ techniques: list[str] | None = None,+ rule_ids: list[str] | None = None,+ keywords: list[str] | None = None,+ sources: list[str] | None = None,+ plan: list[str] | None = None,+ pivots: list[str] | None = None,+) -> dict[str, Any]:+ """One row in the shape ``GET /tenant-skills/resolved/active`` serves."""+ return {+ "skill_id": skill_id,+ "version": version,+ "activated_at": "2026-09-01T00:00:00+00:00",+ "expires_at": "2099-01-01T00:00:00+00:00",+ "body": {+ "id": skill_id,+ "name": "Finance nightly reconciliation batch",+ "owner": "[email protected]",+ "expires_at": "2099-01-01T00:00:00+00:00",+ "applies_when": "Encoded PowerShell names svc_batch on a FIN-APP host.",+ "match": {+ "techniques": techniques if techniques is not None else ["T1059.001"],+ "rule_ids": rule_ids or [],+ "sources": sources or [],+ "keywords": keywords or [],+ },+ "guidance": "Finance runs a nightly reconciliation batch on FIN-APP-01 to FIN-APP-06 between 02:00 and 04:00 UTC.",+ "verdict_guidance": "Encoded PowerShell from svc_batch on a FIN-APP host inside the window is a benign true positive.",+ "required_evidence": ["The parent process is the scheduled task, not a browser."],+ "escalate_when": ["The host is not one of FIN-APP-01 to FIN-APP-06."],+ # ``if ... is None`` rather than ``or``: an empty list is a case+ # these tests deliberately construct, and ``or`` would silently+ # hand it the default instead.+ "plan": plan if plan is not None else ["Establish the process lineage, which decides this alert on its own."],+ "expected_pivots": pivots if pivots is not None else ["process_tree", "authentication_events"],+ "min_pivots": 2,+ },+ }+++def _state() -> InvestigationState:+ return InvestigationState(+ incident_id=uuid.uuid4(),+ tenant_id=_TENANT,+ alert_summary="Encoded PowerShell launched on FIN-APP-03",+ raw_alert={"rule_id": "rule-encoded-powershell", "connector_type": "crowdstrike", "hostname": "FIN-APP-03"},+ mitre_mappings=["T1059.001"],+ )+++# ---------------------------------------------------------------------------+# Selection+# ---------------------------------------------------------------------------+++class TestSelection:+ def test_a_rule_id_outranks_a_technique_which_outranks_a_source(self) -> None:+ """A rule id is the most specific claim an author can make.++ Scored rather than ordered, so the answer does not depend on which+ skill the API happened to return first.+ """+ rows = [+ _row("by-source", techniques=[], sources=["crowdstrike"]),+ _row("by-technique", techniques=["T1059.001"]),+ _row("by-rule", techniques=[], rule_ids=["rule-encoded-powershell"]),+ ]+ chosen = select_skill(+ rows,+ summary="Encoded PowerShell launched on FIN-APP-03",+ techniques=["T1059.001"],+ rule_id="rule-encoded-powershell",+ source="crowdstrike",+ )+ assert chosen is not None and chosen.skill_id == "by-rule"++ def test_a_sub_technique_alert_matches_a_skill_written_against_the_parent(self) -> None:+ chosen = select_skill([_row(techniques=["T1059"])], techniques=["T1059.001"])+ assert chosen is not None++ def test_nothing_matches_when_no_condition_holds(self) -> None:+ """No match must be no skill, not the first one in the list.++ A resolver that fell back to "any skill" would replace the strategy+ library for every alert in the tenant, which is exactly what the+ authoring-time refusal of an empty match block exists to prevent.+ """+ assert select_skill([_row(techniques=["T1566"])], techniques=["T1078"], summary="impossible travel") is None++ def test_a_tie_breaks_on_skill_id_and_not_on_list_order(self) -> None:+ """The same alert triaged twice must produce the same plan."""+ rows = [_row("zulu", techniques=["T1059.001"]), _row("alpha", techniques=["T1059.001"])]+ first = select_skill(rows, techniques=["T1059.001"])+ second = select_skill(list(reversed(rows)), techniques=["T1059.001"])+ assert first is not None and second is not None+ assert first.skill_id == second.skill_id == "alpha"++ def test_a_row_with_no_version_is_refused(self) -> None:+ """Provenance that resolves to nothing is worse than none.++ ``skill@v0`` would be recorded on the verdict and the version history+ would have no such row, so the record would look like provenance and+ answer nothing.+ """+ row = _row(version=0)+ assert select_skill([row], techniques=["T1059.001"]) is None++ def test_a_row_with_no_plan_is_refused(self) -> None:+ row = _row(plan=[])+ assert select_skill([row], techniques=["T1059.001"]) is None+++# ---------------------------------------------------------------------------+# The skill as a strategy+# ---------------------------------------------------------------------------+++class TestStrategyConversion:+ def test_the_skill_becomes_a_real_strategy_so_nothing_downstream_needs_a_special_case(self) -> None:+ skill = select_skill([_row()], techniques=["T1059.001"])+ assert skill is not None+ strategy = skill.strategy()+ assert strategy.expected_pivots == ("process_tree", "authentication_events")+ assert strategy.min_pivots == 2+ # Namespaced, so a skill called "generic-triage" cannot occupy the+ # fallback's identity in the depth cache or in a log line.+ assert strategy.id == "tenant:finance-batch-powershell"+ assert set(strategy.expected_pivots) <= KNOWN_PIVOTS++ def test_the_guidance_is_advisory_and_says_so(self) -> None:+ """A skill is a reason to consider a verdict, never a reason to stop looking.++ The wording is the control. Skill text is first-party, so it is not+ nonce-fenced; what stops it functioning as an instruction that+ overrides telemetry is that the block says it does not.+ """+ skill = select_skill([_row()], techniques=["T1059.001"])+ assert skill is not None+ block = skill.triage_guidance()+ assert "advisory" in block+ assert "never overrides direct evidence of compromise" in block+ # The evidence bar and the escalation conditions both reach the model,+ # or "the evidence required before a verdict" is a field nothing reads.+ assert "parent process is the scheduled task" in block+ assert "Escalate to a human" in block++ def test_the_provenance_carries_the_owner_beside_the_version(self) -> None:+ skill = select_skill([_row()], techniques=["T1059.001"])+ assert skill is not None+ assert skill.as_provenance() == {+ "skill_id": "finance-batch-powershell",+ "version": 3,+ "ref": "finance-batch-powershell@v3",+ "owner": "[email protected]",+ "activated_at": "2026-09-01T00:00:00+00:00",+ "expires_at": "2099-01-01T00:00:00+00:00",+ }+++# ---------------------------------------------------------------------------+# "Done when": the plan actually changes+# ---------------------------------------------------------------------------+++class _ScriptedModel:+ """A model that calls nothing and answers once, capturing what it was handed."""++ def __init__(self) -> None:+ self.system: str = ""++ async def ainvoke(self, messages: Any, **_: Any) -> Any: # pragma: no cover - not the path used+ raise AssertionError("the tool loop drives this model, not ainvoke")+++def _captured_system(monkeypatch: pytest.MonkeyPatch) -> list[str]:+ """Capture the system prompt the tool loop is given, and answer immediately."""+ seen: list[str] = []++ async def _fake_loop(model: Any, *, system: str, user: str, registry: Any, max_iters: int) -> dict[str, Any]:+ seen.append(system)+ return {"content": "nothing to add", "tool_trace": [], "iterations": 1, "truncated": False}++ monkeypatch.setattr(deep_module, "run_with_tools", _fake_loop)+ monkeypatch.setattr(deep_module, "make_chat_model", lambda *a, **k: _ScriptedModel())+ return seen+++def _no_mcp(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _empty(tenant_id: str, **_: Any) -> Any:+ class _Toolset:+ nonce = "AISOC-test"+ tools: list[Any] = []+ refusals: list[Any] = []++ return _Toolset()++ monkeypatch.setattr(deep_module, "build_mcp_toolset", _empty)+++async def test_done_when_a_skill_changes_the_investigation_plan_on_a_matching_alert(+ monkeypatch: pytest.MonkeyPatch,+ _captured_system: list[str],+) -> None:+ """The phase's acceptance clause, run twice over one alert.++ Everything is held constant except whether the tenant has an active skill.+ The assertion is on the plan the model was handed, because that is what+ "changes the investigation plan" means, and because a verdict could be+ identical either way.++ The built-in strategy is named explicitly so this cannot pass by the alert+ selecting nothing: without the skill this alert selects+ ``endpoint-suspicious-process``, and that is asserted rather than assumed.+ """+ _no_mcp(monkeypatch)+ state = _state()++ builtin = select_strategy(summary=state.alert_summary, techniques=list(state.mitre_mappings))+ assert builtin.id == "endpoint-suspicious-process"++ async def _no_skills(tenant_id: str) -> list[dict[str, Any]]:+ return []++ monkeypatch.setattr(skills_module, "fetch_skills", _no_skills)+ before = await deep_module.run_deep_investigation(state, llm=_ScriptedModel())++ async def _one_skill(tenant_id: str) -> list[dict[str, Any]]:+ return [_row()]++ monkeypatch.setattr(skills_module, "fetch_skills", _one_skill)+ after = await deep_module.run_deep_investigation(_state(), llm=_ScriptedModel())++ # 1. The strategy that drove the run changed.+ assert before.strategy_id == "endpoint-suspicious-process"+ assert after.strategy_id == "tenant:finance-batch-powershell"++ # 2. The plan the model was handed changed, and specifically to the+ # tenant's own steps rather than to some other built-in.+ assert len(_captured_system) == 2+ plan_before, plan_after = _captured_system+ assert "Establish the process lineage, which decides this alert on its own." in plan_after+ assert "Establish the process lineage, which decides this alert on its own." not in plan_before+ assert "Finance runs a nightly reconciliation batch" in plan_after++ # 3. The run records which version guided it, which is what makes a+ # verdict explainable six months later.+ assert before.tenant_skill is None+ assert after.tenant_skill is not None+ assert after.tenant_skill["ref"] == "finance-batch-powershell@v3"+ assert after.as_dict()["tenant_skill"]["owner"] == "[email protected]"+ assert any("finance-batch-powershell@v3" in finding for finding in after.findings())+++async def test_an_unmatched_alert_leaves_strategy_selection_exactly_as_it_was(+ monkeypatch: pytest.MonkeyPatch,+ _captured_system: list[str],+) -> None:+ """A tenant with skills must not have every alert steered by one.++ The regression this guards is a resolver that returns "the only skill" for+ an alert nothing matched, which would silently replace the whole strategy+ library for that tenant.+ """+ _no_mcp(monkeypatch)++ async def _unrelated(tenant_id: str) -> list[dict[str, Any]]:+ return [_row("phishing-only", techniques=["T1566"])]++ monkeypatch.setattr(skills_module, "fetch_skills", _unrelated)+ result = await deep_module.run_deep_investigation(_state(), llm=_ScriptedModel())++ assert result.strategy_id == "endpoint-suspicious-process"+ assert result.tenant_skill is None+++async def test_an_unreachable_skill_store_falls_back_to_the_built_in_library(+ monkeypatch: pytest.MonkeyPatch,+ _captured_system: list[str],+) -> None:+ """Guidance is advisory; the investigation is not.++ Asserted rather than assumed because the obvious implementation lets the+ exception escape, and the symptom would be every investigation failing on+ a store that is merely slow.+ """+ _no_mcp(monkeypatch)++ async def _boom(tenant_id: str) -> list[dict[str, Any]]:+ raise RuntimeError("the API is down")++ monkeypatch.setattr(skills_module, "fetch_skills", _boom)+ result = await deep_module.run_deep_investigation(_state(), llm=_ScriptedModel())++ assert result.error is None+ assert result.strategy_id == "endpoint-suspicious-process"+ assert result.tenant_skill is None+++async def test_the_investigation_pins_the_version_triage_already_used(+ monkeypatch: pytest.MonkeyPatch,+ _captured_system: list[str],+) -> None:+ """One alert must not be triaged under v3 and investigated under v4.++ The fetch is cached, so a cache expiry between the two reads is exactly+ the window in which an activation splits them, and the verdict would then+ be explained by text that did not produce it.+ """+ _no_mcp(monkeypatch)++ async def _both_versions(tenant_id: str) -> list[dict[str, Any]]:+ return [_row(version=3), _row(version=4)]++ monkeypatch.setattr(skills_module, "fetch_skills", _both_versions)++ state = _state()+ state.tenant_skill = {"skill_id": "finance-batch-powershell", "version": 3, "ref": "finance-batch-powershell@v3"}+ result = await deep_module.run_deep_investigation(state, llm=_ScriptedModel())++ assert result.tenant_skill is not None+ assert result.tenant_skill["version"] == 3+++def test_the_resolved_payload_reader_tolerates_a_bad_shape() -> None:+ """A malformed registry answer must not take an investigation down."""+ assert skills_module.skills_from_payload(None) == []+ assert skills_module.skills_from_payload({"skills": "not a list"}) == []+ assert skills_module.skills_from_payload({"skills": [_row(), "junk"]}) == [_row()]+++def test_a_resolved_skill_renders_nothing_when_it_says_nothing_a_verdict_uses() -> None:+ """An empty block, not a heading saying the tenant has no conventions.++ Same reasoning as ``organisation_memory.render_for_prompt``: a heading+ reading "organisation skill: none" is a claim, and an absence of one is+ not.+ """+ bare = ResolvedSkill(+ skill_id="bare",+ version=1,+ name="Bare",+ owner="[email protected]",+ plan=("Look at the host.",),+ expected_pivots=("process_activity",),+ )+ assert bare.triage_guidance() == ""+ # The plan still reaches the investigation: a skill with no prose is a+ # plan, which is the minimum a skill can be.+ assert "Look at the host." in bare.system_guidance()diff --git a/services/api/app/api/v1/endpoints/tenant_skills.py b/services/api/app/api/v1/endpoints/tenant_skills.pynew file mode 100644index 000000000..0429ba069--- /dev/null+++ b/services/api/app/api/v1/endpoints/tenant_skills.py@@ -0,0 +1,606 @@+"""Author, backtest and activate a tenant's own investigation skills.++Gap-closure Phase 6.1 and 6.2.++Seven routes. Six are the console's: list, read, validate, save, backtest,+activate, retire and delete. The seventh is internal and is how the agents+service reads the active set on the path of an investigation.++The tenant never appears in a request+--------------------------------------+Every console route takes ``user.tenant_id`` from the authenticated+principal. The skill id is the author's own slug and is scoped to that tenant+by the query, so naming another tenant's skill is a 404 rather than a read.+The internal route names a tenant explicitly for the same reason+``/mcp-servers/resolved`` does: a service token carries no tenant of its own,+so there is nothing to intersect it with.++Why the internal route accepts a service token and not a session+-----------------------------------------------------------------+Unlike ``/mcp-servers/resolved`` this one returns no credential, so the+narrow reason that route gives for refusing a session does not apply. It is+still service-token only, on a simpler ground: it exists for one caller, and a+route with one caller should accept one kind of credential. The console reads+the same rows through ``GET /tenant-skills``, which returns more, not less.++What the backtest route does, and does not, build+--------------------------------------------------+It starts **two Phase 1 replay evaluations** and records their ids against+the skill version. It contains no replay, no scoring and no report rendering:+all three are ``services/api/app/services/replay_evaluation`` and+``packages/aisoc-benchmark``, unchanged. The baseline run carries the tenant's+currently active skills; the candidate run carries those plus this one. Same+connector, same window, same seed, same resample count, so the only difference+between the two reports is the skill.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta+from typing import Annotated, Any++import structlog+from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, status+from pydantic import BaseModel, Field+from sqlalchemy import select++from app.api.v1.deps import AuthUser, DBSession+from app.api.v1.endpoints.alert_writeback import service_token_valid+from app.db.database import AsyncSessionLocal+from app.db.rls import TenantDBSession, set_rls_context+from app.models.connector import Connector+from app.models.tenant_skill import TenantSkill as TenantSkillRow+from app.models.tenant_skill import TenantSkillVersion+from app.services.replay_evaluation import store as replay_store+from app.services.replay_evaluation.job import (+ BOOTSTRAP_RESAMPLES,+ BOOTSTRAP_SEED,+ ReplayRequest,+ run_evaluation,+)+from app.services.replay_evaluation.vendors import UnsupportedConnector, vendor_for+from app.services.tenant_skills import store+from app.services.tenant_skills.models import SkillParseError+from app.services.tenant_skills.tools import tool_inventory_for_tenant++logger = structlog.get_logger(__name__)++router = APIRouter(prefix="/tenant-skills", tags=["tenant-skills"])++#: Same default window as an ordinary replay evaluation, and for the same+#: reason: long enough for most queues to hold enough labelled malicious cases+#: for a headline, short enough that the estate resembles today's.+DEFAULT_WINDOW_DAYS = 90++#: A skill document is guidance, not a corpus. The parser caps every field;+#: this is the transport-level bound so an oversized body is refused before it+#: is parsed rather than after.+MAX_YAML_BYTES = 32_768+++# ---------------------------------------------------------------------------+# Wire models+# ---------------------------------------------------------------------------+++class SkillModel(BaseModel):+ """One skill as the console sees it."""++ skill_id: str+ version: int+ status: str+ name: str+ owner: str+ expires_at: datetime+ expired: bool+ body: dict[str, Any]+ source_yaml: str+ backtest_evaluation_id: str | None = None+ backtest_baseline_id: str | None = None+ backtest_version: int | None = None+ activated_at: datetime | None = None+ created_at: datetime | None = None+ updated_at: datetime | None = None+++class AvailableTools(BaseModel):+ """What an author may name in ``expected_pivots`` on this tenant today.++ Returned with the list so the editor can offer the vocabulary rather than+ making the author discover it by being refused. ``customer_unknown`` is+ part of the contract: an editor that read an unreachable action registry+ as "this tenant has no products" would grey out tools the tenant has.+ """++ builtin: list[str] = Field(default_factory=list)+ customer: list[str] = Field(default_factory=list)+ mcp: list[str] = Field(default_factory=list)+ customer_unknown: bool = False+ customer_unknown_reason: str = ""+++class SkillListResponse(BaseModel):+ skills: list[SkillModel]+ available_tools: AvailableTools+++class SkillVersionModel(BaseModel):+ """One immutable version, which is what a recorded ``skill@vN`` resolves to."""++ skill_id: str+ version: int+ name: str+ owner: str+ expires_at: datetime+ body: dict[str, Any]+ source_yaml: str+ backtest_evaluation_id: str | None = None+ backtest_baseline_id: str | None = None+ authored_at: datetime | None = None+ activated_at: datetime | None = None+ retired_at: datetime | None = None+++class SaveSkillRequest(BaseModel):+ source_yaml: str = Field(..., min_length=1, max_length=MAX_YAML_BYTES)+++class ValidateResponse(BaseModel):+ valid: bool+ skill_id: str | None = None+ name: str | None = None+ expected_pivots: list[str] = Field(default_factory=list)+ available_tools: AvailableTools = Field(default_factory=AvailableTools)+ error: str | None = None+++class SkillBacktestRequest(BaseModel):+ """Which connector and window to grade the skill over."""++ connector_id: uuid.UUID+ since: datetime | None = None+ until: datetime | None = None+ train_fraction: float = Field(default=0.7, gt=0.0, lt=1.0)+ limit: int = Field(default=1000, ge=1, le=2000)+ bootstrap_seed: int = BOOTSTRAP_SEED+ bootstrap_resamples: int = BOOTSTRAP_RESAMPLES+++class SkillBacktestResponse(BaseModel):+ """The two runs the console polls, and how to read them together."""++ skill_id: str+ version: int+ baseline_evaluation_id: str+ candidate_evaluation_id: str+ note: str+++class ResolvedSkillModel(BaseModel):+ skill_id: str+ version: int+ activated_at: str | None = None+ expires_at: str | None = None+ body: dict[str, Any]+++class ResolvedSkillsResponse(BaseModel):+ tenant_id: str+ skills: list[ResolvedSkillModel]+++def _to_model(row: TenantSkillRow, *, now: datetime) -> SkillModel:+ expires_at = row.expires_at if row.expires_at.tzinfo else row.expires_at.replace(tzinfo=UTC)+ return SkillModel(+ skill_id=row.skill_id,+ version=int(row.version),+ status=row.status,+ name=row.name,+ owner=row.owner,+ expires_at=expires_at,+ # Computed rather than left to the client. An active-but-expired skill+ # steers nothing, and a console that shows only "active" would report+ # a skill as working while the resolver silently drops it.+ expired=expires_at <= now,+ body=dict(row.body or {}),+ source_yaml=row.source_yaml,+ backtest_evaluation_id=str(row.backtest_evaluation_id) if row.backtest_evaluation_id else None,+ backtest_baseline_id=str(row.backtest_baseline_id) if row.backtest_baseline_id else None,+ backtest_version=row.backtest_version,+ activated_at=row.activated_at,+ created_at=row.created_at,+ updated_at=row.updated_at,+ )+++def _version_model(row: TenantSkillVersion) -> SkillVersionModel:+ return SkillVersionModel(+ skill_id=row.skill_id,+ version=int(row.version),+ name=row.name,+ owner=row.owner,+ expires_at=row.expires_at,+ body=dict(row.body or {}),+ source_yaml=row.source_yaml,+ backtest_evaluation_id=str(row.backtest_evaluation_id) if row.backtest_evaluation_id else None,+ backtest_baseline_id=str(row.backtest_baseline_id) if row.backtest_baseline_id else None,+ authored_at=row.authored_at,+ activated_at=row.activated_at,+ retired_at=row.retired_at,+ )+++def _not_found(skill_id: str) -> HTTPException:+ return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"no skill {skill_id!r} for this tenant")+++# ---------------------------------------------------------------------------+# Console routes+# ---------------------------------------------------------------------------++[email protected]("", response_model=SkillListResponse, summary="Every skill this tenant has authored")+async def list_tenant_skills(user: AuthUser, db: TenantDBSession) -> SkillListResponse:+ await user.require_permission_db("settings:read", db)+ rows = await store.list_skills(db, user.tenant_id)+ inventory = await tool_inventory_for_tenant(db, user.tenant_id)+ now = datetime.now(UTC)+ return SkillListResponse(+ skills=[_to_model(r, now=now) for r in rows],+ available_tools=AvailableTools(**inventory.as_dict()),+ )++[email protected]("/{skill_id}", response_model=SkillModel, summary="One skill")+async def get_tenant_skill(skill_id: str, user: AuthUser, db: TenantDBSession) -> SkillModel:+ await user.require_permission_db("settings:read", db)+ try:+ row = await store.get_skill(db, user.tenant_id, skill_id)+ except store.SkillNotFound as exc:+ raise _not_found(skill_id) from exc+ return _to_model(row, now=datetime.now(UTC))+++ "/{skill_id}/versions",+ response_model=list[SkillVersionModel],+ summary="Every version of one skill, newest first",+)+async def list_skill_versions(skill_id: str, user: AuthUser, db: TenantDBSession) -> list[SkillVersionModel]:+ """Resolve a ``skill@vN`` recorded on an investigation back to its text.++ This is the read that makes the version recorded on a verdict mean+ something. Without it the pair is a number pointing at nothing.+ """+ await user.require_permission_db("settings:read", db)+ rows = await store.list_versions(db, user.tenant_id, skill_id)+ if not rows:+ raise _not_found(skill_id)+ return [_version_model(r) for r in rows]++[email protected]("/validate", response_model=ValidateResponse, summary="Parse and validate without saving")+async def validate_tenant_skill(body: SaveSkillRequest, user: AuthUser, db: TenantDBSession) -> ValidateResponse:+ """Back the editor's validate button with the same call the save makes.++ A 200 carrying ``valid: false`` rather than a 422: the editor asks this on+ every keystroke pause, and an error status on a document the author is+ still typing is a failed request in their network tab every few seconds.+ The save route returns the 422.+ """+ await user.require_permission_db("settings:read", db)+ inventory = await tool_inventory_for_tenant(db, user.tenant_id)+ try:+ skill = await store.validate_yaml(db, user.tenant_id, body.source_yaml)+ except SkillParseError as exc:+ return ValidateResponse(valid=False, error=str(exc), available_tools=inventory.as_dict())+ return ValidateResponse(+ valid=True,+ skill_id=skill.id,+ name=skill.name,+ expected_pivots=list(skill.expected_pivots),+ available_tools=AvailableTools(**inventory.as_dict()),+ )++[email protected]("", response_model=SkillModel, summary="Create or update a skill from its YAML")+async def save_tenant_skill(+ body: SaveSkillRequest,+ user: AuthUser,+ db: TenantDBSession,+) -> SkillModel:+ """Save the document. A content change bumps the version and drops to draft.++ ``PUT`` with no id in the path because the id is inside the document: a+ skill's identity is the author's slug, and taking it from a path as well+ would create two authorities that can disagree.+ """+ await user.require_permission_db("settings:write", db)+ try:+ row, created = await store.save_skill(+ db,+ tenant_id=user.tenant_id,+ author_id=user.user_id,+ source_yaml=body.source_yaml,+ )+ except SkillParseError as exc:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc+ await db.commit()+ await db.refresh(row)+ logger.info(+ "tenant_skill.saved",+ tenant_id=str(user.tenant_id),+ skill_id=row.skill_id,+ version=int(row.version),+ created=created,+ )+ return _to_model(row, now=datetime.now(UTC))+++ "/{skill_id}/backtest",+ response_model=SkillBacktestResponse,+ status_code=status.HTTP_202_ACCEPTED,+ summary="Grade this skill against the tenant's own closed findings, with and without it",+)+async def backtest_tenant_skill(+ skill_id: str,+ body: SkillBacktestRequest,+ background: BackgroundTasks,+ user: AuthUser,+ db: TenantDBSession,+) -> SkillBacktestResponse:+ """Start the two Phase 1 replay runs that grade this version.++ 202 for the same reason ``POST /evaluations/replay`` is: replaying a few+ hundred findings through a model twice is not a request-response+ operation. The ids come back immediately and the console polls both.++ ``connectors:write`` rather than ``settings:write``, because what this+ actually does is reach a customer's own SIEM with stored credentials,+ which is the bar every other route that does that clears.+ """+ await user.require_permission_db("connectors:write", db)++ try:+ row = await store.get_skill(db, user.tenant_id, skill_id)+ except store.SkillNotFound as exc:+ raise _not_found(skill_id) from exc++ until = body.until or datetime.now(UTC)+ since = body.since or (until - timedelta(days=DEFAULT_WINDOW_DAYS))+ if until <= since:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"until ({until.isoformat()}) must be after since ({since.isoformat()})",+ )++ connector = (+ await db.execute(+ select(Connector).where(+ Connector.id == body.connector_id,+ Connector.tenant_id == user.tenant_id,+ )+ )+ ).scalar_one_or_none()+ if connector is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such connector for this tenant")+ try:+ vendor = vendor_for(connector.connector_type)+ except UnsupportedConnector as exc:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc++ # The tenant's currently active skills are the baseline's context, so the+ # comparison answers "what does adding this one change" rather than "what+ # do skills do at all". The candidate under test is excluded from that+ # set: a skill already active would otherwise appear on both sides and+ # the delta would be zero by construction.+ active = [s for s in await store.resolve_active_skills(db, user.tenant_id) if s["skill_id"] != skill_id]+ candidate = {+ "skill_id": row.skill_id,+ "version": int(row.version),+ "activated_at": row.activated_at.isoformat() if row.activated_at else None,+ "expires_at": row.expires_at.isoformat(),+ "body": dict(row.body or {}),+ }++ common = {+ "tenant_id": user.tenant_id,+ "connector_row_id": body.connector_id,+ "connector_type": connector.connector_type,+ "vendor": vendor,+ "window_start": since,+ "window_end": until,+ "train_fraction": body.train_fraction,+ "limit": body.limit,+ "bootstrap_seed": body.bootstrap_seed,+ "bootstrap_resamples": body.bootstrap_resamples,+ }++ baseline_id = await _queue_run(+ db,+ background,+ user=user,+ common=common,+ skills=tuple(active),+ skill_under_test=None,+ )+ candidate_id = await _queue_run(+ db,+ background,+ user=user,+ common=common,+ skills=tuple(active),+ skill_under_test=candidate,+ )++ await store.attach_backtest(+ db,+ tenant_id=user.tenant_id,+ skill_id=skill_id,+ baseline_evaluation_id=baseline_id,+ candidate_evaluation_id=candidate_id,+ )+ await db.commit()++ logger.info(+ "tenant_skill.backtest_queued",+ tenant_id=str(user.tenant_id),+ skill_id=skill_id,+ version=int(row.version),+ baseline=str(baseline_id),+ candidate=str(candidate_id),+ )+ return SkillBacktestResponse(+ skill_id=skill_id,+ version=int(row.version),+ baseline_evaluation_id=str(baseline_id),+ candidate_evaluation_id=str(candidate_id),+ note=(+ "Two runs over the same window, seed and resample count. The baseline carries this "+ "tenant's other active skills; the candidate carries those plus this one. Read them "+ "side by side at GET /evaluations/replay/{id}. This skill was authored after the window "+ "closed and is applied to it on purpose, so the result measures the skill against this "+ "window and is not a forecast of its accuracy on new alerts."+ ),+ )+++async def _queue_run(+ db: TenantDBSession,+ background: BackgroundTasks,+ *,+ user: AuthUser,+ common: dict[str, Any],+ skills: tuple[dict[str, Any], ...],+ skill_under_test: dict[str, Any] | None,+) -> uuid.UUID:+ evaluation_id = await replay_store.create_evaluation(+ db,+ tenant_id=common["tenant_id"],+ connector_id=str(common["connector_row_id"]),+ vendor=common["vendor"],+ window_start=common["window_start"],+ window_end=common["window_end"],+ train_fraction=common["train_fraction"],+ bootstrap_seed=common["bootstrap_seed"],+ bootstrap_resamples=common["bootstrap_resamples"],+ requested_by=user.user_id,+ )+ background.add_task(+ _run_detached,+ ReplayRequest(+ evaluation_id=evaluation_id,+ skills=skills,+ skill_under_test=skill_under_test,+ **common,+ ),+ )+ return evaluation_id+++async def _run_detached(request: ReplayRequest) -> None:+ """Run one evaluation on its own session.++ The request's session closes when the response returns, so the background+ task opens its own. ``run_evaluation`` never raises: every failure lands+ on the row as a reason.+ """+ async with AsyncSessionLocal() as session:+ await run_evaluation(session, request)++[email protected]("/{skill_id}/activate", response_model=SkillModel, summary="Put a backtested skill into service")+async def activate_tenant_skill(skill_id: str, user: AuthUser, db: TenantDBSession) -> SkillModel:+ """Activate, refusing anything that would put untested guidance in front of alerts.++ The refusals live in the store and are restated by the database+ constraint, so neither this route nor a future caller can be the only+ place the rule holds.+ """+ await user.require_permission_db("settings:write", db)+ try:+ row = await store.activate_skill(+ db,+ tenant_id=user.tenant_id,+ skill_id=skill_id,+ actor_id=user.user_id,+ )+ except store.SkillNotFound as exc:+ raise _not_found(skill_id) from exc+ except store.SkillLifecycleError as exc:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc+ await db.commit()+ await db.refresh(row)+ return _to_model(row, now=datetime.now(UTC))++[email protected]("/{skill_id}/retire", response_model=SkillModel, summary="Take a skill out of service, keeping its history")+async def retire_tenant_skill(skill_id: str, user: AuthUser, db: TenantDBSession) -> SkillModel:+ await user.require_permission_db("settings:write", db)+ try:+ row = await store.retire_skill(db, tenant_id=user.tenant_id, skill_id=skill_id)+ except store.SkillNotFound as exc:+ raise _not_found(skill_id) from exc+ await db.commit()+ await db.refresh(row)+ return _to_model(row, now=datetime.now(UTC))++[email protected]("/{skill_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None, summary="Delete a skill and its history")+async def delete_tenant_skill(skill_id: str, user: AuthUser, db: TenantDBSession) -> None:+ """For a skill created by mistake. To stop using a working one, retire it.++ Deleting removes the version history, which is what explains verdicts the+ skill already steered. The docs say so beside this route.+ """+ await user.require_permission_db("settings:write", db)+ removed = await store.delete_skill(db, tenant_id=user.tenant_id, skill_id=skill_id)+ if not removed:+ raise _not_found(skill_id)+ await db.commit()+++# ---------------------------------------------------------------------------+# Internal route: the agents service, and nothing else+# ---------------------------------------------------------------------------++[email protected]("/resolved/active", response_model=ResolvedSkillsResponse, include_in_schema=False)+async def resolve_tenant_skills(+ db: DBSession,+ tenant_id: uuid.UUID,+ x_aisoc_service_token: Annotated[str | None, Header()] = None,+) -> ResolvedSkillsResponse:+ """Active, unexpired skills for the agents service.++ The token is checked in band rather than through a bearer dependency, the+ same shape ``/mcp-servers/resolved`` and ``/feedback/context-statements``+ use, because the caller is a service with no session.+ ``service_token_valid`` compares in constant time and fails closed when the+ shared secret is unset, so an unconfigured deployment has this route shut.++ ``tenant_id`` is required and is the scope rather than a narrowing of one:+ a service token carries no tenant, so there is nothing to intersect it+ with, and defaulting an omitted parameter to "every tenant" would serve+ one customer's guidance into another's investigation.++ ``TenantDBSession`` cannot be used here because it resolves the tenant+ from a session this caller does not have, so the RLS context is set from+ the named tenant explicitly. The query layer filters on the same value, so+ the two agree by construction rather than by convention.+ """+ if not service_token_valid(x_aisoc_service_token):+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="this route is reachable only by an AiSOC service holding the shared service token",+ )++ await set_rls_context(db, tenant_id)+ skills = await store.resolve_active_skills(db, tenant_id)+ logger.info("tenant_skill.resolved_for_agent", tenant_id=str(tenant_id), skills=len(skills))+ return ResolvedSkillsResponse(+ tenant_id=str(tenant_id),+ skills=[ResolvedSkillModel(**s) for s in skills],+ )diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex 8ec0328fc..a781666f7 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -80,6 +80,7 @@ from app.api.v1.endpoints import (sla,stix_taxii,tenant_provision,+ tenant_skills,tenants,threat_intel,translation,@@ -139,6 +140,12 @@ api_router.include_router(plugins.router)api_router.include_router(community.router)api_router.include_router(marketplace.router)api_router.include_router(mcp_servers.router)+# Gap-closure Phase 6.1 and 6.2: tenant-authored investigation skills:+# authored in YAML, validated against the tools this tenant's agent can+# actually call, backtested through the Phase 1 replay with and without the+# skill, and only then activated. The agents service resolves the active set+# on the path of an investigation.+api_router.include_router(tenant_skills.router)api_router.include_router(rbac.router)api_router.include_router(audit.router)api_router.include_router(compliance.router)diff --git a/services/api/app/models/tenant_skill.py b/services/api/app/models/tenant_skill.pynew file mode 100644index 000000000..2b1939f1e--- /dev/null+++ b/services/api/app/models/tenant_skill.py@@ -0,0 +1,138 @@+"""Tenant-skill ORM models.++Gap-closure Phase 6.1 and 6.2. Backs ``/api/v1/tenant-skills`` and migration+``070_tenant_skills.sql``; the migration header carries the reasoning for each+column and constraint.++The short version: a skill steers an agent's verdict, so it is versioned like+a detection rule rather than stored like a preference. :class:`TenantSkill` is+the current state of one skill and :class:`TenantSkillVersion` is the+append-only history that makes the ``(skill_id, version)`` pair an+investigation records resolvable back to the text that was in force.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import DateTime, ForeignKey, Integer, Text+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base++#: The lifecycle the plan specifies, plus ``retired`` for a skill taken out of+#: service without deleting its history. Mirrored by a CHECK on the column so+#: a row cannot reach a state the application does not know about.+SKILL_STATUSES: tuple[str, ...] = ("draft", "backtested", "active", "retired")++DRAFT = "draft"+BACKTESTED = "backtested"+ACTIVE = "active"+RETIRED = "retired"+++class TenantSkill(Base):+ """One tenant-authored investigation skill, current state."""++ __tablename__ = "aisoc_tenant_skills"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("tenants.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )++ skill_id: Mapped[str] = mapped_column(Text, nullable=False)+ version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)+ status: Mapped[str] = mapped_column(Text, nullable=False, default=DRAFT)++ name: Mapped[str] = mapped_column(Text, nullable=False)+ owner: Mapped[str] = mapped_column(Text, nullable=False)+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)++ body: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)+ source_yaml: Mapped[str] = mapped_column(Text, nullable=False, default="")++ # The "after" run and the "before" run. Both, because a figure with no+ # baseline beside it is not a comparison.+ #+ # No ``ForeignKey`` here, and the migration does declare one. The+ # difference is not drift: ``aisoc_replay_evaluations`` is written and read+ # entirely through raw SQL in ``app.services.replay_evaluation.store`` and+ # has no mapped class, so a ForeignKey naming it cannot resolve against+ # ``Base.metadata`` at all. Declaring one here fails table creation rather+ # than enforcing anything. The constraint is real in Postgres, where it is+ # enforced, and the migration is its authority.+ backtest_evaluation_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)+ backtest_baseline_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)+ backtest_version: Mapped[int | None] = mapped_column(Integer, nullable=True)++ activated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ activated_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)++ created_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False)+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ nullable=False,+ )+++class TenantSkillVersion(Base):+ """One immutable version of a skill.++ Written on every content change and stamped on activation and retirement.+ Nothing here is edited: an activation stamp is a fact about the version+ rather than a change to it.+ """++ __tablename__ = "aisoc_tenant_skill_versions"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("tenants.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )+ skill_row_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("aisoc_tenant_skills.id", ondelete="CASCADE"),+ nullable=False,+ )++ skill_id: Mapped[str] = mapped_column(Text, nullable=False)+ version: Mapped[int] = mapped_column(Integer, nullable=False)++ name: Mapped[str] = mapped_column(Text, nullable=False)+ owner: Mapped[str] = mapped_column(Text, nullable=False)+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)+ body: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)+ source_yaml: Mapped[str] = mapped_column(Text, nullable=False, default="")++ # Unmapped target, same as on the live row above.+ backtest_evaluation_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)+ backtest_baseline_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)++ authored_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)+ authored_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False)+ activated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ activated_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)+ retired_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+++__all__ = [+ "ACTIVE",+ "BACKTESTED",+ "DRAFT",+ "RETIRED",+ "SKILL_STATUSES",+ "TenantSkill",+ "TenantSkillVersion",+]diff --git a/services/api/app/services/replay_evaluation/job.py b/services/api/app/services/replay_evaluation/job.pyindex 72451856d..96b3b6e0c 100644--- a/services/api/app/services/replay_evaluation/job.py+++ b/services/api/app/services/replay_evaluation/job.py@@ -113,6 +113,20 @@ class ReplayRequest:bootstrap_seed: intbootstrap_resamples: int+ #: Gap-closure Phase 6.2. Tenant skills to hand the replay as frozen+ #: context, carrying their ``activated_at`` so the agents side can drop+ #: any activated after the split. ``None`` means "send no context block",+ #: which is what an ordinary replay does and is byte-identical to the+ #: behaviour before this field existed.+ skills: tuple[dict[str, Any], ...] | None = None++ #: The one skill a backtest is measuring, applied to the whole test window+ #: even though it was authored after it. Travels separately from+ #: ``skills`` all the way to the report's method note, where it is named+ #: and caveated, because an accuracy figure produced by guidance written+ #: after the window is a statement about that window and not a forecast.+ skill_under_test: dict[str, Any] | None = None+def _agents_base_url() -> str:"""Where the agents service lives.@@ -206,11 +220,20 @@ async def _read_history(request: ReplayRequest, credentials: dict[str, Any]) ->async def _run_replay(request: ReplayRequest, connector_type: str, findings: list[dict[str, Any]]) -> dict[str, Any]:url = f"{_agents_base_url()}/api/v1/replay/run"- payload = {+ payload: dict[str, Any] = {"connector_id": connector_type,"findings": findings,"train_fraction": request.train_fraction,}+ if request.skills is not None or request.skill_under_test is not None:+ # Sent only when a caller asked for it. An ordinary replay still sends+ # no context block at all, so its snapshot is the empty one documented+ # on `FrozenContext` rather than an empty-but-present one that would+ # read differently in the method note.+ payload["context"] = {+ "skills": list(request.skills or ()),+ "skills_under_test": [request.skill_under_test] if request.skill_under_test else [],+ }try:async with httpx.AsyncClient(timeout=_REPLAY_TIMEOUT_S) as client:response = await client.post(url, headers=_agents_headers(request.tenant_id), json=payload)diff --git a/services/api/app/services/tenant_skills/__init__.py b/services/api/app/services/tenant_skills/__init__.pynew file mode 100644index 000000000..e2c363d1a--- /dev/null+++ b/services/api/app/services/tenant_skills/__init__.py@@ -0,0 +1,59 @@+"""Tenant-authored investigation skills: parsing, tool validation, lifecycle.++Gap-closure Phase 6.1 and 6.2. Read ``models.py`` for the document shape,+``tools.py`` for what "a tool the tenant does not have" means, and+``store.py`` for the draft to backtested to active ladder and the refusals+that make it worth having.+"""++from app.services.tenant_skills.models import (+ SkillMatch,+ SkillParseError,+ TenantSkill,+ parse_skill_yaml,+ skill_from_body,+)+from app.services.tenant_skills.store import (+ SkillLifecycleError,+ SkillNotFound,+ activate_skill,+ attach_backtest,+ delete_skill,+ get_skill,+ list_skills,+ list_versions,+ resolve_active_skills,+ retire_skill,+ save_skill,+ validate_yaml,+)+from app.services.tenant_skills.tools import (+ BUILTIN_PIVOTS,+ ToolInventory,+ tool_inventory_for_tenant,+ validate_expected_pivots,+)++__all__ = [+ "BUILTIN_PIVOTS",+ "SkillLifecycleError",+ "SkillMatch",+ "SkillNotFound",+ "SkillParseError",+ "TenantSkill",+ "ToolInventory",+ "activate_skill",+ "attach_backtest",+ "delete_skill",+ "get_skill",+ "list_skills",+ "list_versions",+ "parse_skill_yaml",+ "resolve_active_skills",+ "retire_skill",+ "save_skill",+ "skill_from_body",+ "tool_inventory_for_tenant",+ "validate_expected_pivots",+ "validate_yaml",+]diff --git a/services/api/app/services/tenant_skills/models.py b/services/api/app/services/tenant_skills/models.pynew file mode 100644index 000000000..bd4d154ea--- /dev/null+++ b/services/api/app/services/tenant_skills/models.py@@ -0,0 +1,433 @@+"""Tenant-authored investigation skills: the YAML the console edits, parsed.++Gap-closure Phase 6.1.++A skill is a customer's own investigation approach, written down. It carries+the same shape as a built-in ``Strategy`` in ``services/agents`` (a plan, the+pivots it expects, a rationale) plus the four things a built-in cannot have,+because they are statements about one organisation rather than about attacker+behaviour: what is normal here, what verdict that normality implies, what+evidence has to be in hand before the verdict is allowed, and what pulls the+alert back to a human anyway.++Why this is shaped like a detection rule and not like a settings page+---------------------------------------------------------------------+A skill steers an agent's verdict. Six months after a disputed auto-close,+"why did it decide that" has to be answerable, and the answer is partly this+text. So a skill has an **owner** (who to ask), a **version** (which text was+in force), and an **expiry** (organisational facts rot, and a skill nobody+renews should stop steering rather than steer forever on last year's estate).+The version is assigned here and never by the author: ``version:`` is refused+as a top-level key precisely so there is one authority for what version 3 is.++Why YAML, and why the parse is strict+-------------------------------------+Same reasoning as ``app.services.business_context.models``: the console+exposes an editor and analysts author rules in YAML. Strictness is the part+that differs. Unknown top-level keys are **refused** rather than ignored,+because a skill whose ``verdict_guidance`` was typed as ``verdict_guidence``+is a skill that silently does half of what its author believes it does, and+the author has no way to find out short of reading a prompt.++Every free-text field is capped. The text reaches a prompt, and the prompt+has a budget shared with the evidence the verdict is supposed to rest on.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from datetime import UTC, date, datetime+from typing import Any++import yaml++__all__ = [+ "MAX_ESCALATIONS",+ "MAX_EVIDENCE_ITEMS",+ "MAX_KEYWORDS",+ "MAX_PIVOTS",+ "MAX_PLAN_STEPS",+ "SkillMatch",+ "SkillParseError",+ "TenantSkill",+ "parse_skill_yaml",+]+++class SkillParseError(ValueError):+ """A skill failed structural validation.++ ``ValueError`` for the same reason ``RuleParseError`` is one: the API layer+ catches this single class and returns the message verbatim in a 422, so+ every message here is written for the analyst who typed the YAML rather+ than for a log.+ """+++# --------------------------------------------------------------------------+# Bounds+#+# Each cap is the point past which the field stops being guidance and starts+# being a document. They are module constants so the console can show them and+# the gate can assert the docs quote the same numbers.+# --------------------------------------------------------------------------++MAX_PLAN_STEPS = 12+MAX_PIVOTS = 12+MAX_EVIDENCE_ITEMS = 10+MAX_ESCALATIONS = 10+MAX_KEYWORDS = 24+MAX_TECHNIQUES = 24+MAX_RULE_IDS = 32+MAX_SOURCES = 16++#: Per-item and per-block character caps. ``guidance`` and ``verdict_guidance``+#: are prose blocks and get more room than a plan step, which is one sentence.+MAX_ITEM_CHARS = 400+MAX_BLOCK_CHARS = 1200+MAX_NAME_CHARS = 120+MAX_OWNER_CHARS = 200++#: Kebab-case slug, 3 to 63 characters. Same shape as a business-context rule+#: id and a playbook id, so an analyst who knows one knows this one.+_SKILL_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$")++#: ATT&CK technique or sub-technique. Parent matching is done at selection+#: time, so ``T1078`` here matches an alert mapped to ``T1078.004``.+_TECHNIQUE_RE = re.compile(r"^T\d{4}(?:\.\d{3})?$", re.IGNORECASE)++_ALLOWED_TOP_LEVEL = frozenset(+ {+ "id",+ "name",+ "owner",+ "expires_at",+ "applies_when",+ "match",+ "guidance",+ "verdict_guidance",+ "required_evidence",+ "escalate_when",+ "plan",+ "expected_pivots",+ "min_pivots",+ }+)++_ALLOWED_MATCH_KEYS = frozenset({"techniques", "rule_ids", "sources", "keywords"})++#: Keys an author might reasonably type that the server owns instead. Named+#: individually so the refusal explains rather than just rejects.+_SERVER_OWNED = {+ "version": "version is assigned by the server on every content change, so it cannot be set in YAML",+ "status": "status moves through draft, backtested and active via the lifecycle routes, not the document",+ "enabled": "a skill is active or it is not; use the activate and retire routes",+ "tenant_id": "the tenant comes from your credential, never from the document",+}+++@dataclass(frozen=True)+class SkillMatch:+ """When a skill applies.++ At least one condition must be present. A skill with an empty match block+ would apply to every alert in the tenant, which is a way to replace the+ whole strategy library by accident.+ """++ techniques: tuple[str, ...] = ()+ rule_ids: tuple[str, ...] = ()+ sources: tuple[str, ...] = ()+ keywords: tuple[str, ...] = ()++ def is_empty(self) -> bool:+ return not (self.techniques or self.rule_ids or self.sources or self.keywords)++ def as_dict(self) -> dict[str, Any]:+ return {+ "techniques": list(self.techniques),+ "rule_ids": list(self.rule_ids),+ "sources": list(self.sources),+ "keywords": list(self.keywords),+ }+++@dataclass(frozen=True)+class TenantSkill:+ """A parsed skill, before it is given a version or a status.++ Frozen, because the store hands the same object to the validator, the+ serialiser and the backtest, and a mutable one would let any of them edit+ what the others are about to read.+ """++ id: str+ name: str+ owner: str+ expires_at: datetime+ match: SkillMatch+ plan: tuple[str, ...]+ expected_pivots: tuple[str, ...]+ applies_when: str = ""+ guidance: str = ""+ verdict_guidance: str = ""+ required_evidence: tuple[str, ...] = ()+ escalate_when: tuple[str, ...] = ()+ min_pivots: int = 2+ raw_yaml: str = ""++ def as_dict(self) -> dict[str, Any]:+ """The JSONB body. Field names match the YAML so a round trip is obvious."""+ return {+ "id": self.id,+ "name": self.name,+ "owner": self.owner,+ "expires_at": self.expires_at.isoformat(),+ "applies_when": self.applies_when,+ "match": self.match.as_dict(),+ "guidance": self.guidance,+ "verdict_guidance": self.verdict_guidance,+ "required_evidence": list(self.required_evidence),+ "escalate_when": list(self.escalate_when),+ "plan": list(self.plan),+ "expected_pivots": list(self.expected_pivots),+ "min_pivots": self.min_pivots,+ }++ def is_expired(self, *, now: datetime | None = None) -> bool:+ return self.expires_at <= (now or datetime.now(UTC))+++# --------------------------------------------------------------------------+# Parsing+# --------------------------------------------------------------------------+++def _string_list(+ raw: Any,+ *,+ field_name: str,+ limit: int,+ lower: bool = False,+) -> tuple[str, ...]:+ """Read a list of non-empty strings, or a bare string as a one-item list."""+ if raw is None:+ return ()+ if isinstance(raw, str):+ raw = [raw]+ if not isinstance(raw, list):+ raise SkillParseError(f"{field_name!r}: expected a list of strings, got {type(raw).__name__}")+ if len(raw) > limit:+ raise SkillParseError(f"{field_name!r}: at most {limit} entries, got {len(raw)}")++ out: list[str] = []+ seen: set[str] = set()+ for index, item in enumerate(raw):+ if not isinstance(item, str) or not item.strip():+ raise SkillParseError(f"{field_name}[{index}]: must be a non-empty string")+ text = item.strip()+ if len(text) > MAX_ITEM_CHARS:+ raise SkillParseError(f"{field_name}[{index}]: at most {MAX_ITEM_CHARS} characters, got {len(text)}")+ if lower:+ text = text.lower()+ if text in seen:+ raise SkillParseError(f"{field_name}[{index}]: duplicate entry {text!r}")+ seen.add(text)+ out.append(text)+ return tuple(out)+++def _block(raw: Any, *, field_name: str) -> str:+ if raw is None:+ return ""+ if not isinstance(raw, str):+ raise SkillParseError(f"{field_name!r}: must be a string")+ text = raw.strip()+ if len(text) > MAX_BLOCK_CHARS:+ raise SkillParseError(f"{field_name!r}: at most {MAX_BLOCK_CHARS} characters, got {len(text)}")+ return text+++def _expiry(raw: Any) -> datetime:+ """Read the expiry, which is required and has no default.++ No default on purpose. Every plausible default is a policy decision+ disguised as a convenience: a year silently renews a fact about an estate+ that may have been rebuilt, and no expiry at all is what the field exists+ to prevent. The author states when this stops being true about their+ organisation, or the skill does not parse.++ A bare date means end of that day in UTC. ``expires_at: 2027-01-31``+ reading as midnight would expire the skill the evening before the day its+ author wrote down.+ """+ if raw is None:+ raise SkillParseError(+ "'expires_at' is required: a skill states what is normal in one organisation, and an "+ "organisational fact with no review date goes on steering verdicts after it stops being true"+ )+ if isinstance(raw, datetime):+ return raw if raw.tzinfo else raw.replace(tzinfo=UTC)+ if isinstance(raw, date):+ return datetime(raw.year, raw.month, raw.day, 23, 59, 59, tzinfo=UTC)+ if isinstance(raw, str) and raw.strip():+ text = raw.strip().replace("Z", "+00:00")+ try:+ parsed = datetime.fromisoformat(text)+ except ValueError as exc:+ raise SkillParseError(f"'expires_at': {raw!r} is not an ISO-8601 date or timestamp") from exc+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)+ raise SkillParseError(f"'expires_at': expected an ISO-8601 date or timestamp, got {type(raw).__name__}")+++def _match(raw: Any) -> SkillMatch:+ if raw is None:+ raise SkillParseError(+ "'match' is required: a skill with no match conditions applies to every alert in the "+ "tenant, which replaces the whole strategy library rather than adding to it"+ )+ if not isinstance(raw, dict):+ raise SkillParseError(f"'match': expected a mapping, got {type(raw).__name__}")++ unknown = sorted(set(raw) - _ALLOWED_MATCH_KEYS)+ if unknown:+ raise SkillParseError(f"'match': unknown key(s) {unknown}; allowed keys are {sorted(_ALLOWED_MATCH_KEYS)}")++ techniques = _string_list(raw.get("techniques"), field_name="match.techniques", limit=MAX_TECHNIQUES)+ for index, technique in enumerate(techniques):+ if not _TECHNIQUE_RE.match(technique):+ raise SkillParseError(f"match.techniques[{index}]: {technique!r} is not an ATT&CK technique id (e.g. T1059 or T1059.001)")++ match = SkillMatch(+ techniques=tuple(t.upper() for t in techniques),+ rule_ids=_string_list(raw.get("rule_ids"), field_name="match.rule_ids", limit=MAX_RULE_IDS),+ sources=_string_list(raw.get("sources"), field_name="match.sources", limit=MAX_SOURCES, lower=True),+ keywords=_string_list(raw.get("keywords"), field_name="match.keywords", limit=MAX_KEYWORDS, lower=True),+ )+ if match.is_empty():+ raise SkillParseError(+ "'match': at least one of techniques, rule_ids, sources or keywords must be present, or the "+ "skill applies to every alert in the tenant"+ )+ return match+++def parse_skill_yaml(source: str) -> TenantSkill:+ """Parse one skill document.++ One skill per document, unlike business-context rules. A skill is a named,+ owned, separately versioned and separately backtested artefact, and a file+ holding four of them would have one version number across four independent+ decisions.+ """+ if not isinstance(source, str):+ raise SkillParseError("YAML source must be a string")+ text = source.strip()+ if not text:+ raise SkillParseError("the skill document is empty")++ try:+ data = yaml.safe_load(text)+ except yaml.YAMLError as exc:+ raise SkillParseError(f"YAML parse error: {exc}") from exc++ if not isinstance(data, dict):+ raise SkillParseError(f"a skill document must be a single mapping, got {type(data).__name__}")++ for key, reason in _SERVER_OWNED.items():+ if key in data:+ raise SkillParseError(f"{key!r} cannot be set in the document: {reason}")+ unknown = sorted(set(data) - _ALLOWED_TOP_LEVEL)+ if unknown:+ raise SkillParseError(f"unknown key(s) {unknown}; allowed keys are {sorted(_ALLOWED_TOP_LEVEL)}")++ skill_id = data.get("id")+ if not isinstance(skill_id, str) or not _SKILL_ID_RE.match(skill_id):+ raise SkillParseError("'id' must be a kebab-case slug of 3 to 63 characters, for example 'finance-batch-powershell'")++ name = data.get("name")+ if not isinstance(name, str) or not name.strip():+ raise SkillParseError("'name' is required and must be a non-empty string")+ name = name.strip()+ if len(name) > MAX_NAME_CHARS:+ raise SkillParseError(f"'name': at most {MAX_NAME_CHARS} characters, got {len(name)}")++ owner = data.get("owner")+ if not isinstance(owner, str) or not owner.strip():+ raise SkillParseError(+ "'owner' is required: a skill that steers a verdict needs someone to ask when the verdict "+ "is disputed, and an unowned one has nobody to ask six months later"+ )+ owner = owner.strip()+ if len(owner) > MAX_OWNER_CHARS:+ raise SkillParseError(f"'owner': at most {MAX_OWNER_CHARS} characters, got {len(owner)}")++ plan = _string_list(data.get("plan"), field_name="plan", limit=MAX_PLAN_STEPS)+ if not plan:+ raise SkillParseError("'plan' is required and must list at least one step; a skill with no plan cannot steer an investigation")++ expected_pivots = _string_list(data.get("expected_pivots"), field_name="expected_pivots", limit=MAX_PIVOTS)+ if not expected_pivots:+ raise SkillParseError(+ "'expected_pivots' is required and must name at least one tool; without it the skill's depth "+ "cannot be graded and the investigation cannot be told apart from a summary"+ )++ min_pivots = data.get("min_pivots", 2)+ if isinstance(min_pivots, bool) or not isinstance(min_pivots, int):+ raise SkillParseError("'min_pivots' must be an integer")+ if not 1 <= min_pivots <= len(expected_pivots):+ raise SkillParseError(+ f"'min_pivots' must be between 1 and the number of expected_pivots ({len(expected_pivots)}), got {min_pivots}"+ )++ return TenantSkill(+ id=skill_id,+ name=name,+ owner=owner,+ expires_at=_expiry(data.get("expires_at")),+ match=_match(data.get("match")),+ plan=plan,+ expected_pivots=expected_pivots,+ applies_when=_block(data.get("applies_when"), field_name="applies_when"),+ guidance=_block(data.get("guidance"), field_name="guidance"),+ verdict_guidance=_block(data.get("verdict_guidance"), field_name="verdict_guidance"),+ required_evidence=_string_list(data.get("required_evidence"), field_name="required_evidence", limit=MAX_EVIDENCE_ITEMS),+ escalate_when=_string_list(data.get("escalate_when"), field_name="escalate_when", limit=MAX_ESCALATIONS),+ min_pivots=min_pivots,+ raw_yaml=text,+ )+++def skill_from_body(body: dict[str, Any], *, raw_yaml: str = "") -> TenantSkill:+ """Rebuild a skill from the stored JSONB body.++ The agents service is served from this shape rather than from the YAML,+ so a stored skill is never re-parsed on the read path: a parser change+ that tightened a rule would otherwise make an already-active skill+ unreadable at triage time, which is a production outage caused by a+ validation improvement.+ """+ match_raw = body.get("match") or {}+ return TenantSkill(+ id=str(body.get("id") or ""),+ name=str(body.get("name") or ""),+ owner=str(body.get("owner") or ""),+ expires_at=_expiry(body.get("expires_at")),+ match=SkillMatch(+ techniques=tuple(str(t) for t in (match_raw.get("techniques") or [])),+ rule_ids=tuple(str(r) for r in (match_raw.get("rule_ids") or [])),+ sources=tuple(str(s) for s in (match_raw.get("sources") or [])),+ keywords=tuple(str(k) for k in (match_raw.get("keywords") or [])),+ ),+ plan=tuple(str(p) for p in (body.get("plan") or [])),+ expected_pivots=tuple(str(p) for p in (body.get("expected_pivots") or [])),+ applies_when=str(body.get("applies_when") or ""),+ guidance=str(body.get("guidance") or ""),+ verdict_guidance=str(body.get("verdict_guidance") or ""),+ required_evidence=tuple(str(e) for e in (body.get("required_evidence") or [])),+ escalate_when=tuple(str(e) for e in (body.get("escalate_when") or [])),+ min_pivots=int(body.get("min_pivots") or 2),+ raw_yaml=raw_yaml,+ )diff --git a/services/api/app/services/tenant_skills/store.py b/services/api/app/services/tenant_skills/store.pynew file mode 100644index 000000000..a709b9bb2--- /dev/null+++ b/services/api/app/services/tenant_skills/store.py@@ -0,0 +1,462 @@+"""Storage and lifecycle for tenant skills: draft, backtested, active, retired.++Gap-closure Phase 6.2.++The lifecycle is the point of this module, and the two rules that make it+worth having are both refusals.++**An edit un-backtests the skill.** Saving new text bumps the version and+drops the row back to ``draft``, discarding the attached reports. A backtest+is a statement about a specific body of text, and carrying it forward across+an edit is how a report comes to describe something nobody is running. The+cost is that an author who fixes a typo runs the backtest again; that is the+correct cost.++**Activation requires a backtest of the exact version being activated**, and+requires both halves of it, the baseline and the candidate. The plan asks for+"before and after metrics side by side", and a candidate score with no+baseline is a number rather than a comparison. The database constraint says+the same thing, so neither this module nor a later one can be the only place+the rule lives.++What a backtest is here+-----------------------+Two Phase 1 replay evaluations over the same history window: one with the+tenant's active skills as they are, one with this skill added. Nothing in this+phase re-implements replay, scoring or reporting. ``services/api/app/services/+replay_evaluation/job.py`` runs both, and this module records which two runs+belong to which skill version.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Any++import structlog+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.tenant_skill import (+ ACTIVE,+ BACKTESTED,+ DRAFT,+ RETIRED,+ TenantSkillVersion,+)+from app.models.tenant_skill import (+ TenantSkill as TenantSkillRow,+)+from app.services.tenant_skills.models import SkillParseError, TenantSkill, parse_skill_yaml, skill_from_body+from app.services.tenant_skills.tools import tool_inventory_for_tenant, validate_expected_pivots++logger = structlog.get_logger(__name__)++__all__ = [+ "SkillLifecycleError",+ "SkillNotFound",+ "activate_skill",+ "attach_backtest",+ "delete_skill",+ "get_skill",+ "list_skills",+ "list_versions",+ "resolve_active_skills",+ "retire_skill",+ "save_skill",+ "validate_yaml",+]+++class SkillNotFound(LookupError):+ """No such skill for this tenant."""+++class SkillLifecycleError(ValueError):+ """A lifecycle transition was refused. The message reaches the operator verbatim."""+++async def _row(db: AsyncSession, tenant_id: uuid.UUID, skill_id: str) -> TenantSkillRow:+ row = (+ await db.execute(+ select(TenantSkillRow).where(+ TenantSkillRow.tenant_id == tenant_id,+ TenantSkillRow.skill_id == skill_id,+ )+ )+ ).scalar_one_or_none()+ if row is None:+ raise SkillNotFound(f"no skill {skill_id!r} for this tenant")+ return row+++async def list_skills(db: AsyncSession, tenant_id: uuid.UUID) -> list[TenantSkillRow]:+ return list(+ (await db.execute(select(TenantSkillRow).where(TenantSkillRow.tenant_id == tenant_id).order_by(TenantSkillRow.skill_id)))+ .scalars()+ .all()+ )+++async def get_skill(db: AsyncSession, tenant_id: uuid.UUID, skill_id: str) -> TenantSkillRow:+ return await _row(db, tenant_id, skill_id)+++async def list_versions(db: AsyncSession, tenant_id: uuid.UUID, skill_id: str) -> list[TenantSkillVersion]:+ """Every version of one skill, newest first.++ This is the read that turns the ``(skill_id, version)`` pair recorded on+ an investigation back into the text that was in force.+ """+ return list(+ (+ await db.execute(+ select(TenantSkillVersion)+ .where(+ TenantSkillVersion.tenant_id == tenant_id,+ TenantSkillVersion.skill_id == skill_id,+ )+ .order_by(TenantSkillVersion.version.desc())+ )+ )+ .scalars()+ .all()+ )+++async def validate_yaml(db: AsyncSession, tenant_id: uuid.UUID, source_yaml: str) -> TenantSkill:+ """Parse and validate without writing anything.++ Backs the editor's validate button, and is the same call ``save_skill``+ makes, so what the editor says is what the save will do.+ """+ skill = parse_skill_yaml(source_yaml)+ inventory = await tool_inventory_for_tenant(db, tenant_id)+ validate_expected_pivots(skill, inventory)+ return skill+++async def save_skill(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ author_id: uuid.UUID | None,+ source_yaml: str,+) -> tuple[TenantSkillRow, bool]:+ """Create or update a skill from its YAML. Returns the row and whether it is new.++ A save whose parsed body is byte-identical to the stored one is a no-op on+ the version: an author who reformats a comment has not changed what the+ agent reads, and bumping the version there would invalidate a backtest+ over nothing. Comparison is on the parsed body rather than on the YAML+ text for exactly that reason.+ """+ skill = await validate_yaml(db, tenant_id, source_yaml)+ body = skill.as_dict()+ now = datetime.now(UTC)++ try:+ row = await _row(db, tenant_id, skill.id)+ except SkillNotFound:+ row = TenantSkillRow(+ tenant_id=tenant_id,+ skill_id=skill.id,+ version=1,+ status=DRAFT,+ name=skill.name,+ owner=skill.owner,+ expires_at=skill.expires_at,+ body=body,+ source_yaml=skill.raw_yaml,+ created_by=author_id,+ created_at=now,+ updated_at=now,+ )+ db.add(row)+ await db.flush()+ _record_version(db, row, authored_by=author_id, authored_at=now)+ logger.info("tenant_skill.created", tenant_id=str(tenant_id), skill_id=skill.id, version=1)+ return row, True++ if row.body == body:+ # Text-only change (comments, ordering, whitespace). Keep the version+ # and any attached backtest, and store the author's formatting.+ row.source_yaml = skill.raw_yaml+ row.updated_at = now+ return row, False++ row.version = int(row.version) + 1+ row.name = skill.name+ row.owner = skill.owner+ row.expires_at = skill.expires_at+ row.body = body+ row.source_yaml = skill.raw_yaml+ # The edit invalidates the backtest, so the row goes back to draft and the+ # reports are detached rather than silently carried onto new text.+ row.status = DRAFT+ row.backtest_evaluation_id = None+ row.backtest_baseline_id = None+ row.backtest_version = None+ row.activated_at = None+ row.activated_by = None+ row.updated_at = now++ _record_version(db, row, authored_by=author_id, authored_at=now)+ logger.info("tenant_skill.updated", tenant_id=str(tenant_id), skill_id=skill.id, version=row.version)+ return row, False+++def _record_version(+ db: AsyncSession,+ row: TenantSkillRow,+ *,+ authored_by: uuid.UUID | None,+ authored_at: datetime,+) -> None:+ db.add(+ TenantSkillVersion(+ tenant_id=row.tenant_id,+ skill_row_id=row.id,+ skill_id=row.skill_id,+ version=row.version,+ name=row.name,+ owner=row.owner,+ expires_at=row.expires_at,+ body=dict(row.body or {}),+ source_yaml=row.source_yaml,+ authored_by=authored_by,+ authored_at=authored_at,+ )+ )+++async def attach_backtest(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ skill_id: str,+ baseline_evaluation_id: uuid.UUID,+ candidate_evaluation_id: uuid.UUID,+) -> TenantSkillRow:+ """Record the two replay runs that graded the current version.++ Both ids, and they must differ. One evaluation used as its own baseline+ would produce a delta of exactly zero on every axis and read as "the skill+ changed nothing", which is a conclusion rather than an absence of one.+ """+ if baseline_evaluation_id == candidate_evaluation_id:+ raise SkillLifecycleError(+ "the baseline and candidate backtest runs are the same evaluation; a comparison needs two runs, "+ "one with this skill and one without"+ )+ row = await _row(db, tenant_id, skill_id)+ if row.status == RETIRED:+ raise SkillLifecycleError("this skill is retired; save it again to return it to draft before backtesting")++ row.backtest_baseline_id = baseline_evaluation_id+ row.backtest_evaluation_id = candidate_evaluation_id+ row.backtest_version = int(row.version)+ if row.status == DRAFT:+ row.status = BACKTESTED+ row.updated_at = datetime.now(UTC)++ await _stamp_version(+ db,+ row,+ baseline_evaluation_id=baseline_evaluation_id,+ candidate_evaluation_id=candidate_evaluation_id,+ )+ logger.info(+ "tenant_skill.backtest_attached",+ tenant_id=str(tenant_id),+ skill_id=skill_id,+ version=row.version,+ )+ return row+++async def _stamp_version(+ db: AsyncSession,+ row: TenantSkillRow,+ *,+ baseline_evaluation_id: uuid.UUID | None = None,+ candidate_evaluation_id: uuid.UUID | None = None,+ activated_at: datetime | None = None,+ activated_by: uuid.UUID | None = None,+ retired_at: datetime | None = None,+) -> None:+ version_row = (+ await db.execute(+ select(TenantSkillVersion).where(+ TenantSkillVersion.tenant_id == row.tenant_id,+ TenantSkillVersion.skill_id == row.skill_id,+ TenantSkillVersion.version == row.version,+ )+ )+ ).scalar_one_or_none()+ if version_row is None:+ # Reachable only if history was purged under a live row. Say so rather+ # than carrying on: the history table is what makes a recorded version+ # resolvable, and continuing would leave a live skill with none.+ logger.warning(+ "tenant_skill.version_row_missing",+ skill_id=row.skill_id,+ version=row.version,+ hint="the recorded version will not resolve back to its text",+ )+ return+ if baseline_evaluation_id is not None:+ version_row.backtest_baseline_id = baseline_evaluation_id+ if candidate_evaluation_id is not None:+ version_row.backtest_evaluation_id = candidate_evaluation_id+ if activated_at is not None:+ version_row.activated_at = activated_at+ version_row.activated_by = activated_by+ if retired_at is not None:+ version_row.retired_at = retired_at+++async def activate_skill(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ skill_id: str,+ actor_id: uuid.UUID | None,+ now: datetime | None = None,+) -> TenantSkillRow:+ """Put a backtested skill into service. Four refusals, each with its own reason."""+ moment = now or datetime.now(UTC)+ row = await _row(db, tenant_id, skill_id)++ if row.backtest_evaluation_id is None or row.backtest_baseline_id is None:+ raise SkillLifecycleError(+ "this skill has no backtest attached. Run the backtest first: it replays the tenant's own "+ "closed findings with and without the skill and reports both, and activating without it "+ "puts untested guidance in front of every matching alert."+ )+ if row.backtest_version != int(row.version):+ raise SkillLifecycleError(+ f"the attached backtest graded version {row.backtest_version} and this skill is now at version "+ f"{row.version}. Re-run the backtest, or the report on the activation describes text nobody is running."+ )+ expires_at = row.expires_at if row.expires_at.tzinfo else row.expires_at.replace(tzinfo=UTC)+ if expires_at <= moment:+ raise SkillLifecycleError(+ f"this skill expired at {expires_at.isoformat()}. Extend 'expires_at' and re-run the backtest: "+ f"the resolver drops an expired skill, so activating it would be a no-op that looks like a change."+ )+ if row.status == ACTIVE:+ raise SkillLifecycleError("this skill is already active")++ row.status = ACTIVE+ row.activated_at = moment+ row.activated_by = actor_id+ row.updated_at = moment+ await _stamp_version(db, row, activated_at=moment, activated_by=actor_id)+ logger.info(+ "tenant_skill.activated",+ tenant_id=str(tenant_id),+ skill_id=skill_id,+ version=row.version,+ backtest_evaluation_id=str(row.backtest_evaluation_id),+ )+ return row+++async def retire_skill(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ skill_id: str,+ now: datetime | None = None,+) -> TenantSkillRow:+ """Take a skill out of service, keeping its history."""+ moment = now or datetime.now(UTC)+ row = await _row(db, tenant_id, skill_id)+ row.status = RETIRED+ row.updated_at = moment+ await _stamp_version(db, row, retired_at=moment)+ logger.info("tenant_skill.retired", tenant_id=str(tenant_id), skill_id=skill_id, version=row.version)+ return row+++async def delete_skill(db: AsyncSession, *, tenant_id: uuid.UUID, skill_id: str) -> bool:+ """Remove a skill and, by cascade, its version history.++ Offered because an operator who created a skill by mistake should not have+ to keep it forever. An operator taking a *working* skill out of service+ wants :func:`retire_skill`, which keeps the history that explains verdicts+ the skill already steered.+ """+ try:+ row = await _row(db, tenant_id, skill_id)+ except SkillNotFound:+ return False+ await db.delete(row)+ return True+++async def resolve_active_skills(+ db: AsyncSession,+ tenant_id: uuid.UUID,+ *,+ now: datetime | None = None,+) -> list[dict[str, Any]]:+ """Active, unexpired skills for the agents service, newest activation first.++ Expiry is applied **in the query**, the same choice+ ``analyst_feedback.active_statements`` makes: a skill stops steering the+ moment it expires rather than whenever a worker next restarts. A skill+ dropped for expiry is logged, because the operator-visible symptom is an+ agent that quietly stopped following their guidance.+ """+ moment = now or datetime.now(UTC)+ rows = list(+ (+ await db.execute(+ select(TenantSkillRow)+ .where(+ TenantSkillRow.tenant_id == tenant_id,+ TenantSkillRow.status == ACTIVE,+ )+ .order_by(TenantSkillRow.skill_id)+ )+ )+ .scalars()+ .all()+ )++ resolved: list[dict[str, Any]] = []+ expired: list[str] = []+ for row in rows:+ expires_at = row.expires_at if row.expires_at.tzinfo else row.expires_at.replace(tzinfo=UTC)+ if expires_at <= moment:+ expired.append(row.skill_id)+ continue+ resolved.append(+ {+ "skill_id": row.skill_id,+ "version": int(row.version),+ "activated_at": row.activated_at.isoformat() if row.activated_at else None,+ "expires_at": expires_at.isoformat(),+ "body": dict(row.body or {}),+ }+ )++ if expired:+ logger.info(+ "tenant_skill.expired_not_served",+ tenant_id=str(tenant_id),+ skills=sorted(expired),+ hint="these skills are active but past their expiry, so they no longer steer investigations",+ )+ return resolved+++def body_to_skill(body: dict[str, Any]) -> TenantSkill:+ """Rebuild a parsed skill from a stored body, for callers that want the dataclass."""+ try:+ return skill_from_body(body)+ except SkillParseError: # pragma: no cover - a stored body was written by the parser+ raisediff --git a/services/api/app/services/tenant_skills/tools.py b/services/api/app/services/tenant_skills/tools.pynew file mode 100644index 000000000..0798dc69e--- /dev/null+++ b/services/api/app/services/tenant_skills/tools.py@@ -0,0 +1,261 @@+"""What tools one tenant's agent can actually reach, and the refusal when a skill names another.++Gap-closure Phase 6.1's validation rule: "validation rejects any expected+pivot that names a tool the tenant does not have".++Three sources, and they are different kinds of fact+----------------------------------------------------+**Built-in pivots** are the lake-backed investigation tools every tenant's+agent binds, listed in ``BUILTIN_PIVOTS``. They are a property of the build,+not of the tenant, which is why they are a constant here rather than a query.++**Customer tools** are Phase 4's typed surface onto the tenant's own SIEM,+EDR, identity provider and cloud audit trail. They are per-tenant and the+answer comes from the same three reads ``GET /agent-tools/backends`` makes, so+the set a skill is validated against is the set the agent will actually bind+rather than a second opinion about it.++**MCP tools** are per-tenant and come from the Phase 5.2 registry: an enabled+server's ``tool_allowlist``, namespaced ``mcp.<server>.<tool>``.++Why the tool names are duplicated rather than imported+-------------------------------------------------------+``services/api`` and ``services/agents`` both package their code as top-level+``app``, so this service cannot import ``app.investigator.strategies`` or+``app.tools.customer_tools``. ``scripts/check_tenant_skill_contract.py``+parses both sides and compares them **in both directions**, because the+one-directional check is the failure shape this repository keeps finding in+its own gates: a tool added in agents and not here would make a legitimate+skill unauthorable, and a tool removed in agents and left here would let a+skill name one that no longer exists and fail at investigation time instead of+at save time. That gate has already earned its keep once, catching six+customer tools Phase 4 added to ``KNOWN_PIVOTS`` while this file was in+flight.++"Could not check" is not "you do not have it"+----------------------------------------------+When the action registry is unreachable, ``available_reads`` cannot say which+vendor verbs this tenant has. Refusing the skill then would tell an author+their EDR is not connected because a different service was briefly down, and+they would delete a correct line from their document. So a *known* customer+tool name is accepted while the registry is unknown and+:attr:`ToolInventory.customer_unknown` says so, which the console surfaces. A+name that is not a customer tool at all is still refused, because that is a+typo rather than an outage. This is the same distinction Phase 4.3 draws for+the prompt: unknown and absent send a reader to different places.+"""++from __future__ import annotations++import uuid+from dataclasses import dataclass, field++import structlog+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.mcp_server import McpServer+from app.services import actions_client+from app.services.agent_tools import siem_search, vendor_reads+from app.services.tenant_skills.models import SkillParseError, TenantSkill++logger = structlog.get_logger(__name__)++__all__ = [+ "BUILTIN_PIVOTS",+ "CUSTOMER_TOOL_CAPABILITIES",+ "MCP_PREFIX",+ "SIEM_SEARCH_TOOL",+ "ToolInventory",+ "tool_inventory_for_tenant",+ "validate_expected_pivots",+]++#: Every lake-backed investigation tool the agent binds for any tenant. Kept+#: in step with the lake half of ``KNOWN_PIVOTS`` in+#: ``services/agents/app/investigator/strategies.py`` by+#: ``scripts/check_tenant_skill_contract.py``.+BUILTIN_PIVOTS: frozenset[str] = frozenset(+ {+ "process_activity",+ "historical_execution",+ "network_connections",+ "authentication_events",+ "fleet_ioc_hunt",+ "entity_timeline",+ "technique_activity",+ "process_tree",+ "mailbox_activity",+ "oauth_grants",+ "persistence_mechanisms",+ }+)++#: The federated-SIEM tool, bound when the feature is on and the tenant has at+#: least one searchable SIEM connector. Mirrors ``SIEM_SEARCH_TOOL`` in+#: ``services/agents/app/tools/customer_tools.py``.+SIEM_SEARCH_TOOL = "siem_indicator_search"++#: Tool name to the capability the action registry advertises it under.+#: Mirrors ``VENDOR_READ_TOOLS`` in the agents service; the gate compares the+#: names **and** the capabilities in both directions, because a tool whose+#: capability drifted would validate against a verb the tenant does not have.+CUSTOMER_TOOL_CAPABILITIES: dict[str, str] = {+ "edr_host_details": "get_host",+ "edr_host_detections": "get_detections",+ "identity_user_activity": "get_user_activity",+ "cloud_audit_lookup": "lookup_cloud_audit",+ "endpoint_telemetry_sightings": "lookup_endpoint_telemetry",+}++#: The namespace ``app.mcp.policy.namespaced`` produces. A skill names an MCP+#: tool by its namespaced form, because that is the name the model is shown.+MCP_PREFIX = "mcp."+++@dataclass(frozen=True)+class ToolInventory:+ """Everything this tenant's agent may be asked to call, by name."""++ builtin: frozenset[str] = BUILTIN_PIVOTS+ customer: frozenset[str] = field(default_factory=frozenset)+ mcp: frozenset[str] = field(default_factory=frozenset)++ #: The action registry could not be asked, so which vendor verbs this+ #: tenant has is unknown rather than empty. A known customer tool name is+ #: accepted while this is true; see the module docstring.+ customer_unknown: bool = False+ customer_unknown_reason: str = ""++ @property+ def names(self) -> frozenset[str]:+ return self.builtin | self.customer | self.mcp++ def as_dict(self) -> dict[str, object]:+ return {+ "builtin": sorted(self.builtin),+ "customer": sorted(self.customer),+ "mcp": sorted(self.mcp),+ "customer_unknown": self.customer_unknown,+ "customer_unknown_reason": self.customer_unknown_reason,+ }+++def _namespaced(server: str, tool: str) -> str:+ return f"{MCP_PREFIX}{server}.{tool}"+++async def _customer_tools(db: AsyncSession, tenant_id: uuid.UUID) -> tuple[frozenset[str], bool, str]:+ """Which Phase 4 customer tools this tenant has a backend for.++ The same three reads ``GET /agent-tools/backends`` makes, in the same+ order, so the set validated against and the set bound at investigation+ time come from one source rather than two that happen to agree.+ """+ names: set[str] = set()++ if siem_search.feature_enabled():+ # Imported here rather than at module scope: `endpoints.federated`+ # imports the v1 dependency stack, and a service module reaching back+ # into an endpoints module at import time is an import cycle waiting+ # for the next file that needs both. The backends route resolves it+ # the same way.+ from app.api.v1.endpoints.federated import _fetch_target_connectors++ if await _fetch_target_connectors(db, tenant_id, requested_ids=None):+ names.add(SIEM_SEARCH_TOOL)++ try:+ reads = await vendor_reads.available_reads(db, tenant_id=tenant_id)+ except actions_client.ActionsServiceError as exc:+ logger.warning("tenant_skills.registry_unreachable", tenant_id=str(tenant_id))+ return frozenset(names), True, exc.upstream_detail or "the action registry could not be reached"++ capabilities = {entry.as_dict().get("capability") for entry in reads}+ names |= {tool for tool, capability in CUSTOMER_TOOL_CAPABILITIES.items() if capability in capabilities}+ return frozenset(names), False, ""+++async def tool_inventory_for_tenant(db: AsyncSession, tenant_id: uuid.UUID) -> ToolInventory:+ """The tenant's tool inventory, read from their own rows and their own registry.++ Only **enabled** MCP servers contribute, and only the tools on their+ allowlist. Both halves matter: a registered-but-disabled server offers+ nothing to an investigation, and an enabled server with an empty allowlist+ offers nothing either, which is the state every newly registered server is+ in. Validating against the registered set instead would let a skill name a+ tool the agent will never be handed.+ """+ rows = (+ await db.execute(+ select(McpServer.name, McpServer.tool_allowlist).where(+ McpServer.tenant_id == tenant_id,+ McpServer.enabled.is_(True),+ )+ )+ ).all()++ mcp: set[str] = set()+ for name, allowlist in rows:+ for tool in allowlist or []:+ if isinstance(tool, str) and tool.strip():+ mcp.add(_namespaced(str(name), tool.strip()))++ customer, unknown, reason = await _customer_tools(db, tenant_id)+ return ToolInventory(+ customer=customer,+ mcp=frozenset(mcp),+ customer_unknown=unknown,+ customer_unknown_reason=reason,+ )+++#: Every customer tool name that exists in the build, whether or not any given+#: tenant has its backend. Used only to tell a typo from an outage.+_ALL_CUSTOMER_TOOLS: frozenset[str] = frozenset({SIEM_SEARCH_TOOL, *CUSTOMER_TOOL_CAPABILITIES})+++def validate_expected_pivots(skill: TenantSkill, inventory: ToolInventory) -> None:+ """Refuse a skill naming a tool this tenant's agent cannot call.++ The message names the pivot and says which of the three reasons applies,+ because the author's next action differs completely between "you typed the+ name wrong", "you have to connect that product first" and "you have to+ allowlist that tool on that server first".+ """+ unknown = [p for p in skill.expected_pivots if p not in inventory.names]+ if not unknown:+ return++ lines: list[str] = []+ for pivot in unknown:+ if pivot.startswith(MCP_PREFIX):+ lines.append(+ f"{pivot!r}: no enabled MCP server in this tenant allowlists that tool. "+ f"Register the server, enable it, and add the tool to its allowlist first."+ )+ elif pivot in _ALL_CUSTOMER_TOOLS:+ if inventory.customer_unknown:+ # Reachable only if a caller built an inventory by hand; the+ # loop below skips these when the registry is unknown.+ continue+ lines.append(+ f"{pivot!r}: this tenant has no connected product behind that tool. "+ f"Connect the SIEM, EDR, identity provider or cloud audit source it reads, then save again."+ )+ else:+ lines.append(+ f"{pivot!r}: not a tool this deployment has. "+ f"Built-in tools are {', '.join(sorted(inventory.builtin))}. "+ f"The customer-product tools are {', '.join(sorted(_ALL_CUSTOMER_TOOLS))}. "+ f"A tool on a third-party MCP server is named 'mcp.<server>.<tool>'."+ )++ if not lines:+ return+ raise SkillParseError(+ "'expected_pivots' names "+ + ("a tool" if len(lines) == 1 else f"{len(lines)} tools")+ + " this tenant's agent cannot call:\n "+ + "\n ".join(lines)+ )diff --git a/services/api/migrations/070_tenant_skills.sql b/services/api/migrations/070_tenant_skills.sqlnew file mode 100644index 000000000..e752fdbfc--- /dev/null+++ b/services/api/migrations/070_tenant_skills.sql@@ -0,0 +1,196 @@+-- 070: tenant-authored investigation skills, and the version history that+-- makes a six-month-old verdict explainable.+--+-- Gap-closure Phase 6.1 and 6.2.+--+-- A skill is customer-authored content that steers an agent's plan and its+-- verdict. That puts it in the same class as a detection rule rather than in+-- the class of a settings toggle, and the difference is entirely in what has+-- to be recoverable afterwards. When an auto-close is disputed six months+-- later, "which text was steering the agent that day" has to have an answer,+-- and a single mutable row cannot give one.+--+-- Why two tables+-- --------------+-- `aisoc_tenant_skills` is the current state of each skill: one row per+-- `(tenant_id, skill_id)`, which is what the console lists and what the+-- agents service resolves on the hot path of an investigation.+--+-- `aisoc_tenant_skill_versions` is append-only history: one immutable row per+-- version, holding the body that was in force, who authored it, the backtest+-- that graded it and when it was activated. An investigation records+-- `skill_id` and `version`, and this is the table that turns that pair back+-- into the text. Without it the recorded version is a number pointing at+-- nothing, which is worse than recording nothing at all because it looks like+-- provenance.+--+-- Why activation carries a backtest id and a version+-- ---------------------------------------------------+-- `backtest_evaluation_id` alone is not enough. A skill backtested at version+-- 2, edited into version 3 and then activated would carry a report about text+-- nobody is running. `backtest_version` records which version the report+-- graded, and the activate route refuses when it is not the version being+-- activated. The constraint below is the floor under that check: an active+-- row must name a backtest, and the backtest must be of the active version.+--+-- Why expiry is NOT NULL+-- ----------------------+-- A skill states what is normal in one organisation. Organisational facts+-- rot: a service account is decommissioned, a subnet is re-purposed, a+-- nightly job moves. A skill with no review date keeps steering verdicts+-- after it stops being true, and nothing surfaces that. Expiry is required at+-- authoring time and the resolver drops an expired skill, so the failure mode+-- is "the agent stopped using my skill" rather than "the agent kept using it".+--+-- Why the status ladder is a CHECK and not an application constant+-- ----------------------------------------------------------------+-- `draft -> backtested -> active` is the lifecycle the plan specifies, plus+-- `retired` for a skill an operator has taken out of service without+-- deleting its history. Writing it into the column means a row cannot reach a+-- state the application does not know about, including through a migration+-- replay or a direct fix-up by an operator.++CREATE TABLE IF NOT EXISTS aisoc_tenant_skills (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,++ -- The author's stable identifier, kebab-case. Stable across versions:+ -- this is what an investigation records alongside the version number.+ skill_id TEXT NOT NULL CHECK (skill_id ~ '^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$'),++ -- Assigned by the server, incremented on every content change. Never set+ -- by the author; the parser refuses `version:` as a document key so there+ -- is exactly one authority for what version 3 is.+ version INTEGER NOT NULL DEFAULT 1 CHECK (version >= 1),++ status TEXT NOT NULL DEFAULT 'draft'+ CHECK (status IN ('draft', 'backtested', 'active', 'retired')),++ name TEXT NOT NULL,+ -- Who to ask when a verdict this skill steered is disputed.+ owner TEXT NOT NULL,+ -- Required. See the header: an organisational fact with no review date+ -- goes on steering verdicts after it stops being true.+ expires_at TIMESTAMPTZ NOT NULL,++ -- The parsed skill. The agents service is served from this rather than+ -- from the YAML, so a later parser change cannot make an already-active+ -- skill unreadable at triage time.+ body JSONB NOT NULL,+ -- The author's text, for round-tripping into the editor with their+ -- comments and formatting intact.+ source_yaml TEXT NOT NULL,++ -- The Phase 1 replay that graded this skill, and the version it graded.+ backtest_evaluation_id UUID REFERENCES aisoc_replay_evaluations(id) ON DELETE SET NULL,+ backtest_baseline_id UUID REFERENCES aisoc_replay_evaluations(id) ON DELETE SET NULL,+ backtest_version INTEGER,++ activated_at TIMESTAMPTZ,+ activated_by UUID REFERENCES users(id) ON DELETE SET NULL,++ created_by UUID REFERENCES users(id) ON DELETE SET NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ UNIQUE (tenant_id, skill_id),++ -- An active skill must name the backtest of the exact version that is+ -- active. Two reports side by side is what the plan asks for, so the+ -- baseline is required too: an "after" figure with no "before" is not a+ -- comparison, it is a number.+ CONSTRAINT aisoc_tenant_skills_active_is_backtested CHECK (+ status <> 'active'+ OR (+ backtest_evaluation_id IS NOT NULL+ AND backtest_baseline_id IS NOT NULL+ AND backtest_version = version+ )+ )+);++COMMENT ON TABLE aisoc_tenant_skills IS+ 'Tenant-authored investigation skills: current state, one row per skill. '+ 'Steers the investigation plan and the triage prompt on matching alerts.';+COMMENT ON COLUMN aisoc_tenant_skills.version IS+ 'Server-assigned, incremented on every content change. An investigation '+ 'records (skill_id, version); aisoc_tenant_skill_versions turns that back '+ 'into the text that was in force.';+COMMENT ON COLUMN aisoc_tenant_skills.backtest_version IS+ 'Which version the attached backtest graded. Activation refuses when it is '+ 'not the version being activated, so a report can never describe text '+ 'nobody is running.';+COMMENT ON COLUMN aisoc_tenant_skills.expires_at IS+ 'Required. The resolver drops an expired skill, so a stale organisational '+ 'fact stops steering rather than steering silently.';++CREATE INDEX IF NOT EXISTS idx_tenant_skills_tenant_status+ ON aisoc_tenant_skills (tenant_id, status);++-- Append-only history. Nothing updates a row here except the activation+-- stamp, which is itself a fact about that version rather than a change to it.+CREATE TABLE IF NOT EXISTS aisoc_tenant_skill_versions (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ -- Denormalised so the RLS policy on this table stands on its own rather+ -- than on a join, the same reasoning as aisoc_replay_decisions: a policy+ -- that has to reach another table to decide returns nothing when that+ -- table is itself filtered.+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ skill_row_id UUID NOT NULL REFERENCES aisoc_tenant_skills(id) ON DELETE CASCADE,++ skill_id TEXT NOT NULL,+ version INTEGER NOT NULL CHECK (version >= 1),++ name TEXT NOT NULL,+ owner TEXT NOT NULL,+ expires_at TIMESTAMPTZ NOT NULL,+ body JSONB NOT NULL,+ source_yaml TEXT NOT NULL,++ backtest_evaluation_id UUID REFERENCES aisoc_replay_evaluations(id) ON DELETE SET NULL,+ backtest_baseline_id UUID REFERENCES aisoc_replay_evaluations(id) ON DELETE SET NULL,++ authored_by UUID REFERENCES users(id) ON DELETE SET NULL,+ authored_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ activated_at TIMESTAMPTZ,+ activated_by UUID REFERENCES users(id) ON DELETE SET NULL,+ retired_at TIMESTAMPTZ,++ UNIQUE (tenant_id, skill_id, version)+);++COMMENT ON TABLE aisoc_tenant_skill_versions IS+ 'Append-only history of every tenant skill version, with the backtest that '+ 'graded it and when it was activated. This is what makes (skill_id, '+ 'version) recorded on an investigation resolvable back to the text.';++CREATE INDEX IF NOT EXISTS idx_tenant_skill_versions_lookup+ ON aisoc_tenant_skill_versions (tenant_id, skill_id, version);++-- Row-level security. The `OR current_tenant_id() IS NULL` arm is what lets+-- the cross-tenant workers (retention purge, tenant deletion) reach these+-- tables; dropping it makes those silently see nothing. FORCE so the table+-- owner, which is the role that runs migrations, does not walk past it.+ALTER TABLE aisoc_tenant_skills ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_tenant_skills FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_tenant_skills_tenant ON aisoc_tenant_skills;+CREATE POLICY aisoc_tenant_skills_tenant ON aisoc_tenant_skills+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++ALTER TABLE aisoc_tenant_skill_versions ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_tenant_skill_versions FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_tenant_skill_versions_tenant ON aisoc_tenant_skill_versions;+CREATE POLICY aisoc_tenant_skill_versions_tenant ON aisoc_tenant_skill_versions+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++-- 061 set ALTER DEFAULT PRIVILEGES so new tables pick these up, but only for+-- tables created by the role that ran it. Granting explicitly means a chain+-- replayed by a different owner still leaves the runtime role able to work.+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_tenant_skills TO aisoc_app;+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_tenant_skill_versions TO aisoc_app;+ END IF;+END+$$;diff --git a/services/api/tests/test_tenant_skills.py b/services/api/tests/test_tenant_skills.pynew file mode 100644index 000000000..07a6cbff5--- /dev/null+++ b/services/api/tests/test_tenant_skills.py@@ -0,0 +1,736 @@+"""Tenant skills: what the parser refuses, what the lifecycle refuses, and who may read.++Gap-closure Phase 6.1 and 6.2 gate.++Five properties, each asserted by name below:++* the document refuses what a skill cannot be without: no owner, no expiry, no+ match block, no plan, no pivots, and any key the server owns+* ``expected_pivots`` is checked against the tools *this tenant* can call,+ which is the built-in set plus the tools on an enabled MCP server's+ allowlist, and the refusal tells the author which of the two reasons applies+* an edit bumps the version and drops the skill back to draft, detaching the+ backtest, so a report can never describe text nobody is running+* activation refuses every way of reaching it without a current backtest, and+ the message names which one+* the internal route is service-token only, and a valid console session is not+ enough++The database is a real one, the same way ``test_mcp_registry.py`` does it:+Postgres-only column types compile down to their SQLite equivalents so these+exercise the real statements rather than a stub that agrees with them.++The CHECK constraints do not compile to SQLite, so the lifecycle refusals here+are the *store's*. The migration states the same rule and+``scripts/check_tenant_skill_contract.py`` fails the build if either place+loses it, which is what keeps one from becoming the only guard.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta++import pytest+import pytest_asyncio+from app.api.v1.deps import CurrentUser, get_current_user+from app.api.v1.endpoints import tenant_skills as endpoint_module+from app.api.v1.endpoints.tenant_skills import router as skills_router+from app.db.database import Base, get_db+from app.db.rls import get_tenant_db+from app.models.connector import Connector+from app.models.mcp_server import McpServer+from app.models.tenant_skill import ACTIVE, BACKTESTED, DRAFT, RETIRED, TenantSkill, TenantSkillVersion+from app.services.agent_tools import vendor_reads+from app.services.tenant_skills import store+from app.services.tenant_skills.models import SkillParseError, parse_skill_yaml+from app.services.tenant_skills.tools import BUILTIN_PIVOTS, ToolInventory, tool_inventory_for_tenant, validate_expected_pivots+from fastapi import FastAPI+from fastapi.testclient import TestClient+from sqlalchemy.dialects.postgresql import JSONB+from sqlalchemy.dialects.postgresql import UUID as PgUUID+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+from sqlalchemy.ext.compiler import compiles++TENANT = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")+OTHER_TENANT = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")+USER = uuid.UUID("11111111-1111-1111-1111-111111111111")++SERVICE_TOKEN = "service-token-for-the-agents-worker"++FAR_FUTURE = "2099-01-31"+++@compiles(JSONB, "sqlite")+def _jsonb_sqlite(_type_, _compiler_, **_kw_):+ return "TEXT"+++@compiles(PgUUID, "sqlite")+def _uuid_sqlite(_type_, _compiler_, **_kw_):+ return "CHAR(36)"+++def _yaml(+ *,+ skill_id: str = "finance-batch-powershell",+ guidance: str = "Finance runs a nightly reconciliation batch on FIN-APP hosts.",+ pivots: str = "[process_activity, process_tree]",+ expires_at: str = FAR_FUTURE,+ extra: str = "",+) -> str:+ return f"""+id: {skill_id}+name: Finance nightly batch+owner: [email protected]+expires_at: {expires_at}+match:+ techniques: [T1059.001]+ rule_ids: [rule-encoded-powershell]+guidance: >+ {guidance}+verdict_guidance: >+ Encoded PowerShell from svc_batch inside the window is a benign true positive.+plan:+ - List what executed on the host around the alert.+ - Establish the process lineage.+expected_pivots: {pivots}+min_pivots: 2+{extra}+""".strip()+++def _one_pivot(pivot: str) -> str:+ """A document naming exactly one pivot, with the floor lowered to match."""+ return _yaml(pivots=f"[{pivot}]").replace("min_pivots: 2", "min_pivots: 1")++[email protected](autouse=True)+def _quiet_action_registry(monkeypatch):+ """No action registry in a unit test, and that must not read as an outage.++ ``tool_inventory_for_tenant`` asks the actions service which vendor read+ verbs a tenant has. Left alone it would reach the network on every save,+ time out, and set ``customer_unknown``, which would make every tool+ refusal in this file pass for the wrong reason. Tests that care about the+ unreachable branch construct that inventory directly.+ """++ async def _none(db, *, tenant_id):+ return []++ monkeypatch.setattr(vendor_reads, "available_reads", _none)+ yield+++@pytest_asyncio.fixture+async def session_factory():+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")+ async with engine.begin() as conn:+ # Only these three. A whole-metadata create_all drags in models using+ # Postgres ARRAY, which SQLite cannot render.+ await conn.run_sync(+ Base.metadata.create_all,+ tables=[TenantSkill.__table__, TenantSkillVersion.__table__, McpServer.__table__, Connector.__table__],+ )+ yield async_sessionmaker(engine, expire_on_commit=False)+ await engine.dispose()+++# ---------------------------------------------------------------------------+# The document+# ---------------------------------------------------------------------------+++class TestParsing:+ """What a skill document cannot be without, and why each refusal exists."""++ def test_a_complete_document_parses_into_every_field(self) -> None:+ skill = parse_skill_yaml(_yaml())+ assert skill.id == "finance-batch-powershell"+ assert skill.owner == "[email protected]"+ assert skill.match.techniques == ("T1059.001",)+ assert skill.match.rule_ids == ("rule-encoded-powershell",)+ assert skill.expected_pivots == ("process_activity", "process_tree")+ # A bare date means end of day, not midnight: a skill written to+ # expire "on the 31st" that stops working on the evening of the 30th+ # is a surprise nobody asked for.+ assert skill.expires_at == datetime(2099, 1, 31, 23, 59, 59, tzinfo=UTC)++ @pytest.mark.parametrize(+ ("drop", "fragment"),+ [+ ("owner", "someone to ask"),+ ("expires_at", "stops being true"),+ ("match", "every alert in the tenant"),+ ("plan", "cannot steer an investigation"),+ ("expected_pivots", "cannot be graded"),+ ],+ )+ def test_the_fields_a_skill_cannot_be_without(self, drop: str, fragment: str) -> None:+ """Each refusal carries the reason, not just the field name.++ An author told "owner is required" adds a placeholder. One told why it+ is required puts a name in it.+ """+ # ``min_pivots`` goes too, so dropping ``expected_pivots`` reports the+ # missing pivots rather than a floor above a list of zero. The two+ # refusals are both correct and only the first one is the subject.+ source = _drop_block(_yaml(), drop)+ if drop == "expected_pivots":+ source = _drop_block(source, "min_pivots")+ with pytest.raises(SkillParseError) as exc:+ parse_skill_yaml(source)+ assert fragment in str(exc.value)++ @pytest.mark.parametrize("key", ["version", "status", "enabled", "tenant_id"])+ def test_a_key_the_server_owns_is_refused_by_name(self, key: str) -> None:+ with pytest.raises(SkillParseError) as exc:+ parse_skill_yaml(_yaml(extra=f"{key}: 3"))+ assert key in str(exc.value)++ def test_an_unknown_key_is_refused_rather_than_ignored(self) -> None:+ """A typo in a field name is a skill that silently does half its job.++ ``verdict_guidence`` parses fine if unknown keys are ignored, and the+ author has no way to find out short of reading a prompt.+ """+ with pytest.raises(SkillParseError) as exc:+ parse_skill_yaml(_yaml(extra="verdict_guidence: oops"))+ assert "verdict_guidence" in str(exc.value)++ def test_an_empty_match_block_is_refused(self) -> None:+ source = _drop_block(_yaml(), "match") + "\nmatch: {}"+ with pytest.raises(SkillParseError) as exc:+ parse_skill_yaml(source)+ assert "every alert in the tenant" in str(exc.value)++ def test_a_technique_that_is_not_a_technique_id_is_refused(self) -> None:+ source = _drop_block(_yaml(), "match") + "\nmatch:\n techniques: [powershell]"+ with pytest.raises(SkillParseError) as exc:+ parse_skill_yaml(source)+ assert "T1059" in str(exc.value)++ def test_min_pivots_above_the_pivot_count_is_refused(self) -> None:+ """A floor nothing can reach grades every run as shallow."""+ with pytest.raises(SkillParseError) as exc:+ parse_skill_yaml(_yaml(pivots="[process_activity]", extra="").replace("min_pivots: 2", "min_pivots: 4"))+ assert "min_pivots" in str(exc.value)+++def _drop_block(source: str, key: str) -> str:+ """Remove a top-level YAML block and everything indented under it."""+ out: list[str] = []+ skipping = False+ for line in source.splitlines():+ if line.startswith(f"{key}:"):+ skipping = True+ continue+ if skipping and (line.startswith((" ", "\t", "-")) or not line.strip()):+ continue+ skipping = False+ out.append(line)+ return "\n".join(out)+++# ---------------------------------------------------------------------------+# Tools+# ---------------------------------------------------------------------------+++class TestToolValidation:+ """A skill may only name a tool this tenant's agent can call."""++ def test_a_builtin_pivot_is_accepted(self) -> None:+ validate_expected_pivots(parse_skill_yaml(_yaml()), ToolInventory())++ def test_a_customer_tool_the_tenant_has_no_product_for_says_to_connect_one(self) -> None:+ """Phase 4's typed surface is per tenant, so a real name can still be wrong here.++ The message has to separate this from a typo: one is fixed by editing+ the document, the other by connecting a product.+ """+ skill = parse_skill_yaml(_one_pivot("edr_host_details"))+ with pytest.raises(SkillParseError) as exc:+ validate_expected_pivots(skill, ToolInventory())+ assert "no connected product behind that tool" in str(exc.value)++ validate_expected_pivots(skill, ToolInventory(customer=frozenset({"edr_host_details"})))++ def test_a_known_customer_tool_is_accepted_while_the_registry_is_unknown(self) -> None:+ """Could not check is not you do not have it.++ Refusing here would tell an author their EDR is not connected because+ a different service was briefly down, and they would delete a correct+ line from their document.+ """+ unknown = ToolInventory(customer_unknown=True, customer_unknown_reason="the action registry timed out")+ validate_expected_pivots(parse_skill_yaml(_one_pivot("edr_host_details")), unknown)++ # A name that is no tool at all is still a typo, and still refused.+ with pytest.raises(SkillParseError) as exc:+ validate_expected_pivots(parse_skill_yaml(_one_pivot("edr_host_detailz")), unknown)+ assert "not a tool this deployment has" in str(exc.value)++ def test_a_misspelt_builtin_names_the_available_ones(self) -> None:+ skill = parse_skill_yaml(_one_pivot("proccess_activity"))+ with pytest.raises(SkillParseError) as exc:+ validate_expected_pivots(skill, ToolInventory())+ message = str(exc.value)+ assert "proccess_activity" in message+ assert "process_activity" in message+ assert "mcp.<server>.<tool>" in message+ assert "edr_host_details" in message++ def test_an_mcp_tool_the_tenant_has_not_allowlisted_says_what_to_do(self) -> None:+ """The author's next action differs completely between the two reasons.++ A typo needs a correction. A tool on a server nobody enabled needs a+ registry change, and being told "not a built-in tool" would send the+ author looking for a spelling mistake that is not there.+ """+ skill = parse_skill_yaml(_one_pivot("mcp.crowdstrike.get_detections"))+ with pytest.raises(SkillParseError) as exc:+ validate_expected_pivots(skill, ToolInventory())+ assert "allowlists that tool" in str(exc.value)++ @pytest.mark.asyncio+ async def test_the_inventory_is_built_from_enabled_servers_only(self, session_factory) -> None:+ async with session_factory() as db:+ db.add_all(+ [+ McpServer(+ tenant_id=TENANT,+ name="crowdstrike",+ transport="streamable_http",+ url="https://mcp.example.invalid",+ tool_allowlist=["get_detections"],+ timeout_seconds=20,+ max_response_bytes=65536,+ enabled=True,+ ),+ # Registered but not enabled: offers nothing to an+ # investigation, so a skill must not be able to name it.+ McpServer(+ tenant_id=TENANT,+ name="sentinelone",+ transport="streamable_http",+ url="https://mcp2.example.invalid",+ tool_allowlist=["get_threats"],+ timeout_seconds=20,+ max_response_bytes=65536,+ enabled=False,+ ),+ # Another tenant's, which must not appear at all.+ McpServer(+ tenant_id=OTHER_TENANT,+ name="splunk",+ transport="streamable_http",+ url="https://mcp3.example.invalid",+ tool_allowlist=["search"],+ timeout_seconds=20,+ max_response_bytes=65536,+ enabled=True,+ ),+ ]+ )+ await db.commit()++ inventory = await tool_inventory_for_tenant(db, TENANT)++ assert inventory.mcp == frozenset({"mcp.crowdstrike.get_detections"})+ assert inventory.builtin == BUILTIN_PIVOTS+ validate_expected_pivots(parse_skill_yaml(_one_pivot("mcp.crowdstrike.get_detections")), inventory)+ with pytest.raises(SkillParseError):+ validate_expected_pivots(parse_skill_yaml(_one_pivot("mcp.sentinelone.get_threats")), inventory)+ with pytest.raises(SkillParseError):+ validate_expected_pivots(parse_skill_yaml(_one_pivot("mcp.splunk.search")), inventory)+++# ---------------------------------------------------------------------------+# Lifecycle+# ---------------------------------------------------------------------------+++class TestLifecycle:+ @pytest.mark.asyncio+ async def test_a_new_skill_starts_at_version_one_and_draft(self, session_factory) -> None:+ async with session_factory() as db:+ row, created = await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await db.commit()+ assert created is True+ assert (row.version, row.status) == (1, DRAFT)+ versions = await store.list_versions(db, TENANT, row.skill_id)+ assert [v.version for v in versions] == [1]++ @pytest.mark.asyncio+ async def test_reformatting_keeps_the_version_and_the_backtest(self, session_factory) -> None:+ """Comparison is on the parsed body, not on the YAML text.++ An author who reflows a comment has not changed what the agent reads,+ and bumping the version there would invalidate a backtest over nothing.+ """+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=uuid.uuid4(),+ candidate_evaluation_id=uuid.uuid4(),+ )+ await db.commit()++ reformatted = _yaml() + "\n# a comment the agent never reads\n"+ row, created = await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=reformatted)+ await db.commit()++ assert created is False+ assert row.version == 1+ assert row.status == BACKTESTED+ assert row.backtest_evaluation_id is not None++ @pytest.mark.asyncio+ async def test_a_content_edit_bumps_the_version_and_detaches_the_backtest(self, session_factory) -> None:+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=uuid.uuid4(),+ candidate_evaluation_id=uuid.uuid4(),+ )+ await db.commit()++ row, _ = await store.save_skill(+ db,+ tenant_id=TENANT,+ author_id=USER,+ source_yaml=_yaml(guidance="The batch moved to 03:00 UTC."),+ )+ await db.commit()++ assert row.version == 2+ assert row.status == DRAFT+ assert row.backtest_evaluation_id is None+ assert row.backtest_version is None+ # Both versions survive, which is what makes a recorded+ # ``skill@v1`` on a months-old verdict resolvable.+ assert [v.version for v in await store.list_versions(db, TENANT, row.skill_id)] == [2, 1]++ @pytest.mark.asyncio+ async def test_activation_refuses_a_skill_with_no_backtest(self, session_factory) -> None:+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await db.commit()+ with pytest.raises(store.SkillLifecycleError) as exc:+ await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ assert "no backtest attached" in str(exc.value)++ @pytest.mark.asyncio+ async def test_activation_refuses_a_backtest_of_a_different_version(self, session_factory) -> None:+ """The refusal this whole ladder exists for.++ Backtest at v1, edit to v2, activate: without this check the report on+ the activation describes text nobody is running.+ """+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=uuid.uuid4(),+ candidate_evaluation_id=uuid.uuid4(),+ )+ await db.commit()+ # Re-attaching is what a re-run does; here the edit happens after+ # the backtest and nothing re-runs it.+ row = await store.get_skill(db, TENANT, "finance-batch-powershell")+ row.version = 2+ await db.commit()++ with pytest.raises(store.SkillLifecycleError) as exc:+ await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ assert "graded version 1" in str(exc.value)+ assert "version 2" in str(exc.value)++ @pytest.mark.asyncio+ async def test_activation_refuses_an_expired_skill(self, session_factory) -> None:+ """Activating an expired skill would be a no-op that looks like a change."""+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml(expires_at="2020-01-01"))+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=uuid.uuid4(),+ candidate_evaluation_id=uuid.uuid4(),+ )+ await db.commit()+ with pytest.raises(store.SkillLifecycleError) as exc:+ await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ assert "expired" in str(exc.value)++ @pytest.mark.asyncio+ async def test_one_evaluation_cannot_be_its_own_baseline(self, session_factory) -> None:+ """A delta of zero by construction would read as a skill that changed nothing."""+ shared = uuid.uuid4()+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await db.commit()+ with pytest.raises(store.SkillLifecycleError) as exc:+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=shared,+ candidate_evaluation_id=shared,+ )+ assert "same evaluation" in str(exc.value)++ @pytest.mark.asyncio+ async def test_activation_stamps_the_version_row_with_the_backtest(self, session_factory) -> None:+ """ "Its backtest report is attached to its activation" is this assertion."""+ baseline, candidate = uuid.uuid4(), uuid.uuid4()+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=baseline,+ candidate_evaluation_id=candidate,+ )+ row = await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ await db.commit()++ assert row.status == ACTIVE+ assert row.activated_at is not None+ version_row = (await store.list_versions(db, TENANT, "finance-batch-powershell"))[0]++ assert version_row.version == 1+ assert version_row.backtest_evaluation_id == candidate+ assert version_row.backtest_baseline_id == baseline+ assert version_row.activated_at is not None++ @pytest.mark.asyncio+ async def test_an_expired_active_skill_is_not_served_to_the_agent(self, session_factory) -> None:+ """Expiry is applied in the query, so a skill stops steering the moment it lapses."""+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=uuid.uuid4(),+ candidate_evaluation_id=uuid.uuid4(),+ )+ await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ await db.commit()++ assert len(await store.resolve_active_skills(db, TENANT)) == 1+ # The same rows, read a day after the expiry.+ later = datetime(2099, 2, 1, tzinfo=UTC)+ assert await store.resolve_active_skills(db, TENANT, now=later) == []++ @pytest.mark.asyncio+ async def test_a_retired_skill_keeps_its_history_and_stops_being_served(self, session_factory) -> None:+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=uuid.uuid4(),+ candidate_evaluation_id=uuid.uuid4(),+ )+ await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ row = await store.retire_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell")+ await db.commit()++ assert row.status == RETIRED+ assert await store.resolve_active_skills(db, TENANT) == []+ history = await store.list_versions(db, TENANT, "finance-batch-powershell")++ assert len(history) == 1+ assert history[0].retired_at is not None+ # Still resolvable, which is the reason retire exists beside delete.+ assert history[0].body["guidance"]+++# ---------------------------------------------------------------------------+# Routes+# ---------------------------------------------------------------------------+++def _app(session_factory, *, user: CurrentUser | None) -> FastAPI:+ app = FastAPI()+ app.include_router(skills_router, prefix="/api/v1")++ async def _db():+ async with session_factory() as session:+ yield session++ # Both, deliberately: ``TenantDBSession`` resolves through+ # ``get_tenant_db`` rather than ``get_db``, so overriding only the latter+ # leaves the console routes reaching for a real Postgres.+ app.dependency_overrides[get_db] = _db+ app.dependency_overrides[get_tenant_db] = _db+ if user is not None:+ app.dependency_overrides[get_current_user] = lambda: user+ return app+++def _console_user() -> CurrentUser:+ return CurrentUser(user_id=USER, tenant_id=TENANT, role="tenant_admin", email="[email protected]", scopes=["*"])+++def _service_token(monkeypatch):+ monkeypatch.setenv("AISOC_AGENTS_SERVICE_TOKEN", SERVICE_TOKEN)++ async def _noop(_db, _tenant):+ return None++ # The route sets the RLS GUC, which SQLite has no notion of.+ monkeypatch.setattr(endpoint_module, "set_rls_context", _noop)+ yield+++class TestRoutes:+ def test_validate_returns_a_readable_failure_rather_than_a_422(self, session_factory) -> None:+ """The editor calls this as the author types.++ An error status on a half-typed document is a failed request in the+ network tab every few seconds, which is why the save route carries the+ 422 and this one does not.+ """+ client = TestClient(_app(session_factory, user=_console_user()))+ response = client.post("/api/v1/tenant-skills/validate", json={"source_yaml": _one_pivot("nope")})+ assert response.status_code == 200+ body = response.json()+ assert body["valid"] is False+ assert "nope" in body["error"]+ assert "process_activity" in body["available_tools"]["builtin"]++ def test_saving_an_invalid_document_is_a_422_with_the_message_verbatim(self, session_factory) -> None:+ client = TestClient(_app(session_factory, user=_console_user()))+ response = client.put("/api/v1/tenant-skills", json={"source_yaml": _one_pivot("nope")})+ assert response.status_code == 422+ assert "nope" in response.json()["detail"]++ def test_save_then_read_then_version_history(self, session_factory) -> None:+ client = TestClient(_app(session_factory, user=_console_user()))+ assert client.put("/api/v1/tenant-skills", json={"source_yaml": _yaml()}).status_code == 200++ listed = client.get("/api/v1/tenant-skills").json()+ assert [s["skill_id"] for s in listed["skills"]] == ["finance-batch-powershell"]+ assert listed["skills"][0]["status"] == "draft"+ assert listed["skills"][0]["expired"] is False++ versions = client.get("/api/v1/tenant-skills/finance-batch-powershell/versions").json()+ assert [v["version"] for v in versions] == [1]+ assert versions[0]["source_yaml"].startswith("id: finance-batch-powershell")++ def test_activating_without_a_backtest_is_a_409_naming_the_reason(self, session_factory) -> None:+ client = TestClient(_app(session_factory, user=_console_user()))+ client.put("/api/v1/tenant-skills", json={"source_yaml": _yaml()})+ response = client.post("/api/v1/tenant-skills/finance-batch-powershell/activate")+ assert response.status_code == 409+ assert "no backtest attached" in response.json()["detail"]++ def test_another_tenants_skill_is_a_404_rather_than_a_read(self, session_factory) -> None:+ client = TestClient(_app(session_factory, user=_console_user()))+ client.put("/api/v1/tenant-skills", json={"source_yaml": _yaml()})++ other = CurrentUser(user_id=uuid.uuid4(), tenant_id=OTHER_TENANT, role="tenant_admin", email="[email protected]", scopes=["*"])+ other_client = TestClient(_app(session_factory, user=other))+ assert other_client.get("/api/v1/tenant-skills/finance-batch-powershell").status_code == 404+ assert other_client.get("/api/v1/tenant-skills").json()["skills"] == []++ def test_the_internal_route_refuses_a_missing_token(self, session_factory, _service_token) -> None:+ client = TestClient(_app(session_factory, user=None))+ response = client.get("/api/v1/tenant-skills/resolved/active", params={"tenant_id": str(TENANT)})+ assert response.status_code == 401++ def test_the_internal_route_refuses_a_valid_console_session(self, session_factory, _service_token) -> None:+ """A session is a credential for the console routes, not for this one.++ The route has exactly one caller, and a route with one caller should+ accept one kind of credential.+ """+ client = TestClient(_app(session_factory, user=_console_user()))+ response = client.get("/api/v1/tenant-skills/resolved/active", params={"tenant_id": str(TENANT)})+ assert response.status_code == 401++ def test_the_internal_route_serves_only_active_unexpired_skills_for_the_named_tenant(self, session_factory, _service_token) -> None:+ console = TestClient(_app(session_factory, user=_console_user()))+ console.put("/api/v1/tenant-skills", json={"source_yaml": _yaml()})+ console.put("/api/v1/tenant-skills", json={"source_yaml": _yaml(skill_id="never-activated")})++ agent = TestClient(_app(session_factory, user=None))+ headers = {"X-AiSOC-Service-Token": SERVICE_TOKEN}+ before = agent.get("/api/v1/tenant-skills/resolved/active", params={"tenant_id": str(TENANT)}, headers=headers)+ assert before.status_code == 200+ # Draft skills steer nothing, so the agent is served none of them.+ assert before.json()["skills"] == []++ _activate(session_factory, "finance-batch-powershell")+ after = agent.get("/api/v1/tenant-skills/resolved/active", params={"tenant_id": str(TENANT)}, headers=headers)+ served = after.json()["skills"]+ assert [s["skill_id"] for s in served] == ["finance-batch-powershell"]+ assert served[0]["version"] == 1+ assert served[0]["body"]["plan"]++ # And nothing at all for a tenant that authored nothing.+ other = agent.get("/api/v1/tenant-skills/resolved/active", params={"tenant_id": str(OTHER_TENANT)}, headers=headers)+ assert other.json()["skills"] == []+++def _activate(session_factory, skill_id: str) -> None:+ """Attach a backtest and activate, outside the route, for route tests.++ The backtest route starts two real replay evaluations against a connector,+ which is a different subject. These tests are about what the *resolved*+ route serves once a skill is active.+ """+ import asyncio++ async def _run() -> None:+ async with session_factory() as db:+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id=skill_id,+ baseline_evaluation_id=uuid.uuid4(),+ candidate_evaluation_id=uuid.uuid4(),+ )+ await store.activate_skill(db, tenant_id=TENANT, skill_id=skill_id, actor_id=USER)+ await db.commit()++ asyncio.run(_run())+++def test_the_expiry_shown_to_the_console_is_computed_not_inferred_from_status() -> None:+ """An active-but-expired skill steers nothing, and the console must say so.++ A console that showed only ``status`` would report the skill as working+ while the resolver silently drops it, which is the exact shape of failure+ an operator cannot diagnose.+ """+ row = TenantSkill(+ tenant_id=TENANT,+ skill_id="lapsed",+ version=1,+ status=ACTIVE,+ name="Lapsed",+ owner="[email protected]",+ expires_at=datetime.now(UTC) - timedelta(days=1),+ body={},+ source_yaml="",+ )+ model = endpoint_module._to_model(row, now=datetime.now(UTC))+ assert model.status == ACTIVE+ assert model.expired is True