agentic-devtools 0.2.641__py3-none-any.whl → 0.2.643__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.
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.2.641'
22
- __version_tuple__ = version_tuple = (0, 2, 641)
21
+ __version__ = version = '0.2.643'
22
+ __version_tuple__ = version_tuple = (0, 2, 643)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -8,10 +8,11 @@ import subprocess
8
8
  import sys
9
9
  import threading
10
10
  import time
11
- from collections.abc import Callable, Mapping, Sequence
12
- from contextlib import ExitStack, suppress
11
+ from collections.abc import Callable, Iterator, Mapping, Sequence
12
+ from contextlib import ExitStack, contextmanager, suppress
13
13
  from pathlib import Path
14
14
  from threading import Thread
15
+ from typing import Any, cast
15
16
 
16
17
  DEFAULT_BUDGET_SECONDS = 600
17
18
  TERM_GRACE_SECONDS = 10
@@ -20,24 +21,100 @@ OUTPUT_DRAIN_SECONDS = 1
20
21
  MAX_PENDING_STDOUT_BYTES = 65536
21
22
 
22
23
 
24
+ def _restore_signal_handlers(installed: list[tuple[int, object]], primary_error: BaseException | None) -> None:
25
+ restoration_errors = []
26
+ for signum, previous_handler in reversed(installed):
27
+ try:
28
+ signal.signal(signum, cast(Any, previous_handler))
29
+ except BaseException as exc:
30
+ restoration_errors.append((signum, exc))
31
+ if primary_error is not None:
32
+ for signum, error in restoration_errors:
33
+ primary_error.add_note(f"Signal restoration failed for {signum}: {error!r}")
34
+ elif restoration_errors:
35
+ raise restoration_errors[0][1]
36
+
37
+
38
+ def _eligible_signal_handlers(
39
+ is_posix: Callable[[], bool],
40
+ is_main_thread: Callable[[], bool],
41
+ get_handler: Callable[[int], object],
42
+ ) -> list[tuple[int, object]]:
43
+ candidates: tuple[str, ...] = ("SIGTERM", "SIGHUP")
44
+ if not is_posix() or not is_main_thread():
45
+ candidates = ()
46
+ return [
47
+ (signum, previous_handler)
48
+ for name in candidates
49
+ if (signum := getattr(signal, name, None)) is not None
50
+ if (previous_handler := get_handler(signum)) is not None
51
+ ]
52
+
53
+
54
+ @contextmanager
23
55
  def _temporary_signal_handlers(
24
56
  *,
25
57
  is_posix: Callable[[], bool] = lambda: os.name == "posix",
26
58
  is_main_thread: Callable[[], bool] = lambda: threading.current_thread() is threading.main_thread(),
27
59
  get_handler: Callable[[int], object] = signal.getsignal,
28
- ) -> list[tuple[int, object]]:
29
- """Return available signals whose previous handlers can be restored."""
30
- if not is_posix() or not is_main_thread():
31
- return []
32
- eligible = []
33
- for name in ("SIGTERM", "SIGHUP"):
34
- signum = getattr(signal, name, None)
35
- if signum is None:
36
- continue
37
- previous_handler = get_handler(signum)
38
- if previous_handler is not None:
39
- eligible.append((signum, previous_handler))
40
- return eligible
60
+ ) -> Iterator[Any]:
61
+ """Yield lifecycle state; callers catch Interrupted through begin_cleanup().
62
+
63
+ Call begin_cleanup() before cleanup work. first_signum remains inspectable
64
+ after exit; signals are no longer intercepted once handlers are restored.
65
+ Reentrant handler calls are ignored while capture is active. CPython
66
+ dispatches pending signal handlers in signum order, so first_signum reflects
67
+ handler invocation order, not kernel arrival order.
68
+ """
69
+ eligible = _eligible_signal_handlers(is_posix, is_main_thread, get_handler)
70
+
71
+ class Lifecycle:
72
+ class Interrupted(BaseException):
73
+ """First body signal; catch only inside the with body."""
74
+
75
+ phase = "installing"
76
+ first_signum: int | None = None
77
+ restoration_started = False
78
+ interrupted = False
79
+ _handling_lock = threading.Lock()
80
+
81
+ def handle(self, signum: int, frame: object) -> None:
82
+ if not self._handling_lock.acquire(blocking=False):
83
+ return
84
+ try:
85
+ if self.first_signum is None:
86
+ self.first_signum = signum
87
+ if all((self.phase == "body", not self.restoration_started, not self.interrupted)):
88
+ self.interrupted = True
89
+ raise self.Interrupted()
90
+ finally:
91
+ self._handling_lock.release()
92
+
93
+ def begin_body(self) -> None:
94
+ self.phase = "body"
95
+ if self.first_signum is not None:
96
+ self.handle(self.first_signum, None)
97
+
98
+ def begin_cleanup(self) -> None:
99
+ self.phase = "cleanup"
100
+
101
+ lifecycle = Lifecycle()
102
+ installed: list[tuple[int, object]] = []
103
+ primary_error = None
104
+ try:
105
+ for signum, previous_handler in eligible:
106
+ signal.signal(signum, lifecycle.handle)
107
+ installed.append((signum, previous_handler))
108
+ try:
109
+ yield lifecycle
110
+ finally:
111
+ lifecycle.restoration_started, lifecycle.phase = True, "restoring"
112
+ except BaseException as exc:
113
+ primary_error = exc
114
+ raise
115
+ finally:
116
+ lifecycle.restoration_started, lifecycle.phase = True, "restoring"
117
+ _restore_signal_handlers(installed, primary_error)
41
118
 
42
119
 
43
120
  def resolve_budget_seconds(environ: Mapping[str, str]) -> int:
@@ -27,6 +27,7 @@ from agentic_devtools.cli.ci.reconciliation.models import (
27
27
  queue_state_from_dict,
28
28
  validate_queue_state,
29
29
  )
30
+ from agentic_devtools.cli.ci.reconciliation.ref_head_writer import _write_ref_head
30
31
  from agentic_devtools.state import deserialize_queue_document, serialize_queue_document
31
32
 
32
33
  logger = logging.getLogger(__name__)
@@ -208,54 +209,32 @@ class GitHubVariableBackingStore:
208
209
  return data.revision, data
209
210
 
210
211
  def save_entry(self, key: tuple[str, str], expected_revision: int, updated: QueueState) -> None:
211
- """Persist queue state using the blob SHA as a compare-and-swap token."""
212
+ """Validate and replace queue state against one captured ref head."""
212
213
  repo, state_ref = key
213
- endpoint = f"/repos/{repo}/contents/{self._PATH}?ref={state_ref}"
214
- try:
215
- metadata = json.loads(self._api(endpoint))
216
- except RuntimeError as exc:
217
- if _is_not_found_error(exc):
218
- metadata = None
219
- else:
220
- raise QueueStoreError(f"Failed to load queue state from GitHub ref {state_ref!r}: {exc}") from exc
221
- if metadata is None:
222
- current_revision = 0
223
- sha = None
224
- else:
214
+
215
+ def prepare_content(head_sha: str) -> bytes:
225
216
  try:
226
- raw = base64.b64decode(metadata["content"].replace("\n", ""), validate=True)
227
- if len(raw) > config.MAX_STATE_SIZE_BYTES:
228
- raise StateTooLargeError(f"State size exceeds {config.MAX_STATE_SIZE_BYTES} bytes")
229
- current_revision = queue_state_from_dict(_decode_queue_document(raw)).revision
230
- sha = metadata["sha"]
231
- except (TypeError, ValueError, KeyError) as exc:
232
- raise StateDecodeError(f"Failed to decode queue state from GitHub ref {state_ref!r}: {exc}") from exc
233
- if current_revision != expected_revision:
234
- raise ConcurrentModificationError(
235
- f"Revision mismatch: expected {expected_revision}, got {current_revision}"
236
- )
237
- body = {
238
- "message": "chore: update ai-pr-loop reconciliation state",
239
- "content": base64.b64encode(serialize_queue_document(_state_to_dict(updated))).decode("ascii"),
240
- "branch": state_ref,
241
- }
242
- if sha is not None:
243
- body["sha"] = sha
217
+ entry = self.load_entry((repo, head_sha))
218
+ except RuntimeError as exc:
219
+ raise QueueStoreError(f"Failed to load queue state from GitHub ref {state_ref!r}: {exc}") from exc
220
+ current_revision = entry[0] if entry is not None else 0
221
+ if current_revision != expected_revision:
222
+ raise ConcurrentModificationError(
223
+ f"Revision mismatch: expected {expected_revision}, got {current_revision}"
224
+ )
225
+ return serialize_queue_document(_state_to_dict(updated))
226
+
244
227
  try:
245
- self._api(f"/repos/{repo}/contents/{self._PATH}", method="PUT", body=body)
228
+ _write_ref_head(
229
+ repo,
230
+ state_ref,
231
+ api=self._api,
232
+ bootstrap=self._create_state_ref,
233
+ prepare_content=prepare_content,
234
+ conflict_error=ConcurrentModificationError,
235
+ )
246
236
  except RuntimeError as exc:
247
- if sha is None and _is_not_found_error(exc):
248
- self._create_state_ref(repo, state_ref)
249
- try:
250
- self._api(f"/repos/{repo}/contents/{self._PATH}", method="PUT", body=body)
251
- except RuntimeError as retry_exc:
252
- if _is_conflict_error(retry_exc):
253
- raise ConcurrentModificationError("Queue state changed during save") from retry_exc
254
- raise QueueStoreError(
255
- f"Failed to persist queue state to GitHub ref {state_ref!r}: {retry_exc}"
256
- ) from retry_exc
257
- return
258
- if _is_conflict_error(exc):
237
+ if _contains_status_code(str(exc), 409):
259
238
  raise ConcurrentModificationError("Queue state changed during save") from exc
260
239
  raise QueueStoreError(f"Failed to persist queue state to GitHub ref {state_ref!r}: {exc}") from exc
261
240
 
@@ -0,0 +1,119 @@
1
+ """Private Git Data writer for snapshot-bound queue-state updates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import re
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+
12
+ def _is_ref_conflict(
13
+ exc: RuntimeError,
14
+ ref_endpoint: str,
15
+ captured_head: str,
16
+ *,
17
+ api: Callable[..., str],
18
+ sha_from: Callable[..., str],
19
+ ) -> bool:
20
+ text = str(exc)
21
+ status = getattr(exc, "http_status", None)
22
+ if status is None:
23
+ if re.search(r"(?<!\d)409(?!\d)", text):
24
+ status = 409
25
+ elif re.search(r"(?<!\d)422(?!\d)", text):
26
+ status = 422
27
+ if status == 409:
28
+ return True
29
+ if status != 422:
30
+ return False
31
+ if re.search(r"\b(?:non[-_ ]fast[-_ ]forward|not (?:a )?fast[- ]forward)\b", text, re.I):
32
+ return True
33
+ try:
34
+ current_head = sha_from(api(ref_endpoint), "object", "sha")
35
+ except Exception:
36
+ return False
37
+ return current_head != captured_head
38
+
39
+
40
+ def _write_ref_head(
41
+ repo: str,
42
+ state_ref: str,
43
+ *,
44
+ api: Callable[..., str],
45
+ bootstrap: Callable[[str, str], None],
46
+ prepare_content: Callable[[str], bytes],
47
+ conflict_error: type[Exception],
48
+ expected_head: str | None = None,
49
+ ) -> None:
50
+ """Write a child of one observed head, failing closed without a stale retry.
51
+
52
+ ``api`` is the caller's credential boundary. ``prepare_content`` validates
53
+ and serializes that exact snapshot. A supplied ``expected_head`` is used
54
+ without reading the ref; otherwise an absent ref is bootstrapped and reread.
55
+ A base tree preserves all paths except the queue document.
56
+ """
57
+
58
+ def sha_from(response: str, *keys: str) -> str:
59
+ try:
60
+ value: Any = json.loads(response)
61
+ except ValueError as exc:
62
+ raise RuntimeError("Invalid GitHub Git Data response") from exc
63
+ for key in keys:
64
+ value = value.get(key) if isinstance(value, dict) else None
65
+ if not isinstance(value, str) or not value:
66
+ raise RuntimeError("Invalid GitHub Git Data SHA")
67
+ return value
68
+
69
+ root = f"/repos/{repo}/git"
70
+ ref_endpoint = f"{root}/ref/heads/{state_ref}"
71
+ head = expected_head
72
+ if head is None:
73
+ try:
74
+ response = api(ref_endpoint)
75
+ except RuntimeError as exc:
76
+ if not (re.search(r"(?<!\d)404(?!\d)", str(exc)) or "not found" in str(exc).lower()):
77
+ raise
78
+ bootstrap(repo, state_ref)
79
+ response = api(ref_endpoint)
80
+ head = sha_from(response, "object", "sha")
81
+ content = prepare_content(head)
82
+ tree = sha_from(api(f"{root}/commits/{head}"), "tree", "sha")
83
+ blob = sha_from(
84
+ api(
85
+ f"{root}/blobs",
86
+ method="POST",
87
+ body={"content": base64.b64encode(content).decode("ascii"), "encoding": "base64"},
88
+ ),
89
+ "sha",
90
+ )
91
+ replacement_tree = sha_from(
92
+ api(
93
+ f"{root}/trees",
94
+ method="POST",
95
+ body={
96
+ "base_tree": tree,
97
+ "tree": [{"path": ".agdt/ai-pr-loop-state.json", "mode": "100644", "type": "blob", "sha": blob}],
98
+ },
99
+ ),
100
+ "sha",
101
+ )
102
+ commit = sha_from(
103
+ api(
104
+ f"{root}/commits",
105
+ method="POST",
106
+ body={
107
+ "message": "chore: update ai-pr-loop reconciliation state",
108
+ "tree": replacement_tree,
109
+ "parents": [head],
110
+ },
111
+ ),
112
+ "sha",
113
+ )
114
+ try:
115
+ api(f"{root}/refs/heads/{state_ref}", method="PATCH", body={"sha": commit, "force": False})
116
+ except RuntimeError as exc:
117
+ if _is_ref_conflict(exc, ref_endpoint, head, api=api, sha_from=sha_from):
118
+ raise conflict_error("Queue state changed during save") from exc
119
+ raise
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentic-devtools
3
- Version: 0.2.641
3
+ Version: 0.2.643
4
4
  Summary: Agentic devtools integrate Jira, DevOps & more
5
5
  Author: ayaiayorg
6
6
  License-Expression: MIT
@@ -1,5 +1,5 @@
1
1
  agentic_devtools/__init__.py,sha256=gvLzsZ6L3Abr4sPHr4OJ_rdZDD8cFzXacaV0LGs8dVc,539
2
- agentic_devtools/_version.py,sha256=qB7gQxsKEWH5wQb0kHqMPB5QRXDbcgUCF2qmB5Xvy6M,524
2
+ agentic_devtools/_version.py,sha256=EKFRcGP8KFFAOItiT4BQTB6iE3p9iwPnU3HZq3H21h4,524
3
3
  agentic_devtools/agdt_gitignore.py,sha256=vVVqTjBZ_ijn6U3Lnh_JGrARLschYVN-fFal9jDk0Ak,2694
4
4
  agentic_devtools/background_tasks.py,sha256=sFgmqOnCdCjclABJ8V__yDwBXDyi45b1Z-MVv3G2zB8,17664
5
5
  agentic_devtools/config.py,sha256=DEVxTVZhsQbVQwO9qdB_1h19aBpjMzF6xJY_ePYLGLs,15629
@@ -217,7 +217,7 @@ agentic_devtools/cli/checks/coverage_pool.py,sha256=I8lvSDABhVGopukLGsrXIsL9SbQZ
217
217
  agentic_devtools/cli/checks/customization_quality.py,sha256=VLZQW5WNUSTr40ngxI9gHUY7fK0P0Mm3PsMn3HYajj4,47864
218
218
  agentic_devtools/cli/checks/file_length.py,sha256=K1v6Bkn6dbVoBppjdigcpuPqYcxwmWanE3FtDwq78FA,4139
219
219
  agentic_devtools/cli/checks/lint.py,sha256=DLXWJpAJ8GfLYpBUF1sf2ArPnEdIkuQ2ksYv44wWJ5M,8568
220
- agentic_devtools/cli/checks/pre_push_budget.py,sha256=1P3GB8yuvnoaHXym03menCJ11BIVP8CMqBPlC8w4t9k,8258
220
+ agentic_devtools/cli/checks/pre_push_budget.py,sha256=6ZCJag2gFFOW9hpp8H-34SIgiJe7_egU5e2jtxZ9ip8,11224
221
221
  agentic_devtools/cli/checks/quality_baseline.py,sha256=PbSYAiJdWwEDP8SGGUXNpJVxkswGi-whveLOav7J2y4,2967
222
222
  agentic_devtools/cli/checks/setup_drift.py,sha256=bVR0F4wpwt8rOl829tGXKqI1PDUbg9JsXTShgYaJSSM,7666
223
223
  agentic_devtools/cli/checks/setup_drift_changed_files.py,sha256=73IuzquyLDKhWderCvFE5TXnHuBxBcQTSbg2p15-wKE,3719
@@ -417,10 +417,11 @@ agentic_devtools/cli/ci/reconciliation/observability.py,sha256=fdi1eOoosMg4gsGOP
417
417
  agentic_devtools/cli/ci/reconciliation/orchestrator.py,sha256=E2FwqzOT3lOtFmJz6I6V4Sfb7huFdKqqA6TEwkU7VnE,10262
418
418
  agentic_devtools/cli/ci/reconciliation/probes.py,sha256=ZO0RPX1p4e8pSd8zfRfWIFHbxqoenrVHwNcrEs25lBk,5519
419
419
  agentic_devtools/cli/ci/reconciliation/provider_outcomes.py,sha256=WhW1PNIZ7wRfxlsNSPOru5mxHcqDg1RB2QoRhtoT0wk,296
420
- agentic_devtools/cli/ci/reconciliation/queue_store.py,sha256=9qiDv133iEcEA2rTAX3EZReTmdJEbcSb9YsOpI89MlU,52405
420
+ agentic_devtools/cli/ci/reconciliation/queue_store.py,sha256=cadRqQzK0OaUVzpnC59EbP16Ln-cDq77uiPaQrx0BKA,51101
421
421
  agentic_devtools/cli/ci/reconciliation/queue_transitions.py,sha256=773zPv_N67cjQXkz9bhz5On_QqVRD6Nqms6wAs866tQ,9386
422
422
  agentic_devtools/cli/ci/reconciliation/reconciler.py,sha256=p3-mFDKCRk60e8T39AdJ967dpEW0q9xk2oFdDrZWxng,5487
423
423
  agentic_devtools/cli/ci/reconciliation/recovery.py,sha256=3Nz9AnFLtYJv7j_QvV4SYJDESJ1vvCHtPkD4N01g6h4,13310
424
+ agentic_devtools/cli/ci/reconciliation/ref_head_writer.py,sha256=OWnLnKnFimp6TY9Arr5xCXg4LG_wCLr7vtXvLET2FR0,3824
424
425
  agentic_devtools/cli/ci/reconciliation/reliability_metrics.py,sha256=rUcdv9YBJ-EdxZcY_ae3fQVhP5eYIGA-1bCcJAmEpFY,2635
425
426
  agentic_devtools/cli/ci/reconciliation/repository.py,sha256=0PT6KSzU1vYANQ-rfDonHY_FqBuE5K3m5HWkjBkxk38,11345
426
427
  agentic_devtools/cli/ci/reconciliation/rollout.py,sha256=CgS7zKmlkRWt1vHPEcry4kPcuEWegO0YjJmbV3hODxk,747
@@ -1335,8 +1336,8 @@ agentic_devtools/_bundled_skills/skills/speckit-plan/SKILL.md,sha256=qYLpzgLCIZ6
1335
1336
  agentic_devtools/_bundled_skills/skills/speckit-specify/SKILL.md,sha256=HbHRbdphMqbtNw6fL6NcYCj6sSFmUyk2S4U0bZ9p_l4,13681
1336
1337
  agentic_devtools/_bundled_skills/skills/write-github-commit-message/SKILL.md,sha256=Ep1lR8NDN117Iytj172VZgqazFiLpJ56Z7RXgaTnxR8,2626
1337
1338
  agentic_devtools/_bundled_skills/skills/write-github-commit-message/commit-types.md,sha256=bTy_t68ZD6R87rFIzq9wybTu8Wudoahb7nB9IWC4bFo,1839
1338
- agentic_devtools-0.2.641.dist-info/METADATA,sha256=t1ciUEPOijshlgXqDDEB9teJPyFa1Ecz11Yssdjn0ns,35594
1339
- agentic_devtools-0.2.641.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
1340
- agentic_devtools-0.2.641.dist-info/entry_points.txt,sha256=oHUiF-YvDtXSMTUh0E2bwYKGn4hZlIVbBRaQGSFXASc,13696
1341
- agentic_devtools-0.2.641.dist-info/licenses/LICENSE,sha256=yBEDdICksxhBYLWoERKp9MTqwGnUF6Ryj9BTLwXTc6k,1082
1342
- agentic_devtools-0.2.641.dist-info/RECORD,,
1339
+ agentic_devtools-0.2.643.dist-info/METADATA,sha256=O3-6jQjHwlDolIe-GbxvlWnXOyim6wTQe8uH8z42eqw,35594
1340
+ agentic_devtools-0.2.643.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
1341
+ agentic_devtools-0.2.643.dist-info/entry_points.txt,sha256=oHUiF-YvDtXSMTUh0E2bwYKGn4hZlIVbBRaQGSFXASc,13696
1342
+ agentic_devtools-0.2.643.dist-info/licenses/LICENSE,sha256=yBEDdICksxhBYLWoERKp9MTqwGnUF6Ryj9BTLwXTc6k,1082
1343
+ agentic_devtools-0.2.643.dist-info/RECORD,,