Files
AiSOC/scripts/check_executor_arm_count.py
Beenu Arora f61942f309 Lane D: response that finishes — verb breadth 89 → 165, a bounded model step, time gates, and a ticket-sync defect (#1587)
* depth2 Phase 0: kickoff, re-derived baseline and the SIEM-scope decision

Phase 0.1-0.4 of the wave-2 depth plan, which lands here locked beside the
other four plans.

0.2 re-derives every figure the plan captured. All twenty reproduce exactly
except the cloud/identity/SaaS/code condition count, which the plan itself
flagged as approximate: measured 344 against 'about 358'. D1 records why,
and the finding underneath it — no script in the tree implements that
sentence, so every published value of it was hand-counted with a slightly
different product set, and windowed rules contribute zero because they
carry no product field at all. Phase 2.1's gate has to decide that
explicitly.

0.3 captures the baselines, including 'make up-full' — the one the first
depth plan recorded as never captured (its D2). 22 containers on the full
profile; CORE passed 'make smoke' 10 of 10. The baseline host had nine
unrelated containers on it including a foreign Postgres on 5432, and
'make up-full' failed its first bind before the port resolver's overlay
landed. D2 records the sequence and, deliberately, does not claim a defect
from it: the preceding state is not replayable, so it carries a clean-host
reproduction as a follow-up instead.

0.4 is ADR-0015: AiSOC federates to the SIEM rather than replacing it. The
README's 'Not a drop-in SIEM replacement' is now a decided position with its
cost argument — compliance search needs raw-payload retention outside the
8 GB CORE budget and an availability promise this project has no measured
evidence it can keep. Proposed, and nothing in this plan builds from it.

* chore(depth2): Lane D claims migrations 142-145 and ADR 0020

* test(actions): arm-count gate reproduces depth 5.5 at 89 of a 150 floor

The figure had been quoted three ways. A loose grep over live_actions/
also matches reverse_capability= arguments and reports 111; the plan's
declared rule is class-level capability = "..." declarations, which
reports 89. This counts by the declared rule and cross-checks it against
builtins._BUILTIN_ADAPTERS, so a class that declares a capability and is
never registered cannot pad the headline while answering
executor_not_found at dispatch.

Fails on this tree for the stated reason: 89 arms over 39 verbs against
a floor of 150.

* feat(actions): AWS, GCP, GitHub and Slack containment clients

AWS IAM/EC2 over httpx with a hand-written SigV4 rather than boto3,
which is not in this service's dependency set: every method in
aws_security_groups.py degrades to a note saying boto3 is absent, so
the only behaviour that path has ever been observed to have is its own
fallback. Role-session revocation is the documented aws:TokenIssueTime
inline policy the IAM console itself writes, which makes the rollback a
policy delete and the probe a policy read.

GitHub's credential-revocation endpoint is unauthenticated by design and
returns 403 to an authenticated caller, so that one call strips the
Authorization header every other call sends.

Slack answers HTTP 200 with ok:false on a refusal; the client raises on
it, so an executor cannot report 'we asked' as 'it happened'.
admin.users.setInactive does not exist (404) — removal plus
admin.users.assign is the pair that does.

* feat(actions): SaaS and secure-web-gateway containment clients

Salesforce freeze rather than deactivate, because deactivating releases
the licence and breaks record ownership: IsFrozen lives on UserLogin,
not User, so every call resolves through a SOQL lookup first.

Snowflake containment is SQL, and SQL identifiers cannot be bound. The
value is made unrepresentable rather than escaped — this tree already
shipped a denylist that blocked --, /* and ; and never ', so an escaped
name that matches no user would report a clean containment that did
nothing.

Both gateway clients send the vendor's incremental list edit rather than
a read-modify-write, because two concurrent containments against a
shared list lose one entry and the losing action still reports success.

* feat(actions): 62 cloud, SaaS and gateway arms take the count 89 -> 151

Depth 5.5's floor is 150 by the declared rule. Measured by the gate in
the previous commit the tree stood at 89 over 39 verbs; it now reads 151
over 60 verbs across 34 vendors.

Each new verb has a contract declaring what it does when the finding is
wrong, and the conservative answer wins at verb level rather than the
most capable vendor's: revoke_token declares MANUAL_ONLY because GitHub
states a revoked credential cannot be reactivated and a Workspace
application password is gone, even though GCP can re-enable a key --
which has its own verb an operator dispatches deliberately. Declaring
PLATFORM because one vendor can would have given the rollback path a
route back it does not have on the other four.

Verification is a recorded gap, not a claim: every client here has a
real read-back and PostActionVerifier is keyed on ActionType, which
these live-action verbs do not have. That is why none of them is
AUTOMATIC at any confidence -- unverifiable means not autonomous -- and
why the read-backs ship as dispatchable read verbs instead.

dry_run returns before the client factory is reached, so a preview
cannot construct a client at all. The declared _credential_keys stay as
the second layer.

* test(actions): grade all 62 arms, wire the gate, record the verification gap

Three properties per arm, each a defect this tree has already shipped.

Signatures: every arm runs against a create_autospec of its real client,
so a wrong keyword fails in CI rather than raising TypeError on the
first live call. That is how SearchSIEMExecutor (max_results= against a
client taking max_count) and CreateNotableEventExecutor reached
production -- simulation mode never constructs the client, so the only
path the tests exercised was the one that does not call the vendor.

Dry run, graded in both directions: SIMULATED, so no arm reports a
change it did not make, and the factory asserted never to be called, so
no credential a strip list happened to miss can let a preview reach a
production system.

Vendor shapes: recorded payloads replayed through the real clients with
respx, which is what shows an AWS error body surfacing NoSuchEntity, a
Slack ok:false being a refusal rather than a success, and DESCRIBE USER
being read by column name rather than offset.

Five negative controls run and recorded in DEPTH2_PROGRESS.md.

* feat(playbooks): a bounded ask_model step that branches and cannot act

Wave-2 Phase 6.2 adds one step type that asks the model a
multiple-choice question about the evidence and branches on the answer.
Every part of it is a narrowing, because a playbook step the model can
steer in a product that dispatches containment is the shortest path from
a prompt injection to an outage.

The answer set is closed and written by the playbook author; an answer
outside it is invalid. on_invalid is required, so the case that matters
-- the model not deciding -- has a destination the author chose rather
than a fall-through. The answer selects a key in the author's own
branches map, so the model's text never becomes a step id and the worst
an injected instruction achieves is picking a branch the playbook
already contains.

It cannot call a verb, pinned three ways: it is routed through the
control-flow table rather than _HANDLERS (which is where the action
bridge lives), an AST test asserts the module imports nothing that can
dispatch, and a tripwire test makes the model answer with the name of a
containment verb, replaces the bridge with something that fails the test
if called, and watches the step decide nothing.

Five surfaces in sync, held by check_playbook_schema_parity.py: the
engine enum, schemas/playbook.schema.json, packages/types, and the web
editor's step schema registry and its vocabulary test.

* feat(response): time gates on approval, and deadlines that do something

6.3, both halves.

A tenant may declare when automatic response is acceptable: outside
business hours, with nobody on call, or during a change freeze, each
opt-in and each applying from a declared impact floor. The direction is
fixed and asserted over every impact and requirement the matrix emits --
a schedule may only raise AUTOMATIC to ANALYST and returns a decision
that already needs a human untouched. An unreadable on-call state counts
as nobody on call, because the alternative is a failed rota lookup
silently re-enabling containment at three in the morning.

Approval deadlines gain a declared outcome. Until now every approval in
the product behaved identically at its deadline: the action did not
happen and nothing else happened either, which for the step that
isolates a host believed to be exfiltrating is a decision nobody made on
purpose. A step may now declare stay_paused (the existing behaviour,
chosen rather than implied), rollback, or one named limited containment.

The named verb is graded by its own contract through the ordinary
governed path, so a timeout is not a tier promotion: a verb the tenant's
tier would not auto-execute queues here exactly as it would anywhere
else, and the record says executed=false rather than reporting a
containment that did not happen.

The expiry and the declaration are one UPDATE ... RETURNING rather than
two statements. Not tidiness: the declaration lives on a row the expiry
stops being 'waiting', so a separate read afterwards finds nothing and a
read beforehand is a second cross-tenant sweep racing the first. The
tenant-predicate ratchet therefore moves rather than growing.

* fix(itsm): a vendor retry no longer reopens a closed case

6.4 asks for the two-way sync to be verified before anything is built,
and the verification is the finding.

Outbound already works. Driven end to end for the first time -- the
production push_case and push_status_change routes, the production Jira
and ServiceNow connectors, and a mock HTTP server returning recorded
vendor shapes -- a case mints an issue carrying the aisoc-case label the
return leg resolves by, a ServiceNow incident carries its correlation
id, and a status change patches the existing ticket rather than minting
a second one. Five tests, all green on the first run, no change needed.

Inbound had a defect that four correct unit tests could not see, because
each mocks the next layer: the idempotency check was an exact equality,
so a case a human had closed in AiSOC, receiving an ordinary Jira
redelivery of Done -- which maps to the *intermediate* resolved -- was
moved backwards out of its terminal state. No unusual sequence was
needed, only a close followed by a retry, and Jira retries up to five
times while ServiceNow retries until it gets a 2xx.

The guard is scoped to terminal states only. An ITSM moving a ticket
from Resolved back to In Progress is a real transition this product
should mirror; only at closed is a retry indistinguishable from a
reopen, and there a case that stays closed is visible and correctable
while one silently reopened by a retry is neither.

* feat(ai): AI-estate containment arms and an approved kill-switch playbook

7.5. The inventory could score a provider key's exposure and nothing
could act on it, so a key found in a public repository was a finding
with a recommendation and no verb. 165 arms over 64 verbs now, up from
151.

The three providers give three different answers to 'can this be
undone', and the arms carry each honestly: OpenAI deletes a project key
so that arm declares no rollback, Anthropic deactivates one so it has a
real reverse and is the reason restore_token exists as a verb, and a
gateway block is a documented pair. One revoke_token contract claiming a
platform rollback because Anthropic can would have given the rollback
path a route back it does not have on the other two.

Two things this deliberately did not add, recorded rather than
duplicated. AI OAuth grant revocation reuses the Workspace, Entra and
Okta arms from 6.1, because an AI application's grant is an ordinary
consent and a fourth arm would be a second code path to the same vendor
endpoint. Agent process kill reuses the EDR arms, because the agent is a
process on a host. And neither OpenAI's nor Anthropic's public admin API
exposes a budget this platform can set, so set_spend_cap has exactly one
vendor arm and a test says so.

The kill-switch playbook ships disabled, asks the bounded model question
before the approval rather than after it, and the approval declares its
timeout outcome: if nobody answers in two hours the gateway key's spend
cap goes to zero, which is the narrow containment rather than the wide
one.

* docs(depth2): record 6.1-6.4 and 7.5, with the two gaps that stay open

Matrix moves 335 -> 340 rows, 330 -> 335 GATED, in lockstep across the
matrix Summary, ROADMAP.md and the evidence pack.

Two deviations recorded rather than papered over. Depth 5.6's 'preview
against a chosen past alert' is still open: the drafter exists and lands
a disabled draft, but nothing resolves a historical alert into a trigger
context, which is the console's alert reader rather than the playbook
engine. And the 24 new verbs carry a recorded verification gap rather
than a probe, because PostActionVerifier is keyed on ActionType and
these are live-action capabilities -- the same gap unisolate_host has
carried since it was built. The consequence is enforced: a test asserts
no new verb above read_only is AUTOMATIC.

* test(playbooks): record the kill switch as outside the benchmark corpus

The completion-rate gate requires every shipped playbook to match an
incident in the 200-case corpus, and the AI-agent kill switch matches
nothing because the corpus contains no AI-estate template at all.

Two wrong fixes were available and both were refused. Tagging it
supply-chain so it matched github-pat-leak is the 'matches by tag only'
case the gate's own docstring says it exists to prevent -- blocking a
gateway key does nothing about a leaked GitHub PAT. Adding a template to
the corpus moves a published measurement.

So: one entry in the existing not-in-benchmark list with its reason, the
category gate's exemption derived from that list rather than kept as a
second hand-written one, and a ratchet that re-runs the evaluation with
the exemption emptied and fails if an entry would no longer be an
orphan. The ratchet uses the evaluator's own definition of orphan rather
than a second predicate, because a ratchet with its own idea of
'covered' is one that drifts.

* chore(marketplace): regenerate the index for the kill-switch playbook

Generated, not hand-edited: the gate compares the three on-disk copies
against the generator's output and the new pack entry moved the playbook
count from 88 to 89.

* fix(gates): RLS shape on migration 142, and guard the AWS XML parse at source

Two CI findings, both real.

The RLS policy-shape gate requires FORCE (an owner walks past a policy
that is only ENABLEd) and an 'OR current_tenant_id() IS NULL' arm. The
arm matters here specifically: the sweep that fires an approval deadline
runs on a connection that binds no tenant, by design, and without it
that sweep reads zero rows and reports success -- the silent failure the
table exists to prevent.

Semgrep's use-defused-xml fired on the AWS client's ElementTree import,
taking the error ratchet from 44 to 45. The ceiling was not raised. AWS
query APIs answer in XML and IAM has no JSON alternative, so the parse
has to happen; what makes it safe is refusing a document-type or entity
declaration on the raw text before a parser sees it, plus a size bound,
rather than trusting a parser's defaults to be what a reader assumes.
Checked on the raw text because a parser that has already expanded an
entity cannot tell you it did. Re-measured locally at 112 total / 44
error, which is the ceiling unchanged.

* depth2 Lane E: AI provider coverage, chat-compliance minimisation, hosted agents, repository AI config and four replayed AI rules (#1585)

* depth2 Lane E: claim migrations 146-150 and ADR 0021

* test(connectors): reproduce the AI provider-coverage gap in llm_usage

Depth 6.3 / wave-2 7.1. `LlmUsageConnector` accepted `openai` and
`anthropic` and nothing else, so Gemini in Workspace, Copilot in M365,
Copilot in GitHub and Entra consent grants to AI applications had no
reader at all and the AI estate's provider-audit discovery source could
only ever see two vendors.

Six of the seven tests fail on this tree: four drive the real HTTP path
against a mock server returning vendor-shaped payloads and get a
ValueError from the constructor, one asserts the org-scoping refusal and
one asserts the schema's select options match the accepted providers
(`PROVIDERS` does not exist yet).

Endpoints, query parameters and event names come from the vendors'
current public references, each fetched and 200 before being written:
the Admin SDK Reports API `gemini_in_workspace_apps` application, the
GitHub organization audit log, the Office 365 Management Activity API
schema (RecordType 261 CopilotInteraction, 284 AIAppInteraction) and
Microsoft Graph directoryAudits.

* feat(connectors): four more AI provider audit feeds in llm_usage

Depth 6.3 / wave-2 7.1. Closes the gap the previous commit reproduced:
the connector now reads Gemini in Workspace, GitHub Copilot, Microsoft
365 Copilot and Entra consent grants alongside OpenAI and Anthropic.

Each client was written against the vendor's current public reference,
every one of which was fetched and returned 200 before being committed;
the module docstring names them per provider. The Workspace
`gemini_in_workspace_apps` applicationName and the `ai_usage_event` /
`feature_utilization` event names, the 23 published `copilot.*` audit
actions, RecordType 261 CopilotInteraction and 284 AIAppInteraction, and
the directoryAudits consent activities are all read values, not
inferred ones.

Three things the tests pin beyond "it parses":

- Filtering happens server-side where the vendor supports it. Asking
  GitHub for an organisation's whole audit stream and discarding
  client-side is a rate-budget problem on a busy org, not a style one.
- Where it cannot, the reader discards non-AI records by RecordType and
  by consent activity name. `Audit.General` is the entire Microsoft 365
  general audit and `directoryAudits` is every directory change; a
  reader that forwarded both would replace the AI feed with a second
  copy of the general audit.
- A consent grant's scopes are lifted out of the free-text
  `ConsentAction.Permissions` property into a sorted `scopes` list on
  the envelope. A grant whose scopes stay buried scores in the AI estate
  as a grant with no scope at all, which is the opposite of the truth
  for `Mail.Read`.

M365 needs a second request because the subscription endpoint returns
blob references rather than content; a reader that stopped at the first
response would poll successfully forever and emit nothing.

Workspace OAuth token grants are deliberately not read here —
`google_workspace` already polls the `token` application, and a second
reader would double-count every grant. What is missing there is
classification, which is the next commit.

Docs and the conformance matrix regenerated, not hand-edited.

* test(fusion): reproduce the recorder reading a path no connector emits

Wave-2 7.1 wiring. `test_ai_asset_recorder.py` writes
`finding.evidence.scopes` into a hand-built OCSF event and asserts the
recorder reads `finding.evidence.scopes`. Both halves are the test's own
invention: no connector in the tree produces that path and ingest does
not synthesise it, so the assertion holds whether or not the production
path works.

What ingest really hands fusion is the connector's normalized dict as a
JSON string under `ocsf["raw_data"]`, which is why `_connector_fields`
exists for the endpoint path and is not used by the provider-audit path.

Driven through that real shape, both new tests fail: an Entra consent
grant reaches the inventory with no scopes at all, so an AI notetaker
consented into every mailbox in the organisation scores identically to
one granted nothing, and the console's reason list is silent about the
single fact that decides whether the grant matters.

The fixtures are the real output of `LlmUsageConnector.normalize()`.
The two services cannot import each other — both package their
application as `app` — so they are held together by a committed
artefact plus a check in each direction, the way the vendored narrative
and the detection ruleset already are.

* fix(fusion): read provider-audit fields where the connector puts them

Wave-2 7.1 wiring. `_from_provider_audit` now reads through
`_connector_fields`, the same reconstruction the endpoint path already
performs, instead of off the canonical OCSF map. An Entra consent
grant's scope list reaches `score_risk`, so a grant holding `Mail.Read`
scores as broad and says so in its reason list.

Two further corrections the real shape forced:

- An OAuth grant is keyed on the **application**, not the audit record.
  Keying on the record id would make every re-consent a new asset and
  reset `first_seen_at` on each, so the inventory would grow a row per
  event and never show that this application has been there since May.
- The OCSF-native `finding.evidence.scopes` read is kept as a fallback
  rather than replaced, so a producer that does emit it is still read.
  Trading one blind spot for another is not a fix.

Negative control, recorded: with the `fields.get("scopes")` read
reverted to the pre-fix path and nothing else changed, both new tests
fail again (`KeyError: 'scopes'`). Restored, the fusion suite is 1063
passed / 28 skipped.

The `normalize` contract is unchanged across all 87 connectors: the
"is this record AI activity at all" decision is a separate
`is_ai_record` predicate rather than a `None` return, which keeps the
base signature intact and makes the filter — the thing that stops the
Microsoft 365 AI feed becoming a second copy of the general audit —
callable and testable on its own.

* feat(api): enterprise AI-chat compliance logs, minimised by the schema

Wave-2 7.1, second half. Reads an AI provider's compliance API for the
directory, projects and activity feed, and — behind a second, narrower
opt-in — classifies message content without keeping any of it.

Written against Anthropic's Compliance API, the one enterprise AI-chat
compliance surface with a complete public reference. Every path, scope,
key prefix and response field was read from pages that each returned 200
before being committed; the client's module docstring names them. The
Activity Feed record and the chat record in the tests are the vendor's
published examples field for field.

The minimisation is in the schema, which is the point of ADR-0021.
A plan sentence saying "never full conversations" that a TEXT column
permits is not a control; it holds until the first caller who binds
"\n".join(messages) and succeeds silently.

- No table has a column able to hold a message. Asserted against the
  ORM, since that is what application code binds through.
- The snippet is VARCHAR(280). The collector truncates; the column is
  the backstop for the caller that forgets.
- The snippet is masked BEFORE it is cut, so a row saying "this chat
  contained an AWS key" does not contain the key. A verbatim window
  would create a new copy of the secret in a table an operator believes
  is safe to keep, and label it so an attacker can find it. A
  per-pattern sweep asserts the value is absent for every shape in the
  shared list.
- The label vocabulary is a CHECK constraint, and a test asserts the
  three copies of it (constraint, ORM, classifier) agree.
- The client has no method returning message text, asserted on its
  public surface.
- Two opt-ins, stricter one default-off: collection does not imply
  reading message bodies.
- Off by default per tenant, through the console, vault-held key. No
  environment variable. A vault failure is a 503, never a plaintext row.

The secret-shape patterns are the AI SDK's own, vendored by
scripts/sync_vendored_ai_redaction.py and held byte-identical by its
--check. A prompt and a chat message containing the same AWS key must
produce the same shape name on both surfaces; a second hand-written
copy is how two surfaces come to disagree about the same rows. The SDK
groups e-mail and card shapes with credentials because it is answering
a transmission question; _SDK_LABEL maps each shape to one of the
plan's four classes rather than relabelling the shared list.

Luhn is applied to the shared card shape. Without it the digits-only
pattern labels order ids as payment data, and a classifier that labels
everything is one nobody believes.

Retention, legal hold and erasure come free and are tested: every table
carries a column named exactly `tenant_id`, which is how
`discover_tenant_tables` finds it. Discovery rather than a declared
list is deliberate — a list is the thing that goes stale.

Tests use httpx.MockTransport rather than respx, because respx is not
in this service's locked dependency set and a test needing a package CI
does not install is a test CI cannot run. MockTransport replaces only
the network leg.

Negative control, recorded: adding a `transcript: Mapped[str | None]
= mapped_column(Text)` to AiChatContentLabel and changing nothing else
fails two tests (the forbidden-column sweep and the unbounded-TEXT
sweep). Removed, the API suite is 5074 passed / 174 skipped.

Migration 146 and ADR-0021 were claimed in DEPTH2_PROGRESS.md before
either file was written.

* docs(depth2): record 7.1 in the progress tracker

* feat(ai-estate): hosted agents and repository AI config as asset kinds

Wave-2 7.2. Two new kinds on `aisoc_ai_assets` (migration 147), both
scored by the one existing `score_risk` and rendered with their reasons
on the AI estate page. No second scorer: the plan forbids it by name and
it is the drift this repository keeps finding.

**Hosted agents** come from `GET /v1/agents` with the
`managed-agents-2026-04-01` beta header, read against the vendor's
published reference (fetched, 200). An agent configured in a provider's
control plane is invisible to every other discovery path here: endpoint
telemetry never sees it, and gateway telemetry sees its traffic without
knowing what it was configured to do. The client is read-only — the
vendor offers create, update and archive and none of them is here,
because an inventory that can reconfigure a customer's agents is a
different risk conversation and 7.2 is read-only by the plan's rule.

**Repository AI config** is the scan of agent-instruction files, skill
directories and MCP configuration through the code-platform connectors,
recording the tools and servers each references. "Which repositories
point an agent at this MCP server" is a question the estate could not
answer.

Every byte of that scan is attacker-controlled and is treated as such.
These files are checked in, editable by anyone who can land a pull
request, and read by an agent verbatim as instructions — the same trust
class as a retrieved runbook, which this platform already scans. So:

- Nothing is stored raw. Excerpts are flattened and capped at 400
  characters, with zero-width and bidirectional characters stripped,
  because an instruction file is exactly where a payload invisible in a
  diff gets hidden.
- The content is scanned at capture and only the matched *pattern
  names* are kept — never the matching text, which would put the
  attacker's payload in a table the console renders, labelled so a
  security team looks at it.
- Those names reach `score_risk`, so a flagged file raises the asset's
  exposure and the reason names the channel.
- A hosted agent's `system` prompt goes through the identical path, for
  the identical reason.

The patterns are **generated** from the agents guard's own `_RULES`
table rather than hand-picked, by
scripts/sync_vendored_ai_instruction_rules.py with a --check wired into
ci.yml. A hand-copied subset drifts: a pattern added to the guard after
the next incident would never reach the scanner and nothing would say
so. One rule is excluded with its reason recorded — `fabricated_tool_result`
matches a model-output envelope rather than a repository file, and its
pattern is assembled from a set, so it renders in a different order in
every process and no generated file could match itself. The generator
fails if an excluded name leaves the guard, so the exclusion cannot
outlive the rule and become a silent gap.

Two things found while building it:

- `path.lstrip("./")` eats the leading dot of a dotfolder, so
  `.cursor/rules/x.mdc` became `cursor/rules/x.mdc` and stopped
  matching — silently, as a path that simply is not an AI artefact.
  Every convention here lives in a dotfolder, so that one call would
  have turned most of the scan off. Caught by the classification table,
  which is why it enumerates real paths rather than a couple of
  examples.
- `DEVICELESS_KINDS` is shared between the model and `score_risk`, so
  the four kinds that cannot have a device are not charged for lacking
  one. A hosted agent has no laptop to isolate; the reason string
  "containment has nowhere to act" would simply be false.

The tool reader matches grants, not prose: "do not use `write_file`" in
a paragraph is not a grant, and counting it would make a careful
instruction file score worse than a careless one.

Also: a committed JWT-shaped literal in the 7.1 classifier test is now
assembled from parts. The repository's secret scan was right to refuse
it, and a test fixture has no business looking like a credential.

* docs(depth2): record 7.2 in the progress tracker

* feat(detections): four AI rules on the provider feeds 7.1 added

Wave-2 7.4, partial — four of the rule pack's targets, each earned
rather than declared. Executable corpus 2,530 -> 2,534, regenerated
from `scripts/project_stats.py` and propagated to the README, ROADMAP,
truth table, corpus stats, marketplace index and the packaged API copy
by their own generators. Nothing was hand-typed.

- `llm-copilot-content-exclusion-changed` (critical) — content
  exclusion is the control that stops a coding assistant reading the
  paths an organisation declared off limits. It is changed in a
  settings page rather than in a pull request, so nothing else reviews
  it.
- `llm-copilot-agent-mcp-config-changed` (high) — adding an MCP server
  adds a party that can instruct a hosted agent. A scope change, not a
  settings change, and the agent runs on the provider's infrastructure
  so no endpoint control sees the result.
- `llm-ai-app-granted-write-scope` (high) — a consent grant letting an
  AI application change a mailbox, drive, site or the directory. The
  read equivalent is an exposure; this one can act.
- `llm-copilot-bulk-resource-access` (medium) — one assistant turn that
  read 25 or more distinct resources. An assistant with a user's grant
  is an exfiltration path that authenticates as that user and looks
  like ordinary application traffic.

Every rule is replayed through the REAL connector and the REAL engine
in `services/fusion/tests/test_ai_rule_pack_replay.py`. The fixtures
are the committed output of `LlmUsageConnector.normalize()` on
vendor-shaped records, regenerated and drift-checked from the
connectors side, because the two services cannot import each other.

Nothing here is synthesized from the rule it tests. That is the whole
point: 1 of 12 GitHub rules fired on real connector output while all
twelve passed their own fixture replay, because a fixture generated
from a rule carries the rule's own clause key and the replay is
tautological.

Each negative twin differs in exactly ONE decisive field — a different
Copilot action, `Mail.Read` where the twin is `Mail.ReadWrite`, 24
resources where the twin is 40 — and a test asserts that property on
the fixtures rather than trusting it, since a negative that also moved
the actor would pass for a reason unrelated to the clause.

Negative control, recorded: rewriting one rule's clause to the
unprefixed vendor action (`event_type: content_exclusion_changed`),
which is the exact shape of the measured GitHub failure, and
re-exporting, fails that rule's positive replay while the other three
stay green. Restored, all ten pass.

`test_builtin_rule_catalogue.py`'s hand-typed counts moved 760 -> 764
and 2609 -> 2613 with the reason recorded beside the existing history,
in the style that file already keeps.

* docs(depth2): record 7.4 partial and 7.3 not delivered, with evidence

* chore(detections): regenerate the curated index for the four new rules

`curate_detections.py --check` is a drift gate I had not run: adding four
rules moves the curated selection and the coverage page, and neither is
produced by any of the seven generators I did regenerate. Caught by CI,
reproduced locally with the same command, and regenerated rather than
hand-edited.

Worth recording because it is the shape this repository keeps finding: a
published artefact with its own generator and its own `--check`, sitting
outside the chain everything else in the family runs through. All eight
detection drift gates now pass together.

* fix(ci): correct the gitleaks fingerprints the four new rules shifted

`.gitleaksignore` pins a finding by `file:rule:line`, so inserting four
entries into `detections/rule-ids.lock.json` moved every line below them
and five fingerprints stopped matching the findings they were triaged
for. The file's own header describes this rot and says the fix is to
correct the line number, never to drop the entry or relax the job, so
that is what this does: the set is re-derived by running CI's exact
gitleaks 8.21.2 with the allow-list removed, and all fourteen are
written back.

Thirteen are the same pre-existing, benign findings — the heuristic
fires on rule *slugs* such as `llm-api-key-created` and
`slack-token-exposed`, never on a value. One is genuinely new:
`llm-copilot-bulk-resource-access` trips it on the word "access".

Verified under 8.21.2 rather than the 8.30.1 on this machine, because
the two disagree about this tree and only the pinned one decides.

Also regenerates `apps/web/public/marketplace/{index,curated}.json`
through `pnpm marketplace:sync`. `curate_detections.py --check` passing
is not the whole gate: the web mirror is copied by a separate step, and
a curated index that is current in one place and stale in the other is
the drift that check exists to catch.

* fix(depth2): three real defects behind lane D's red checks

**Playbook editor types.** `ask_model` claimed an integration bucket
`Decision` that `INTEGRATION_TYPES` does not declare, and three of its field
descriptors used `list` and `text` where the vocabulary is `string_list` and
`string`. Not cosmetic: `SchemaForm` renders by `FieldKind`, so the two list
fields and the fallback-branch field would not have rendered. `ask_model`
now sits in `AI Analysis` beside `investigate` and `enrich`, which is the
integration it actually reaches.

**A retired rule credited to the wrong vendor.** check_enrichment_decisions
reported `ident-github-pat-classic-created-with-broad-scopes` as working
again. It is not: the rule reads `scopes`, which reaches the namespace from
`llm_usage.py`, and GitHub's connector emits no such field -- as its refusal
says, no GitHub audit entry carries a created token's scopes.

The gate's namespace was a flat union of every connector's field names, so
one vendor introducing a field name silently un-retires another vendor's
rule. It now resolves a retired rule's fields against the connector its own
`log_source.product` names, falling back to the union where the product
names no module (`windows`, `waf`) so nothing that was checked stops being
checked. Scoping makes the check fire *less* often, so the self-test gains
the control for it -- a retired rule whose own product's connector supplies
every field is still caught -- alongside the existing
`application/user-agent-known-tool` case, which still fires.

**Two CodeQL error-severity alerts and nine notes.** The
`py/non-iterable-in-for-loop` pair is a false positive: CodeQL does not
resolve `EnumMeta.__iter__` through the `(str, Enum)` form, and both enums
iterate at runtime (6 and 4 members, measured). Materialised with `list()`
so the analysis sees what the interpreter does, rather than suppressed. The
nine `py/unnecessary-lambda` notes were real -- `lambda: object()` is
`object` -- and are now the callable itself.

Verified: agents test_ask_model_step 33 passed, actions test_response_schedule
21 passed, apps/web type-check clean, enrichment-decision gate and self-test
both OK.

* chore(depth2): regenerate corpus-stats after the main merge

Generated artefact, stale against the merged corpus. Regenerated, not
hand-edited; its self-test passes again.

* fix(agents): vendor the AI kill-switch playbook into the image build context

The agents image cannot COPY outside its build context, so a playbook that
is only in `playbooks/packs/v1` is a playbook no deployment has. 7.5's
`ai-agent-kill-switch` was authored there and never copied across, which
would have shipped an AI-containment response the runtime could not load.
Copied by the sync script; 64 playbooks, byte-identical.

* fix(agents): put ask_model's system prompt through the registry

5.4's bounded model step sent a 604-character system prompt written inline,
so it shipped with no version, no lock entry and no eval re-grade on the
next edit -- and this is the prompt that decides which branch a playbook run
takes next, which is exactly what the lock exists to make visible.

Registered as `playbook.ask_model.system` v1 with the text unchanged, read
back with `prompt_text()` at the call site. The name is a literal rather
than a constant because the gate reads it there: a pin nothing can be seen
to ask for is the appearance of coverage. Lock regenerated; 23 prompts
pinned, each with a reader. 33 ask_model tests still pass.

* style: ruff format

* fix(agents): defer the prompt-registry import in ask_model

Registering the prompt put `from app.llm.prompt_registry import prompt_text`
at module scope, which drags langchain_core into the playbook engine's
import chain. The schema-parity gate installs only httpx and pydantic and
refused to grade -- "could not import the playbook engine ... or the gate is
grading nothing" -- which is the gate being right: a heavy import at module
scope is how one service's dependency takes an unrelated job down.

Moved beside the `safe_ainvoke` import already deferred in the same block
for the same reason, with the same documented noqa. ask_model's module-scope
imports are stdlib and `.bounds` again.

* ci: wire the executor arm-count gate into the build

check_gate_coverage caught it: a check with a findings-exit and a verdict
flag that no workflow reaches. It is the gate behind wave-2 6.1's headline
— 165 arms over 64 verbs against a floor of 150 — so unwired, the figure
had nothing holding it. Runs beside the action-contract gate it belongs
with. 185 of 185 gates reachable.

* test: join the stub vendor's request threads before the suite exits

`One approval, one vendor call, or an honest unknown` went red with 27 of
27 tests passing above it: `ThreadingHTTPServer` defaults to
`daemon_threads = True`, so `server_close()` returned while a handler was
still inside `handle()`, and the process aborted at interpreter shutdown —
"could not acquire lock for <stderr> ... possibly due to daemon threads",
exit 134.

Intermittent, and red for nothing when it fires. Non-daemon request threads
make `server_close()` join them; `shutdown()` has already stopped the
accept loop, so the only wait is for requests in flight against a local
stub.
2026-11-01 17:41:03 -08:00

219 lines
8.5 KiB
Python

#!/usr/bin/env python3
"""Gate: count the response arms the actions service actually registers.
Depth 5.5 (carried to wave-2 Phase 6.1) sets a floor on executor arms and
names the counting rule, because the number had already been quoted three
ways. A loose grep over ``services/actions/app/live_actions/`` also matches
``reverse_capability=`` arguments and reports 111; the declared rule is
class-level ``capability = "..."`` declarations, which reports 89. Quoting
the larger figure would publish 22 arms that do not exist.
So this counts twice and makes the two agree:
``declared``
An ``ast`` walk for class-level ``capability = "<literal>"`` under
``services/actions/app/live_actions/``. This is the plan's rule, kept
so the published figure stays comparable with the baseline it is
measured against. It never imports, so it cannot be fooled by an
import-time side effect.
``registered``
The adapters in ``builtins._BUILTIN_ADAPTERS``, which is what
``register_builtin_executors()`` puts in the registry and therefore what
a dispatch can actually reach.
A class that declares a capability and is never registered answers
``executor_not_found`` at dispatch while counting towards the headline — the
exact shape of padding this gate exists to refuse — so the two sets must be
identical, not merely the same size.
The artefact is generated, never hand-edited: ``--write`` regenerates
``docs/audit/executor-arms.json`` and ``--check`` fails when the committed
file disagrees with the tree.
Run: python3 scripts/check_executor_arm_count.py --check
python3 scripts/check_executor_arm_count.py --write
"""
from __future__ import annotations
import argparse
import ast
import json
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
self_test_if_requested(__file__)
REPO_ROOT = repo_root()
LIVE_ACTIONS = REPO_ROOT / "services" / "actions" / "app" / "live_actions"
ARTEFACT = REPO_ROOT / "docs" / "audit" / "executor-arms.json"
#: The floor wave-2 Phase 6.1 sets, which is depth 5.5's floor. A floor is
#: only a gate while it is above the tree; this one was 89 when it was
#: written, which is the measurement that made the phase necessary.
REQUIRED_ARMS = 150
def declared_arms() -> list[tuple[str, str, str]]:
"""``(module, class, capability)`` for every class-level declaration.
Pure source analysis, matching the plan's counting rule exactly. A
``capability`` assigned anything but a non-empty string literal is not a
declaration — ``capability: str = ""`` on the base class is the shape
that would otherwise inflate the count by one per abstract class.
"""
found: list[tuple[str, str, str]] = []
for path in sorted(LIVE_ACTIONS.glob("*.py")):
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
for node in ast.walk(tree):
if not isinstance(node, ast.ClassDef):
continue
for stmt in node.body:
if not isinstance(stmt, ast.Assign) or len(stmt.targets) != 1:
continue
target = stmt.targets[0]
if not isinstance(target, ast.Name) or target.id != "capability":
continue
value = stmt.value
if isinstance(value, ast.Constant) and isinstance(value.value, str) and value.value:
found.append((path.stem, node.name, value.value))
return sorted(found)
def registered_arms() -> list[dict[str, str]]:
"""``vendor_id``/``capability`` for every adapter the registry gets.
Imports the actions service the way ``check_action_contract.py`` does.
Eight adapters take their ``vendor_id`` from a module constant rather
than a literal, so this is the only honest way to read the vendor —
which is also why the artefact is written from here and the ``ast`` walk
only supplies the count.
"""
sys.path.insert(0, str(REPO_ROOT / "services" / "actions"))
from app.live_actions.builtins import _BUILTIN_ADAPTERS # noqa: PLC0415 — needs the sys.path edit above
return sorted(
(
{
"module": cls.__module__.rsplit(".", 1)[-1],
"class": cls.__name__,
"vendor_id": str(cls.vendor_id),
"capability": str(cls.capability),
}
for cls in _BUILTIN_ADAPTERS
),
key=lambda row: (row["capability"], row["vendor_id"], row["class"]),
)
def build() -> dict:
arms = registered_arms()
return {
"_comment": ("Generated by scripts/check_executor_arm_count.py --write. Do not hand-edit; regenerate."),
"counting_rule": (
'Class-level `capability = "..."` declarations under '
"services/actions/app/live_actions/, cross-checked against "
"builtins._BUILTIN_ADAPTERS."
),
"arms": len(arms),
"verbs": len({row["capability"] for row in arms}),
"vendors": len({row["vendor_id"] for row in arms}),
"required_minimum": REQUIRED_ARMS,
"by_capability": {
capability: sorted(row["vendor_id"] for row in arms if row["capability"] == capability)
for capability in sorted({row["capability"] for row in arms})
},
"registry": arms,
}
def problems() -> list[str]:
errors: list[str] = []
declared = declared_arms()
registered = registered_arms()
if not declared:
return [
f"no capability declarations found under {LIVE_ACTIONS}. A gate that "
f"scans nothing reports the same word as a gate that found nothing, "
f"so this refuses rather than passing."
]
declared_classes = {(module, cls) for module, cls, _ in declared}
registered_classes = {(row["module"], row["class"]) for row in registered}
for module, cls in sorted(declared_classes - registered_classes):
errors.append(
f"{module}.{cls} declares a capability and is not in "
f"_BUILTIN_ADAPTERS, so it counts towards the arm total and "
f"answers executor_not_found at dispatch. Register it or stop "
f"declaring it."
)
for module, cls in sorted(registered_classes - declared_classes):
errors.append(
f"{module}.{cls} is registered but declares no class-level "
f"capability literal, so the declared-rule count cannot see it "
f"and the published figure is lower than the surface."
)
if len(declared) < REQUIRED_ARMS:
errors.append(
f"{len(declared)} executor arms over {len({c for _, _, c in declared})} "
f"verbs; the plan's floor is {REQUIRED_ARMS}. Counted by the declared "
f'rule (class-level `capability = "..."`), not the looser grep that '
f"also matches reverse_capability arguments."
)
if ARTEFACT.is_file():
committed = json.loads(ARTEFACT.read_text(encoding="utf-8"))
if committed != build():
errors.append(
f"{ARTEFACT.relative_to(REPO_ROOT)} disagrees with the tree. "
f"Regenerate it with --write; never hand-edit a generated figure."
)
else:
errors.append(f"{ARTEFACT.relative_to(REPO_ROOT)} is missing. Generate it with --write.")
return errors
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="fail when the tree disagrees with the artefact or the floor")
parser.add_argument("--write", action="store_true", help="regenerate the artefact from the tree")
args = parser.parse_args()
if args.write:
ARTEFACT.parent.mkdir(parents=True, exist_ok=True)
ARTEFACT.write_text(json.dumps(build(), indent=2) + "\n", encoding="utf-8")
payload = build()
print(
f"wrote {ARTEFACT.relative_to(REPO_ROOT)}: {payload['arms']} arms over {payload['verbs']} verbs, {payload['vendors']} vendors"
)
return 0
errors = problems()
if errors:
print("executor-arm-count: FAIL\n", file=sys.stderr)
for error in errors:
print(f" {error}", file=sys.stderr)
print("", file=sys.stderr)
return 1
payload = build()
print(
f"executor-arm-count: OK — {payload['arms']} arms over "
f"{payload['verbs']} verbs across {payload['vendors']} vendors "
f"(floor {REQUIRED_ARMS})"
)
return 0
if __name__ == "__main__":
sys.exit(main())