stacktrace-cli 0.5.0__py3-none-any.whl → 0.5.2__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 (45) hide show
  1. stacktrace_cli/__init__.py +8 -1
  2. stacktrace_cli/cli.py +2 -0
  3. stacktrace_cli/cloud/__init__.py +39 -0
  4. stacktrace_cli/cloud/setup.sh +247 -0
  5. stacktrace_cli/daemon/activity_log.py +94 -0
  6. stacktrace_cli/daemon/bom.py +56 -0
  7. stacktrace_cli/daemon/cli.py +453 -19
  8. stacktrace_cli/daemon/client.py +230 -9
  9. stacktrace_cli/daemon/composition.py +112 -3
  10. stacktrace_cli/daemon/config.py +191 -0
  11. stacktrace_cli/daemon/db.py +625 -0
  12. stacktrace_cli/daemon/fleet.py +660 -0
  13. stacktrace_cli/daemon/identity.py +83 -0
  14. stacktrace_cli/daemon/jobs.py +181 -0
  15. stacktrace_cli/daemon/lifecycle.py +172 -0
  16. stacktrace_cli/daemon/observer.py +545 -92
  17. stacktrace_cli/daemon/paths.py +6 -1
  18. stacktrace_cli/daemon/protocol.py +125 -8
  19. stacktrace_cli/daemon/runtime.py +572 -100
  20. stacktrace_cli/daemon/scan.py +256 -0
  21. stacktrace_cli/daemon/server.py +141 -2
  22. stacktrace_cli/daemon/service.py +98 -121
  23. stacktrace_cli/daemon/store.py +789 -258
  24. stacktrace_cli/daemon/webhook.py +508 -0
  25. stacktrace_cli/detector/render.py +31 -4
  26. stacktrace_cli/monitor/site/app.js +1 -1
  27. stacktrace_cli/monitor/site/index.html +3 -4
  28. stacktrace_cli/remote/cli.py +28 -19
  29. stacktrace_cli/remote/client.py +29 -0
  30. stacktrace_cli/remote/detect_payload.py +147 -25
  31. stacktrace_cli/remote/identity.py +305 -0
  32. stacktrace_cli/remote/payload.py +7 -4
  33. stacktrace_cli/remote/redact.py +773 -105
  34. stacktrace_cli/remote/sync.py +330 -98
  35. stacktrace_cli/remote/sync_detect.py +134 -64
  36. stacktrace_cli/remote/upload_contract.py +10 -1
  37. stacktrace_cli/telemetry/events.py +12 -6
  38. stacktrace_cli/telemetry/posthog.py +34 -5
  39. stacktrace_cli/webhook/__init__.py +1 -0
  40. stacktrace_cli/webhook/cli.py +169 -0
  41. stacktrace_cli/webhook/config.py +193 -0
  42. {stacktrace_cli-0.5.0.dist-info → stacktrace_cli-0.5.2.dist-info}/METADATA +30 -2
  43. {stacktrace_cli-0.5.0.dist-info → stacktrace_cli-0.5.2.dist-info}/RECORD +45 -29
  44. {stacktrace_cli-0.5.0.dist-info → stacktrace_cli-0.5.2.dist-info}/entry_points.txt +1 -0
  45. {stacktrace_cli-0.5.0.dist-info → stacktrace_cli-0.5.2.dist-info}/WHEEL +0 -0
@@ -1,3 +1,10 @@
1
1
  """The `stacktrace` command-line interface — detection and response for AI agents."""
2
2
 
3
- __version__ = "0.5.0"
3
+ import logging as _logging
4
+
5
+ __version__ = "0.5.2"
6
+
7
+ # Only the daemon attaches a handler (ADR-0048). Without this one, a WARNING
8
+ # logged in any other process would reach Python's last-resort handler and
9
+ # print onto the user's terminal.
10
+ _logging.getLogger(__name__).addHandler(_logging.NullHandler())
stacktrace_cli/cli.py CHANGED
@@ -40,6 +40,7 @@ from .sessions.access import collect_sessions
40
40
  from .sessions.render import render_json, render_text
41
41
  from .telemetry import emit_error
42
42
  from .telemetry.cli import telemetry as telemetry_cmd
43
+ from .webhook.cli import webhook as webhook_cmd
43
44
 
44
45
  PASSTHROUGH: Final = ("scan", "bom", "policy")
45
46
 
@@ -586,3 +587,4 @@ main.add_command(monitor)
586
587
  main.add_command(daemon_cmd, "daemon")
587
588
  main.add_command(findings)
588
589
  main.add_command(telemetry_cmd, "telemetry")
590
+ main.add_command(webhook_cmd, "webhook")
@@ -0,0 +1,39 @@
1
+ """One entry point for a Claude Code cloud environment's setup script.
2
+
3
+ A cloud environment's setup script runs once, as root, before the filesystem is
4
+ snapshotted and reused by every later session. What a session needs that is not
5
+ the CLI itself — the per-session boot hook and the asset identity — has to be
6
+ laid down there so it lands inside the snapshot.
7
+
8
+ Rather than paste that into the setup-script box, a setup script installs the
9
+ CLI and runs this:
10
+
11
+ UV_TOOL_DIR=/usr/local/share/uv-tools UV_TOOL_BIN_DIR=/usr/local/bin \
12
+ uv tool install stacktrace-cli
13
+ stacktrace-cloud-setup
14
+
15
+ Both variables matter: setup runs as root, and `uv tool install`'s root
16
+ defaults put the tool's environment under `/root/.local/share/uv/tools` and the
17
+ linked executable under `/root/.local/bin` — both inside `/root`, which a later
18
+ non-root session user cannot traverse. `UV_TOOL_BIN_DIR` alone moves the
19
+ symlink but not the environment it points into, so `command -v stacktrace` would
20
+ find the binary while running it still fails; both must move.
21
+
22
+ The work itself is `setup.sh`, shipped beside this module so it travels in the
23
+ wheel. This shim only locates it and hands off, so the logic stays one auditable
24
+ bash file rather than being reimplemented in Python.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ import sys
31
+ from pathlib import Path
32
+
33
+
34
+ def main() -> None:
35
+ script = Path(__file__).with_name("setup.sh")
36
+ # execvp so the process *becomes* bash: its exit status is the setup
37
+ # script's, which is what the environment reads to decide the session may
38
+ # start, and there is no Python frame left to swallow a signal.
39
+ os.execvp("bash", ["bash", str(script), *sys.argv[1:]])
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env bash
2
+ # Lay down everything a Claude Code cloud session needs, at environment setup.
3
+ #
4
+ # Run once by the environment's setup script, as root, before the filesystem is
5
+ # snapshotted. Two things, both of which must be inside that snapshot because
6
+ # the setup script does not run again for later sessions:
7
+ #
8
+ # 1. /usr/local/bin/stacktrace-boot.sh — the per-session hook that configures
9
+ # the remote and starts the daemon. Registered as a SessionStart hook in
10
+ # every home so it fires whichever user the session runs as.
11
+ # 2. The asset identity, in every home's ~/.config/stacktrace/asset-id, so
12
+ # `stacktrace remote sync` resolves it at the persisted rung (ADR-0065)
13
+ # instead of minting a fresh asset per session.
14
+ #
15
+ # The telemetry install id is deliberately NOT seeded here. Seeding it would
16
+ # make `read_install_id()` non-None before any event runs, so the one-time
17
+ # `installed` event (which `emit()` synthesizes only when the id is absent)
18
+ # would never fire. Left unseeded, the daemon's first in-session event mints the
19
+ # id and fires `installed` once per VM, correctly attributed `remote=true`
20
+ # because it runs inside the session. Counting one install per VM rather than
21
+ # per environment is ADR-0043's documented cloud tradeoff; per-environment is
22
+ # not cleanly achievable for an ephemeral VM (a setup-time emit would carry the
23
+ # wrong `remote` value and could not flush from a one-shot process).
24
+ #
25
+ # Every home rather than $HOME: setup runs as root and the user a session runs
26
+ # as is not documented, so writing all of them removes the guess. The asset id
27
+ # is unconditional — each environment instance gets its own, and a leftover from
28
+ # a previous snapshot must not win.
29
+ #
30
+ # Scope (ADR-0070): this seeds the snapshot and starts the daemon per session.
31
+ # It does not own daemon lifetime across a supervisor — that is ADR-0066, and a
32
+ # cloud VM is one session per VM, so the daemon dying with the VM is correct.
33
+ # The environment this targets is a fresh, single-tenant snapshot: it does not
34
+ # defend against adversarial or pre-existing symlinks and special files in a
35
+ # home, because that home does not exist until this run creates it.
36
+ #
37
+ # Options (all optional):
38
+ # --asset-id VALUE use this asset id instead of minting one; also taken
39
+ # from STACKTRACE_ASSET_EXTERNAL_ID in the environment
40
+ # --root DIR treat DIR as / (for testing)
41
+ #
42
+ # The remote token and API URL are read by the boot hook at session time from
43
+ # STACKTRACE_REMOTE_TOKEN and STACKTRACE_REMOTE_API_URL, not here: they belong
44
+ # to the environment's variables, not to the snapshot this seeds.
45
+ set -uo pipefail
46
+
47
+ ASSET_ID="${STACKTRACE_ASSET_EXTERNAL_ID:-}"
48
+ ROOT=""
49
+
50
+ while [ $# -gt 0 ]; do
51
+ case "$1" in
52
+ # `$# -ge 2` before the shift: without it, `--root` with no operand leaves
53
+ # the positional parameters unchanged under `set -u` with no `set -e`, and
54
+ # the loop spins forever — a malformed invocation would hang setup.
55
+ --asset-id) [ $# -ge 2 ] || { echo "✗ --asset-id needs a value" >&2; exit 2; }; ASSET_ID="$2"; shift 2 ;;
56
+ --root) [ $# -ge 2 ] || { echo "✗ --root needs a value" >&2; exit 2; }; ROOT="$2"; shift 2 ;;
57
+ -h|--help) sed -n '2,44p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
58
+ *) echo "✗ unknown argument: $1" >&2; exit 2 ;;
59
+ esac
60
+ done
61
+
62
+ LOG="${ROOT}/var/log/stacktrace-cloud-setup.log"
63
+ mkdir -p "$(dirname "$LOG")" 2>/dev/null || true
64
+ exec > >(tee -a "$LOG") 2>&1
65
+ echo "=== stacktrace cloud setup $(date -u +%FT%TZ) ==="
66
+
67
+ # ---- identities ----------------------------------------------------------
68
+ _uuid() {
69
+ if [ -r /proc/sys/kernel/random/uuid ]; then
70
+ cat /proc/sys/kernel/random/uuid
71
+ else
72
+ python3 -c 'import uuid; print(uuid.uuid4())'
73
+ fi
74
+ }
75
+
76
+ [ -n "$ASSET_ID" ] || ASSET_ID="cloud-$(_uuid)"
77
+ # remote/identity.py:_is_identifier rejects whitespace, non-printable
78
+ # characters, and anything over 255 characters. A value this accepts but the
79
+ # runtime rejects is worse than no file: every session reads it, rejects it,
80
+ # and mints a fresh asset — the per-session proliferation this exists to stop.
81
+ case "$ASSET_ID" in
82
+ *[[:space:]]*|"") echo "✗ asset id must be non-empty with no whitespace" >&2; exit 2 ;;
83
+ esac
84
+ if [ "${#ASSET_ID}" -gt 255 ]; then
85
+ echo "✗ asset id must be 255 characters or fewer" >&2
86
+ exit 2
87
+ fi
88
+ if ! python3 -c 'import sys; sys.exit(0 if sys.argv[1].isprintable() else 1)' "$ASSET_ID"; then
89
+ echo "✗ asset id must contain no non-printable characters" >&2
90
+ exit 2
91
+ fi
92
+ # ---- the per-session boot hook -------------------------------------------
93
+ # Failing hard here: if the hook cannot be written, every session's SessionStart
94
+ # command points at a file that does not exist and the daemon never starts —
95
+ # a silent total failure worse than a setup that stops and says so.
96
+ BOOT="${ROOT}/usr/local/bin/stacktrace-boot.sh"
97
+ mkdir -p "$(dirname "$BOOT")" || { echo "✗ cannot create $(dirname "$BOOT")" >&2; exit 1; }
98
+ cat > "$BOOT" <<'BOOTSCRIPT' || { echo "✗ cannot write $BOOT" >&2; exit 1; }
99
+ #!/usr/bin/env bash
100
+ # Configure the remote and start the daemon for this cloud session. No-op
101
+ # anywhere else. The asset id is already on disk from setup, so this does not
102
+ # touch it: it only configures the token and starts the daemon, which resolves
103
+ # the persisted asset id and mints the telemetry id on its first event.
104
+ #
105
+ # `daemon run` is started detached, not through a supervisor: a cloud VM runs
106
+ # one session, so the daemon's lifetime is the VM's (ADR-0070). Where a host
107
+ # runs several sessions, ADR-0066's `daemon start` replaces this one line.
108
+ set -u
109
+ [ "${CLAUDE_CODE_REMOTE:-}" = "true" ] || exit 0
110
+ command -v stacktrace >/dev/null 2>&1 || exit 0
111
+ [ -n "${STACKTRACE_REMOTE_TOKEN:-}" ] || exit 0
112
+
113
+ STATE="$HOME/.local/state/stacktrace"
114
+ mkdir -p "$STATE" && chmod 700 "$STATE"
115
+
116
+ stacktrace remote configure \
117
+ --token "$STACKTRACE_REMOTE_TOKEN" \
118
+ --api-url "${STACKTRACE_REMOTE_API_URL:-https://api.stacktrace.ai}" >/dev/null 2>&1 || true
119
+
120
+ # Streams redirected because own_std_streams only re-points fd 1/2 on log
121
+ # rollover; without this the daemon inherits the hook's pipe to Claude Code.
122
+ if ! stacktrace daemon status 2>/dev/null | grep -q '^running: yes'; then
123
+ setsid nohup stacktrace daemon run </dev/null >>"$STATE/daemon.log" 2>&1 &
124
+ fi
125
+ exit 0
126
+ BOOTSCRIPT
127
+ chmod 755 "$BOOT" || { echo "✗ cannot chmod $BOOT" >&2; exit 1; }
128
+ echo "✓ $BOOT"
129
+
130
+ # ---- seed every home -----------------------------------------------------
131
+ # Every existing home is seeded because the future session user is unknown, so a
132
+ # home that exists but cannot be seeded is a failure, not a skip: the session
133
+ # might run as exactly that user and find no daemon. `failed` records any such
134
+ # home and fails the whole run at the end, covering the mixed-success case where
135
+ # one home seeds and another does not. A candidate that is not a directory (the
136
+ # `/home/*` glob with no match, a stray file) is a genuine skip, not a home.
137
+ seeded=0
138
+ failed=0
139
+ for home in "${ROOT}"/root "${ROOT}"/home/*; do
140
+ [ -d "$home" ] || continue
141
+
142
+ cfg="$home/.config/stacktrace"
143
+ if ! install -d -m 700 "$cfg" 2>/dev/null; then
144
+ echo "✗ cannot create $cfg — not seeding $home" >&2; failed=1; continue
145
+ fi
146
+
147
+ if ! printf '%s\n' "$ASSET_ID" > "$cfg/asset-id" 2>/dev/null; then
148
+ echo "✗ cannot write $cfg/asset-id — not seeding $home" >&2; failed=1; continue
149
+ fi
150
+ chmod 600 "$cfg/asset-id" 2>/dev/null || true
151
+
152
+ # Register the SessionStart hook, merging so any existing settings survive.
153
+ # The hook is the point of seeding a home — a home whose registration fails
154
+ # (an unwritable path, or a settings.json that is valid JSON of an unexpected
155
+ # shape) is a failure, not a skip, or setup would exit 0 having left that
156
+ # session with no daemon.
157
+ if ! python3 - "$home" <<'PY'
158
+ import json, pathlib, sys
159
+ home = pathlib.Path(sys.argv[1])
160
+ p = home / ".claude" / "settings.json"
161
+ command = "/usr/local/bin/stacktrace-boot.sh"
162
+ try:
163
+ p.parent.mkdir(parents=True, exist_ok=True)
164
+ if p.exists():
165
+ # Present but unreadable or not valid JSON: do not clobber a real file.
166
+ s = json.loads(p.read_text())
167
+ else:
168
+ s = {}
169
+ except Exception:
170
+ sys.exit(1)
171
+ # A settings.json Claude Code accepts is a JSON object with object-shaped
172
+ # `hooks` and a list-shaped `SessionStart`; anything else is a shape this must
173
+ # not silently rewrite, so it fails the home rather than guessing.
174
+ if not isinstance(s, dict):
175
+ sys.exit(1)
176
+ hooks = s.setdefault("hooks", {})
177
+ if not isinstance(hooks, dict):
178
+ sys.exit(1)
179
+ starts = hooks.setdefault("SessionStart", [])
180
+ if not isinstance(starts, list):
181
+ sys.exit(1)
182
+ # Dedup only against an entry that actually fires on the events we need. An
183
+ # existing entry carrying this command under a narrower matcher (say `compact`)
184
+ # does not start the daemon at session start, so it must not suppress the
185
+ # `startup|resume` registration. A matcher covers us when it names both events,
186
+ # or when it is absent/empty — Claude Code treats that as matching every event.
187
+ required = {"startup", "resume"}
188
+
189
+
190
+ def covers(entry):
191
+ matcher = entry.get("matcher")
192
+ if matcher is None or matcher == "":
193
+ return True
194
+ return required.issubset({t.strip() for t in str(matcher).split("|")})
195
+
196
+
197
+ already = any(
198
+ isinstance(e, dict)
199
+ and covers(e)
200
+ and any(isinstance(h, dict) and h.get("command") == command for h in e.get("hooks", []))
201
+ for e in starts
202
+ )
203
+ if not already:
204
+ starts.append({"matcher": "startup|resume",
205
+ "hooks": [{"type": "command", "command": command}]})
206
+ try:
207
+ p.write_text(json.dumps(s, indent=2) + "\n")
208
+ except Exception:
209
+ sys.exit(1)
210
+ PY
211
+ then
212
+ echo "✗ could not register the hook in $home — not seeding it" >&2
213
+ failed=1
214
+ continue
215
+ fi
216
+
217
+ # Root created these directories, so they are root-owned; give them to the
218
+ # home's owner or the session user cannot write its own config. The parent
219
+ # `.config` that `install -d` created is chowned as well as the leaf, since a
220
+ # root-owned .config blocks the user from creating any other config beneath it.
221
+ for d in "$home/.config" "$cfg" "$home/.claude"; do
222
+ [ -e "$d" ] && chown --reference="$home" "$d" 2>/dev/null || true
223
+ done
224
+ chown --reference="$home" "$cfg/asset-id" \
225
+ "$home/.claude/settings.json" 2>/dev/null || true
226
+
227
+ echo "✓ seeded $home"
228
+ seeded=$((seeded + 1))
229
+ done
230
+
231
+ if [ "$seeded" -eq 0 ]; then
232
+ echo "✗ no home directory was writable — every session will mint its own identity" >&2
233
+ exit 1
234
+ fi
235
+
236
+ if [ "$failed" -ne 0 ]; then
237
+ echo "✗ one or more home directories could not be seeded — a session running as" \
238
+ "that user would have no daemon, so failing the whole setup rather than" \
239
+ "accepting a snapshot that works for some users and not others" >&2
240
+ exit 1
241
+ fi
242
+
243
+ command -v stacktrace >/dev/null 2>&1 || echo "! stacktrace is not on PATH yet; the boot hook waits for it" >&2
244
+
245
+ echo "✓ asset id: $ASSET_ID"
246
+ echo "✓ homes seeded: $seeded"
247
+ exit 0
@@ -0,0 +1,94 @@
1
+ """The daemon's activity log: leveled, private and capped (ADR-0048).
2
+
3
+ Every module logs to its own `logging.getLogger(__name__)`. Only the daemon
4
+ attaches a file handler, to the `stacktrace_cli` package logger; everywhere
5
+ else the package's `NullHandler` keeps those lines off the terminal.
6
+
7
+ A line names kinds, counts, class names and event ids. It never carries a
8
+ finding's title or body, an exception message, or anything from a transcript,
9
+ and a peer-supplied session id is written with `%r`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import os
16
+ import sys
17
+ import time
18
+ from collections.abc import Mapping
19
+ from logging.handlers import RotatingFileHandler
20
+ from pathlib import Path
21
+
22
+ from stacktrace_cli.private_state import ensure_private_directory
23
+
24
+ LEVEL_VARIABLE = "STACKTRACE_DAEMON_LOG_LEVEL"
25
+ MAX_BYTES = 5 * 1024 * 1024
26
+ BACKUP_COUNT = 1
27
+ PACKAGE = "stacktrace_cli"
28
+
29
+
30
+ def private_opener(path: str, flags: int) -> int:
31
+ return os.open(path, flags, 0o600)
32
+
33
+
34
+ class _PrivateRotatingFileHandler(RotatingFileHandler):
35
+ def __init__(self, path: Path, *, max_bytes: int, own_std_streams: bool) -> None:
36
+ self._own_std_streams = own_std_streams
37
+ super().__init__(path, maxBytes=max_bytes, backupCount=BACKUP_COUNT, encoding="utf-8")
38
+
39
+ def _open(self): # type: ignore[override]
40
+ stream = open( # noqa: SIM115 - the handler owns and closes it
41
+ self.baseFilename,
42
+ self.mode,
43
+ encoding=self.encoding,
44
+ errors=self.errors,
45
+ opener=private_opener,
46
+ )
47
+ # The opener's mode applies only to a file it creates.
48
+ os.chmod(self.baseFilename, 0o600)
49
+ return stream
50
+
51
+ def doRollover(self) -> None:
52
+ super().doRollover()
53
+ # The detached launcher points this process's stdout and stderr at
54
+ # the file just renamed away. Follow it, or a crash traceback lands in
55
+ # the backup and is deleted with it at the next rollover.
56
+ if self._own_std_streams and self.stream is not None:
57
+ sys.stdout.flush()
58
+ sys.stderr.flush()
59
+ os.dup2(self.stream.fileno(), 1)
60
+ os.dup2(self.stream.fileno(), 2)
61
+
62
+
63
+ def level_from(environment: Mapping[str, str]) -> int:
64
+ name = environment.get(LEVEL_VARIABLE, "").strip().upper()
65
+ return logging.getLevelNamesMapping().get(name, logging.DEBUG)
66
+
67
+
68
+ def configure(
69
+ path: Path,
70
+ *,
71
+ environ: Mapping[str, str] | None = None,
72
+ own_std_streams: bool = False,
73
+ max_bytes: int = MAX_BYTES,
74
+ ) -> logging.Handler:
75
+ ensure_private_directory(path.parent)
76
+ handler = _PrivateRotatingFileHandler(
77
+ path, max_bytes=max_bytes, own_std_streams=own_std_streams
78
+ )
79
+ formatter = logging.Formatter(
80
+ "%(asctime)s %(levelname)s %(name)s: %(message)s", datefmt="%Y-%m-%dT%H:%M:%SZ"
81
+ )
82
+ formatter.converter = time.gmtime
83
+ handler.setFormatter(formatter)
84
+ logger = logging.getLogger(PACKAGE)
85
+ logger.setLevel(level_from(os.environ if environ is None else environ))
86
+ logger.addHandler(handler)
87
+ return handler
88
+
89
+
90
+ def release(handler: logging.Handler) -> None:
91
+ logger = logging.getLogger(PACKAGE)
92
+ logger.removeHandler(handler)
93
+ logger.setLevel(logging.NOTSET)
94
+ handler.close()
@@ -0,0 +1,56 @@
1
+ """The BOM job: `sync_endpoint()` on a timer.
2
+
3
+ A full snapshot of what is installed, not an append stream — so there is nothing
4
+ to cursor, and the spool already handles offline retry. It reads no part of the
5
+ finding queue, and it must upload on a machine with a broken detector, an empty
6
+ database, or no session ever scanned.
7
+
8
+ **It re-collects rather than uploading the daemon's warm `CompositionSnapshots`.**
9
+ `docs/specs/remote-sync.md`'s bar requires the payload be byte-identical to
10
+ OpenACA's for the same endpoint state, and the snapshot is built for a different
11
+ scope — `("claude-code", None)`, user scope with no project layering — by a
12
+ different path than `_collect()`. Reusing it would be a payload change wearing
13
+ the costume of a performance win.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass
20
+
21
+ from stacktrace_cli.remote.sync import SyncError, sync_endpoint
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class BomJobReport:
26
+ """What one run did, for a caller that has to tell the two zeros apart.
27
+
28
+ A machine with nothing installed and a machine that could not reach the
29
+ Cloud both upload nothing. The scheduled job does not care — it is due
30
+ again either way — but `stacktrace daemon sync-bom` is asked by a person,
31
+ and answering "0" to both is answering neither.
32
+ """
33
+
34
+ uploaded: int
35
+ failure: str | None = None
36
+
37
+
38
+ def run_bom_job(*, report: Callable[[str], None]) -> BomJobReport:
39
+ """One `sync endpoint`, with its progress sent somewhere a daemon can write.
40
+
41
+ `drain_the_spool` and `allow_offline_cache` semantics are exactly as the CLI
42
+ has them: a machine that is offline caches its collection and the next run
43
+ replays it. `SyncError` is an outcome here rather than an exit code — there
44
+ is no process to exit — so it is reported and the job is simply due again.
45
+ """
46
+ try:
47
+ results = sync_endpoint(
48
+ project=None,
49
+ quiet=True,
50
+ allow_offline_cache=True,
51
+ reporter=report,
52
+ )
53
+ except SyncError as error:
54
+ report(f"bom sync: {error}")
55
+ return BomJobReport(uploaded=0, failure=str(error))
56
+ return BomJobReport(uploaded=len(results))