stacktrace-cli 0.18.1__py3-none-any.whl → 0.19.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. stacktrace/__init__.py +1 -1
  2. stacktrace/analysis.py +9 -2
  3. stacktrace/cloud/boot.py +160 -21
  4. stacktrace/correlate/acquire.py +59 -64
  5. stacktrace/correlate/composition.py +13 -0
  6. stacktrace/correlate/orchestrate.py +11 -4
  7. stacktrace/daemon/db.py +149 -19
  8. stacktrace/daemon/gateway.py +1 -4
  9. stacktrace/daemon/gateway_policy.py +6 -1
  10. stacktrace/daemon/inline_hook.py +354 -93
  11. stacktrace/daemon/observer.py +306 -43
  12. stacktrace/daemon/policy_collect.py +68 -17
  13. stacktrace/daemon/policy_inputs.py +2 -1
  14. stacktrace/daemon/policy_runtime.py +217 -67
  15. stacktrace/daemon/runtime.py +28 -17
  16. stacktrace/daemon/scan.py +11 -0
  17. stacktrace/daemon/server.py +8 -0
  18. stacktrace/daemon/store.py +212 -28
  19. stacktrace/detector/deterministic.py +157 -11
  20. stacktrace/detector/inline.py +41 -7
  21. stacktrace/detector/rules.py +51 -11
  22. stacktrace/detector/run.py +15 -3
  23. stacktrace/gateway/analyzer.py +151 -53
  24. stacktrace/gateway/marker.py +729 -0
  25. stacktrace/gateway/service.py +13 -2
  26. stacktrace/gateway/sink.py +9 -0
  27. stacktrace/hooks/claude.py +41 -9
  28. stacktrace/hooks/codex.py +57 -17
  29. stacktrace/hooks/cursor.py +30 -15
  30. stacktrace/hooks/devin.py +122 -0
  31. stacktrace/hooks/session.py +60 -9
  32. stacktrace/remote/cli.py +4 -0
  33. stacktrace/remote/detect_payload.py +8 -2
  34. stacktrace/remote/hook_policy.py +21 -1
  35. stacktrace/remote/policy_service.py +27 -0
  36. {stacktrace_cli-0.18.1.dist-info → stacktrace_cli-0.19.1.dist-info}/METADATA +4 -4
  37. {stacktrace_cli-0.18.1.dist-info → stacktrace_cli-0.19.1.dist-info}/RECORD +39 -37
  38. {stacktrace_cli-0.18.1.dist-info → stacktrace_cli-0.19.1.dist-info}/WHEEL +0 -0
  39. {stacktrace_cli-0.18.1.dist-info → stacktrace_cli-0.19.1.dist-info}/entry_points.txt +0 -0
stacktrace/__init__.py CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  import logging as _logging
4
4
 
5
- __version__ = "0.18.1"
5
+ __version__ = "0.19.1"
6
6
 
7
7
  # Only the daemon attaches a handler (ADR-0048). Without this one, a WARNING
8
8
  # logged in any other process would reach Python's last-resort handler and
stacktrace/analysis.py CHANGED
@@ -20,7 +20,7 @@ path's tests already pin.
20
20
  from __future__ import annotations
21
21
 
22
22
  import re
23
- from collections.abc import Iterator
23
+ from collections.abc import Iterator, Mapping
24
24
  from dataclasses import dataclass, replace
25
25
  from datetime import UTC, datetime, timedelta
26
26
  from pathlib import Path
@@ -245,8 +245,12 @@ def analyse_sessions(
245
245
  analyzer: str = NO_ANALYZER,
246
246
  jev_key: str | None = None,
247
247
  history: DriftHistory | None = None,
248
+ gate_conditions: Mapping[str, object] | None = None,
248
249
  ) -> Analysis:
249
- """Correlate and judge a session view already collected by a long-lived reader."""
250
+ """Correlate and judge a session view already collected by a long-lived reader.
251
+
252
+ `gate_conditions` travels to `run_detector` unchanged.
253
+ """
250
254
  window_end = datetime.now(UTC)
251
255
  window_start = since if isinstance(since, datetime) else parse_since(since)
252
256
  return _analyse_sessions(
@@ -264,6 +268,7 @@ def analyse_sessions(
264
268
  analyzer=analyzer,
265
269
  jev_key=jev_key,
266
270
  history=history,
271
+ gate_conditions=gate_conditions,
267
272
  )
268
273
 
269
274
 
@@ -283,6 +288,7 @@ def _analyse_sessions(
283
288
  analyzer: str,
284
289
  jev_key: str | None,
285
290
  history: DriftHistory | None,
291
+ gate_conditions: Mapping[str, object] | None = None,
286
292
  ) -> Analysis:
287
293
  acquired = _acquire(
288
294
  sessions,
@@ -300,6 +306,7 @@ def _analyse_sessions(
300
306
  analyzer=analyzer,
301
307
  jev_key=jev_key,
302
308
  history=history,
309
+ gate_conditions=gate_conditions,
303
310
  )
304
311
  return Analysis(
305
312
  run=run,
stacktrace/cloud/boot.py CHANGED
@@ -6,18 +6,28 @@ One worker at a time holds `boot.lock`, from its own `daemon status` check
6
6
  until the daemon it starts answers. So a worker never replaces the client's
7
7
  files while a daemon runs or is starting: a second hook's worker waits, checks
8
8
  again, and finds the daemon up.
9
+
10
+ Each failure, and each daemon this worker had to start, is one line in
11
+ `session-start.log` (docs/specs/plugin-installation.md, "Session-start log").
12
+ The SessionStart adapters write their own failures through `write_log` here.
9
13
  """
10
14
 
11
15
  import fcntl
16
+ import json
12
17
  import os
13
18
  import pwd
19
+ import re
14
20
  import shlex
21
+ import stat
15
22
  import subprocess
16
23
  import sys
17
24
  import time
25
+ from contextlib import contextmanager
18
26
  from datetime import datetime, timezone
19
27
 
20
28
  STATE, UPDATE_ENV = "", ""
29
+ #: The session's agent kind, from the scope argument, or `-` when there is none.
30
+ KIND = "-"
21
31
  #: How long an update may take before the installed client runs instead.
22
32
  UPDATE_SECONDS = 120
23
33
  #: How long the lock waits for the daemon this worker started to answer.
@@ -26,6 +36,113 @@ START_SECONDS = 30
26
36
  #: transition lock while it uploads to Fleet, and refuses until it finishes.
27
37
  REGISTER_ATTEMPTS = 10
28
38
 
39
+ LOG_NAME = "session-start.log"
40
+ #: Past this size the log keeps only its last `LOG_LINES` lines.
41
+ LOG_BYTES = 64 * 1024
42
+ LOG_LINES = 500
43
+ #: An agent kind's shape. The kinds themselves are not listed: a new one needs no change here.
44
+ KIND_SHAPE = re.compile(r"[a-z][a-z0-9-]{0,31}")
45
+ STAGES = (
46
+ "input",
47
+ "scope",
48
+ "launch",
49
+ "lock",
50
+ "update",
51
+ "daemon-start",
52
+ "daemon-started",
53
+ "register",
54
+ "bootstrap",
55
+ )
56
+ #: A fixed word or an exception's type name. Never a message, a path or a value.
57
+ DETAIL = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{0,63}")
58
+
59
+
60
+ def log_root():
61
+ """`state_root()` from `stacktrace.private_state`. Setup copies this file to
62
+ run on system Python, where the package need not import."""
63
+ default = os.path.join(os.path.expanduser("~"), ".local", "state", "stacktrace")
64
+ return os.environ.get("STACKTRACE_STATE_DIR", default)
65
+
66
+
67
+ def write_log(path, agent_kind, stage, detail):
68
+ """Append one line to the session-start log and trim it; never raise.
69
+
70
+ The writer accepts only a name-shaped kind, a known stage and a word-shaped detail, so
71
+ a call site that passes anything else writes `-` rather than the text."""
72
+ try:
73
+ if stage not in STAGES:
74
+ return
75
+ kind = (
76
+ agent_kind if isinstance(agent_kind, str) and KIND_SHAPE.fullmatch(agent_kind) else "-"
77
+ )
78
+ detail = detail if isinstance(detail, str) and DETAIL.fullmatch(detail) else "-"
79
+ line = f"{datetime.now(timezone.utc):%Y-%m-%dT%H:%M:%SZ} {kind} cli {stage} {detail}\n" # noqa: UP017 - legacy wrapper uses system Python, including 3.10
80
+ descriptor = os.open(path, os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
81
+ except Exception: # noqa: BLE001 - logging never fails the session
82
+ return
83
+ try:
84
+ # Bounded wait: a writer holds the lock for one append and trim.
85
+ for _ in range(20):
86
+ try:
87
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
88
+ break
89
+ except BlockingIOError:
90
+ time.sleep(0.01)
91
+ else:
92
+ return
93
+ os.write(descriptor, line.encode("utf-8"))
94
+ size = os.fstat(descriptor).st_size
95
+ if size > LOG_BYTES:
96
+ kept = os.pread(descriptor, size, 0).splitlines(keepends=True)[-LOG_LINES:]
97
+ os.ftruncate(descriptor, 0)
98
+ os.write(descriptor, b"".join(kept))
99
+ except Exception: # noqa: BLE001, S110 - logging never fails the session
100
+ pass
101
+ finally:
102
+ os.close(descriptor)
103
+
104
+
105
+ def _private_directory(path):
106
+ """`ensure_private_directory` from `stacktrace.private_state`, for the same reason."""
107
+ os.makedirs(path, mode=0o700, exist_ok=True)
108
+ metadata = os.lstat(path)
109
+ if not stat.S_ISDIR(metadata.st_mode) or metadata.st_uid != os.getuid():
110
+ raise OSError("state directory is not a user-owned directory")
111
+ if stat.S_IMODE(metadata.st_mode) != 0o700:
112
+ os.chmod(path, 0o700)
113
+
114
+
115
+ def log(stage, detail):
116
+ """One line for this worker's session; never raise."""
117
+ try:
118
+ root = log_root()
119
+ _private_directory(root)
120
+ write_log(os.path.join(root, LOG_NAME), KIND, stage, detail)
121
+ except Exception: # noqa: BLE001, S110 - logging never fails the session
122
+ pass
123
+
124
+
125
+ @contextmanager
126
+ def stage(name):
127
+ """Log a failure inside this block by its type, once, and let it propagate."""
128
+ try:
129
+ yield
130
+ except Exception as error:
131
+ if not getattr(error, "session_start_logged", False):
132
+ setattr(error, "session_start_logged", True) # noqa: B010 - any exception type
133
+ log(name, type(error).__name__)
134
+ raise
135
+
136
+
137
+ def kind_of(arguments):
138
+ """The agent kind the scope argument names, else `-`."""
139
+ try:
140
+ scope = json.loads(arguments[0])
141
+ kind = scope.get("agent_kind") if isinstance(scope, dict) else None
142
+ except Exception: # noqa: BLE001 - registration reports a bad scope
143
+ return "-"
144
+ return kind if isinstance(kind, str) and KIND_SHAPE.fullmatch(kind) else "-"
145
+
29
146
 
30
147
  def note(text):
31
148
  with open(os.path.join(STATE, "update.log"), "a", encoding="utf-8") as log:
@@ -82,21 +199,26 @@ def update():
82
199
  f"not updating: {user} cannot run uv or write the install; "
83
200
  "rebuild the environment to update the client"
84
201
  )
202
+ log("update", "not-permitted")
85
203
  return
86
204
  environment = {**os.environ, **{k: v for k, v in values.items() if k.startswith("UV_")}}
87
- with open(os.path.join(STATE, "update.log"), "a", encoding="utf-8") as log:
205
+ with open(os.path.join(STATE, "update.log"), "a", encoding="utf-8") as output:
88
206
  try:
89
- subprocess.run(
207
+ result = subprocess.run(
90
208
  [uv, "tool", "upgrade", "stacktrace-cli"],
91
209
  env=environment,
92
210
  stdin=subprocess.DEVNULL,
93
- stdout=log,
211
+ stdout=output,
94
212
  stderr=subprocess.STDOUT,
95
213
  timeout=UPDATE_SECONDS,
96
214
  check=False,
97
215
  )
98
216
  except (OSError, subprocess.SubprocessError) as error:
99
217
  note(f"update stopped: {type(error).__name__}; the installed client runs")
218
+ log("update", type(error).__name__)
219
+ return
220
+ if result.returncode:
221
+ log("update", "nonzero-exit")
100
222
 
101
223
 
102
224
  def configure():
@@ -135,9 +257,11 @@ def configure():
135
257
 
136
258
 
137
259
  def ensure_daemon():
138
- lock = os.open(os.path.join(STATE, "boot.lock"), os.O_CREAT | os.O_RDWR, 0o600)
260
+ with stage("lock"):
261
+ lock = os.open(os.path.join(STATE, "boot.lock"), os.O_CREAT | os.O_RDWR, 0o600)
139
262
  try:
140
- fcntl.flock(lock, fcntl.LOCK_EX)
263
+ with stage("lock"):
264
+ fcntl.flock(lock, fcntl.LOCK_EX)
141
265
  configure()
142
266
  _ensure_daemon()
143
267
  finally:
@@ -153,10 +277,12 @@ def _ensure_daemon():
153
277
  # answer says nothing. Either may be a live client.
154
278
  if answer == "no":
155
279
  if os.environ.get("CLAUDE_CODE_REMOTE") == "true":
156
- update()
280
+ with stage("update"):
281
+ update()
157
282
  else:
158
283
  note(f"not updating: daemon status said {answer or 'nothing'}, not that no daemon runs")
159
- with open(os.path.join(STATE, "daemon.log"), "a", encoding="utf-8") as out:
284
+ daemon_log = os.path.join(STATE, "daemon.log")
285
+ with stage("daemon-start"), open(daemon_log, "a", encoding="utf-8") as out:
160
286
  subprocess.Popen(
161
287
  ["stacktrace", "daemon", "start", "--no-reasoning"],
162
288
  stdin=subprocess.DEVNULL,
@@ -165,33 +291,46 @@ def _ensure_daemon():
165
291
  start_new_session=True,
166
292
  )
167
293
  deadline = time.monotonic() + START_SECONDS
168
- while time.monotonic() < deadline and running() != "yes":
294
+ while time.monotonic() < deadline:
295
+ if running() == "yes":
296
+ log(
297
+ "daemon-started",
298
+ "was-stopped"
299
+ if answer == "no"
300
+ else "was-unresponsive"
301
+ if answer == "unresponsive"
302
+ else "no-status",
303
+ )
304
+ return
169
305
  time.sleep(0.5)
306
+ log("daemon-start", "timeout")
170
307
 
171
308
 
172
309
  def main():
310
+ global KIND
311
+ KIND = kind_of(sys.argv[3:4])
173
312
  os.makedirs(STATE, mode=0o700, exist_ok=True)
174
313
  os.chmod(STATE, 0o700)
175
314
  ensure_daemon()
176
315
  if len(sys.argv) > 3:
177
- import json
178
-
179
- from stacktrace.hooks.session import register
316
+ with stage("register"):
317
+ from stacktrace.hooks.session import register
180
318
 
181
- scope = json.loads(sys.argv[3])
182
- for attempt in range(REGISTER_ATTEMPTS):
183
- try:
184
- register(scope)
185
- return
186
- except Exception: # a busy daemon refuses or times out alike
187
- if attempt == REGISTER_ATTEMPTS - 1:
188
- raise
189
- time.sleep(1)
319
+ scope = json.loads(sys.argv[3])
320
+ for attempt in range(REGISTER_ATTEMPTS):
321
+ try:
322
+ register(scope)
323
+ return
324
+ except Exception: # a busy daemon refuses or times out alike
325
+ if attempt == REGISTER_ATTEMPTS - 1:
326
+ raise
327
+ time.sleep(1)
190
328
 
191
329
 
192
330
  if __name__ == "__main__":
193
331
  STATE, UPDATE_ENV = sys.argv[1], sys.argv[2]
194
332
  try:
195
- main()
333
+ with stage("bootstrap"):
334
+ main()
196
335
  except Exception: # noqa: BLE001 - never expose native payloads or credentials
197
336
  note("session bootstrap failed; inspect daemon status and rerun setup")
@@ -25,7 +25,7 @@ import sys
25
25
  import tempfile
26
26
  from collections.abc import Callable, Sequence
27
27
  from collections.abc import Set as AbstractSet
28
- from dataclasses import dataclass
28
+ from dataclasses import dataclass, replace
29
29
  from datetime import UTC, datetime
30
30
  from importlib.metadata import (
31
31
  Distribution,
@@ -36,9 +36,12 @@ from importlib.metadata import (
36
36
  from pathlib import Path
37
37
  from typing import Any
38
38
 
39
+ from openaca.core import collect_installed_agents
40
+
39
41
  from stacktrace.correlate.composition import (
40
42
  Advisory,
41
43
  Composition,
44
+ Posture,
42
45
  composable,
43
46
  composition_from_bom,
44
47
  reject_malformed_shape,
@@ -242,71 +245,38 @@ def build_bom(
242
245
  """
243
246
  if not composable(agent_kind):
244
247
  return None
245
- with tempfile.TemporaryDirectory() as scratch:
246
- directory = Path(scratch)
247
- argv = [
248
- _openaca(),
249
- "bom",
250
- "endpoint",
251
- "--kind",
252
- agent_kind,
253
- "--output-dir",
254
- str(directory),
255
- ]
256
- if project is not None:
257
- argv += ["--project", str(project)]
258
- result = subprocess.run(
259
- argv,
260
- capture_output=True,
261
- text=True,
262
- check=False,
248
+ try:
249
+ agents = collect_installed_agents(project=project, kind_id=agent_kind)
250
+ except Exception as error:
251
+ raise RuntimeError(f"OpenACA composition acquisition failed: {error}") from error
252
+ if not agents:
253
+ return None
254
+ if len(agents) != 1:
255
+ raise ValueError(
256
+ f"OpenACA produced {len(agents)} BOMs for kind {agent_kind!r}; one kind selects one composition"
263
257
  )
264
- if result.returncode != 0:
265
- # A missing composition is the difference between "nothing ran" and
266
- # "we could not look"; the second must not read as the first.
267
- scope = f" --project {project}" if project is not None else ""
268
- raise RuntimeError(
269
- f"openaca bom endpoint --kind {agent_kind}{scope} failed "
270
- f"(exit {result.returncode}): {result.stderr.strip()}"
271
- )
272
-
273
- # `*.cdx.json`, not `*.json`: OpenACA also writes a
274
- # `.openaca-bom-manifest.json` index beside the documents, and counting
275
- # it as a BOM would read one agent as two.
276
- documents = sorted(directory.glob("*.cdx.json"))
277
- if not documents:
278
- return None
279
- if len(documents) > 1:
280
- raise ValueError(
281
- f"openaca produced {len(documents)} BOMs for kind {agent_kind!r}; "
282
- "one kind selects one composition, and choosing between instances "
283
- "would invent one"
284
- )
285
-
286
- document = json.loads(documents[0].read_text(encoding="utf-8"))
287
- # Same rule as `load_bom`, for the same reason. This document came from
288
- # `openaca` rather than from a user, but a version skew that changed a
289
- # container's type would still reach `_declared_kind` first, and the
290
- # boundary is *every* entry point that reads a raw field.
291
- reject_malformed_shape(document)
292
- declared = _declared_kind(document)
293
- if declared != agent_kind:
294
- raise ValueError(
295
- f"requested kind {agent_kind!r} but the BOM declares {declared!r}; "
296
- "caching it under the requested kind would resolve sessions "
297
- "against another agent's composition"
258
+ agent = agents[0]
259
+ document = agent.bom
260
+ reject_malformed_shape(document)
261
+ declared = _declared_kind(document)
262
+ if declared != agent_kind:
263
+ raise ValueError(f"requested kind {agent_kind!r} but the BOM declares {declared!r}")
264
+ composition = composition_from_bom(document, agent_kind, clock(), True)
265
+ posture: dict[str, list[Posture]] = {}
266
+ refs = {component.bom_ref for component in composition.components}
267
+ for finding in agent.posture_findings:
268
+ if finding.bom_ref in refs:
269
+ posture.setdefault(finding.bom_ref, []).append(
270
+ Posture(finding.rule_id, finding.severity)
298
271
  )
299
- # Read now: the first moment this document is known to exist, and to be
300
- # the kind that was asked for. Before the subprocess it did not exist, so
301
- # that reading could only ever be a lower bound.
302
- #
303
- # Advisories are *not* fetched here. They are matched once, after
304
- # correlation, over the components sessions actually invoked — see
305
- # `advisories_for`.
306
- return Built(
307
- composition=composition_from_bom(document, agent_kind, clock(), True),
308
- document=document,
309
- )
272
+ return Built(
273
+ composition=replace(
274
+ composition,
275
+ posture={ref: tuple(found) for ref, found in posture.items()},
276
+ posture_checked=True,
277
+ ),
278
+ document=document,
279
+ )
310
280
 
311
281
 
312
282
  @dataclass(frozen=True)
@@ -504,6 +474,9 @@ def _scan(
504
474
  return None
505
475
  if not all(_text_or_absent(value) for value in (fixed_in, source, severity, title)):
506
476
  return None
477
+ aliases = _aliases(finding.get("matched_advisory"))
478
+ if aliases is None:
479
+ return None
507
480
  key = key_by_ref.get(ref)
508
481
  if key is None:
509
482
  # Not malformed: we sent the components, and a ref we do not hold is
@@ -517,11 +490,33 @@ def _scan(
517
490
  title=title or "",
518
491
  fixed_in=fixed_in,
519
492
  source=source,
493
+ aliases=aliases,
520
494
  )
521
495
  )
522
496
  return {key: tuple(items) for key, items in matched.items()}
523
497
 
524
498
 
499
+ def _aliases(matched: object) -> tuple[str, ...] | None:
500
+ """`matched_advisory.aliases` as a tuple, `()` when absent, or None when
501
+ the response is not the shape OpenACA writes.
502
+
503
+ OpenACA's own vulnerability gate matches a listed id against the advisory's
504
+ id and its aliases (`tools/overlays.py`, `id_set`). Detect filters by the
505
+ same ids, so it reads the same aliases (unified-policy.md, "Detect with a
506
+ condition").
507
+ """
508
+ if matched is None:
509
+ return ()
510
+ if not isinstance(matched, dict):
511
+ return None
512
+ aliases = matched.get("aliases")
513
+ if aliases is None:
514
+ return ()
515
+ if not isinstance(aliases, list) or not all(isinstance(a, str) for a in aliases):
516
+ return None
517
+ return tuple(aliases)
518
+
519
+
525
520
  def _text_or_absent(value: object) -> bool:
526
521
  """Whether a field arrived as the `str | None` `Advisory` declares it.
527
522
 
@@ -98,6 +98,17 @@ class Advisory:
98
98
  title: str
99
99
  fixed_in: str | None
100
100
  source: str | None
101
+ #: The advisory's other ids, such as a GHSA advisory's CVE, as OpenACA's
102
+ #: `matched_advisory.aliases` lists them. A gate's `ids` match any of them.
103
+ aliases: tuple[str, ...] = ()
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class Posture:
108
+ """A posture check OpenACA matched to a component in the scanned BOM."""
109
+
110
+ rule_id: str
111
+ severity: str
101
112
 
102
113
 
103
114
  @dataclass(frozen=True)
@@ -127,6 +138,8 @@ class Composition:
127
138
  #: Whether advisory matching ran at all. An unchecked composition must never
128
139
  #: read as a clean one.
129
140
  advisories_checked: bool = False
141
+ posture: dict[str, tuple[Posture, ...]] = field(default_factory=dict)
142
+ posture_checked: bool = False
130
143
  #: The directory a session named, when this composition was built somewhere
131
144
  #: else because that directory no longer exists. None for the ordinary case,
132
145
  #: where the scanned location is the one the session recorded.
@@ -181,7 +181,7 @@ AdvisoryLookup = Callable[
181
181
  ["Sequence[dict[str, Any]]", "AbstractSet[AdvisoryKey]"],
182
182
  "dict[AdvisoryKey, tuple[Advisory, ...]] | None",
183
183
  ]
184
- AttachAdvisories = Callable[[CorrelatedView, "Sequence[Built]"], CorrelatedView]
184
+ AttachAdvisories = Callable[..., CorrelatedView]
185
185
 
186
186
 
187
187
  class CachingAdvisoryLookup:
@@ -234,8 +234,12 @@ def advisory_attacher(lookup: AdvisoryLookup = advisories_for) -> AttachAdvisori
234
234
  that reasoning would be a second chance to get it wrong.
235
235
  """
236
236
 
237
- def attach(correlated: CorrelatedView, builts: Sequence[Built]) -> CorrelatedView:
238
- return _attach_advisories(correlated, builts, lookup=lookup)
237
+ def attach(
238
+ correlated: CorrelatedView,
239
+ builts: Sequence[Built],
240
+ also: AbstractSet[AdvisoryKey] = frozenset(),
241
+ ) -> CorrelatedView:
242
+ return _attach_advisories(correlated, builts, lookup=lookup, also=also)
239
243
 
240
244
  return attach
241
245
 
@@ -245,6 +249,7 @@ def _attach_advisories(
245
249
  builts: Sequence[Built],
246
250
  *,
247
251
  lookup: AdvisoryLookup = advisories_for,
252
+ also: AbstractSet[AdvisoryKey] = frozenset(),
248
253
  ) -> CorrelatedView:
249
254
  """Match advisories once, over what ran, and hang them on every composition.
250
255
 
@@ -267,7 +272,9 @@ def _attach_advisories(
267
272
  session independently would give two sessions that shared one composition
268
273
  two different enriched objects and break that dedup silently.
269
274
  """
270
- keys = _invoked_keys(correlated)
275
+ # `also` adds what a caller needs beyond what ran: the component of a
276
+ # component deny's marker, which did not run (ADR-0184).
277
+ keys = _invoked_keys(correlated) | set(also)
271
278
  matched = lookup([b.document for b in builts], keys)
272
279
  checked = matched is not None
273
280
  by_key = matched or {}