claude-dev-env 4.2.0 → 4.3.0

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 (78) hide show
  1. package/.agents/skills/_shared/pr-loop/scripts/durable_post_lint.py +242 -0
  2. package/.agents/skills/_shared/pr-loop/scripts/skills_pr_loop_constants/durable_post_lint_constants.py +106 -0
  3. package/.agents/skills/_shared/pr-loop/scripts/test_durable_post_lint.py +332 -0
  4. package/.agents/skills/_shared/pr-loop/scripts/test_durable_post_lint_constants.py +25 -0
  5. package/.agents/skills/issue-tracker/SKILL.md +6 -0
  6. package/.agents/skills/pull-request/SKILL.md +218 -0
  7. package/.agents/skills/pull-request/reference/publication-tasks.md +18 -0
  8. package/.agents/skills/pull-request/scripts/github_pr_command_constants/__init__.py +1 -0
  9. package/.agents/skills/pull-request/scripts/github_pr_command_constants/config/__init__.py +1 -0
  10. package/.agents/skills/pull-request/scripts/github_pr_command_constants/config/constants.py +61 -0
  11. package/.agents/skills/pull-request/scripts/pull_request.py +276 -0
  12. package/.agents/skills/pull-request/scripts/recover_legacy_author.py +251 -0
  13. package/.agents/skills/pull-request/scripts/test_github_pr_command_constants.py +49 -0
  14. package/.agents/skills/pull-request/scripts/test_pull_request.py +398 -0
  15. package/.agents/skills/pull-request/scripts/test_recover_legacy_author.py +221 -0
  16. package/.agents/skills/test-runner/SKILL.md +69 -0
  17. package/.agents/skills/test-runner/scripts/preflight_checks.py +365 -0
  18. package/.agents/skills/test-runner/scripts/run_tests.py +316 -0
  19. package/.agents/skills/test-runner/scripts/test_preflight_checks.py +185 -0
  20. package/.agents/skills/test-runner/scripts/test_run_tests.py +281 -0
  21. package/.agents/skills/test-runner/scripts/test_runner_constants/__init__.py +1 -0
  22. package/.agents/skills/test-runner/scripts/test_runner_constants/config/__init__.py +1 -0
  23. package/.agents/skills/test-runner/scripts/test_runner_constants/config/constants.py +96 -0
  24. package/.agents/skills-archived/pr-loop-cloud-transport/reference/identity-and-hooks.md +1 -1
  25. package/bin/ever-shipped-skills.mjs +2 -0
  26. package/bin/ever-shipped-skills.test.mjs +8 -0
  27. package/bin/install.mjs +9 -1
  28. package/bin/install.prune.test.mjs +90 -0
  29. package/bin/install.test.mjs +24 -7
  30. package/hooks/blocking/pii_prevention_blocker.py +32 -51
  31. package/hooks/blocking/test_bash_post_call_dispatcher.py +5 -28
  32. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +1 -4
  33. package/hooks/blocking/test_code_rules_command_dispatch.py +2 -2
  34. package/hooks/blocking/test_pii_prevention_blocker.py +37 -89
  35. package/hooks/gh_post_body_texts.py +195 -0
  36. package/hooks/hooks.json +0 -15
  37. package/hooks/hooks_constants/bash_post_call_dispatcher_constants.py +0 -1
  38. package/hooks/hooks_constants/bash_pre_tool_use_dispatcher_constants.py +0 -8
  39. package/hooks/hooks_constants/gh_post_body_texts_constants.py +12 -0
  40. package/hooks/hooks_constants/test_bash_post_call_dispatcher_constants.py +0 -7
  41. package/hooks/hooks_constants/test_bash_pre_tool_use_dispatcher_constants.py +0 -7
  42. package/hooks/hooks_constants/test_failure_recorder_constants.py +3 -3
  43. package/hooks/hooks_constants/test_gh_post_body_texts_constants.py +19 -0
  44. package/hooks/observability/test_failure_recorder.py +1 -1
  45. package/hooks/pyproject.toml +1 -1
  46. package/hooks/test_gh_post_body_texts.py +79 -0
  47. package/package.json +1 -1
  48. package/rules/durable-post-artifacts.md +31 -20
  49. package/rules/gh-cli-conventions.md +23 -13
  50. package/rules/git-workflow.md +21 -8
  51. package/scripts/policy_lint/adapter_configuration.py +53 -12
  52. package/scripts/repository_checks/config/constants.py +0 -5
  53. package/scripts/tests/test_adapter_configuration.py +54 -0
  54. package/hooks/_gh_pr_author_swap_utils.py +0 -1225
  55. package/hooks/blocking/conventional_pr_title_gate.py +0 -443
  56. package/hooks/blocking/gh_body_arg_blocker.py +0 -176
  57. package/hooks/blocking/gh_pr_author_enforcer.py +0 -487
  58. package/hooks/blocking/gh_pr_author_restore.py +0 -105
  59. package/hooks/blocking/pr_description_writer_gate.py +0 -256
  60. package/hooks/blocking/test_conventional_pr_title_gate.py +0 -640
  61. package/hooks/blocking/test_gh_body_arg_blocker.py +0 -441
  62. package/hooks/blocking/test_gh_pr_author_enforcer.py +0 -1166
  63. package/hooks/blocking/test_gh_pr_author_restore.py +0 -513
  64. package/hooks/blocking/test_gh_pr_author_swap_utils.py +0 -910
  65. package/hooks/blocking/test_pr_description_writer_gate.py +0 -234
  66. package/hooks/blocking/test_preflight_check.py +0 -343
  67. package/hooks/blocking/test_test_preflight_check.py +0 -80
  68. package/hooks/blocking/test_volatile_path_in_post_blocker.py +0 -322
  69. package/hooks/blocking/volatile_path_in_post_blocker.py +0 -461
  70. package/hooks/hooks_constants/conventional_pr_title_gate_constants.py +0 -58
  71. package/hooks/hooks_constants/gh_pr_author_swap_constants.py +0 -76
  72. package/hooks/hooks_constants/pr_description_writer_gate_constants.py +0 -73
  73. package/hooks/hooks_constants/volatile_path_in_post_blocker_constants.py +0 -55
  74. package/hooks/observability/pr_description_writer_spawn_tracker.py +0 -113
  75. package/hooks/observability/test_pr_description_writer_spawn_tracker.py +0 -150
  76. package/hooks/session/gh_pr_author_session_cleanup.py +0 -175
  77. package/hooks/session/test_gh_pr_author_session_cleanup.py +0 -576
  78. package/hooks/test__gh_pr_author_swap_utils.py +0 -333
@@ -0,0 +1,251 @@
1
+ """Restore one explicitly selected legacy GitHub author-swap record."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import stat
9
+ import subprocess
10
+ import sys
11
+ import time
12
+ from collections.abc import Callable, Sequence
13
+ from pathlib import Path
14
+
15
+ from github_pr_command_constants.config.constants import (
16
+ ALL_GH_AUTH_SWITCH_COMMAND_HEAD,
17
+ LEGACY_RECORD_ACTIVE_MESSAGE,
18
+ LEGACY_RECORD_CHANGED_MESSAGE,
19
+ LEGACY_RECORD_CONFIRMATION_MESSAGE,
20
+ LEGACY_RECORD_INACTIVE_CONFIRMATION_FLAG,
21
+ LEGACY_RECORD_NAME_PATTERN,
22
+ LEGACY_RECORD_ORIGINAL_ACCOUNT_KEY,
23
+ LEGACY_RECORD_PERMISSION_MODE,
24
+ LEGACY_RECORD_REJECTED_MESSAGE,
25
+ LEGACY_RECORD_STALE_AGE_SECONDS,
26
+ LEGACY_RESTORE_FAILED_MESSAGE,
27
+ RECOVERY_CLEAN_EXIT_CODE,
28
+ RECOVERY_FAILED_EXIT_CODE,
29
+ RECOVERY_REJECTED_EXIT_CODE,
30
+ RECOVERY_UNRESOLVED_EXIT_CODE,
31
+ )
32
+
33
+ CommandRunner = Callable[..., subprocess.CompletedProcess[str]]
34
+ FileFingerprint = tuple[int, int, int, int, int]
35
+ VerifiedRecord = tuple[str, FileFingerprint]
36
+
37
+
38
+ class LegacyRecordRejected(ValueError):
39
+ """Report an invalid legacy state record."""
40
+
41
+
42
+ class LegacyRecordActive(ValueError):
43
+ """Report a legacy state record that is not old enough for recovery."""
44
+
45
+
46
+ class LegacyRecordChanged(ValueError):
47
+ """Report a legacy state record that changed during recovery."""
48
+
49
+
50
+ def _build_parser() -> argparse.ArgumentParser:
51
+ parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
52
+ parser.add_argument("state_file", type=Path)
53
+ parser.add_argument(LEGACY_RECORD_INACTIVE_CONFIRMATION_FLAG, action="store_true")
54
+ return parser
55
+
56
+
57
+ def _posix_metadata_is_secure(
58
+ file_mode: int,
59
+ file_owner_id: int,
60
+ current_user_id: int | None,
61
+ ) -> bool:
62
+ if not stat.S_ISREG(file_mode):
63
+ return False
64
+ if current_user_id is None:
65
+ return True
66
+ return (
67
+ stat.S_IMODE(file_mode) == LEGACY_RECORD_PERMISSION_MODE
68
+ and file_owner_id == current_user_id
69
+ )
70
+
71
+
72
+ def _secure_metadata(
73
+ state_file: Path,
74
+ current_user_id: int | None,
75
+ ) -> os.stat_result:
76
+ try:
77
+ file_metadata = state_file.lstat()
78
+ except OSError as error:
79
+ raise LegacyRecordRejected from error
80
+ if not _posix_metadata_is_secure(
81
+ file_metadata.st_mode,
82
+ file_metadata.st_uid,
83
+ current_user_id,
84
+ ):
85
+ raise LegacyRecordRejected
86
+ return file_metadata
87
+
88
+
89
+ def _fingerprint(file_metadata: os.stat_result) -> FileFingerprint:
90
+ return (
91
+ file_metadata.st_dev,
92
+ file_metadata.st_ino,
93
+ file_metadata.st_mode,
94
+ file_metadata.st_size,
95
+ file_metadata.st_mtime_ns,
96
+ )
97
+
98
+
99
+ def _parse_original_account(record_text: str) -> str:
100
+ try:
101
+ decoded_record = json.loads(record_text)
102
+ except json.JSONDecodeError as error:
103
+ raise LegacyRecordRejected from error
104
+ if not isinstance(decoded_record, dict):
105
+ raise LegacyRecordRejected
106
+ if set(decoded_record) != {LEGACY_RECORD_ORIGINAL_ACCOUNT_KEY}:
107
+ raise LegacyRecordRejected
108
+ original_account = decoded_record[LEGACY_RECORD_ORIGINAL_ACCOUNT_KEY]
109
+ if not isinstance(original_account, str) or not original_account.strip():
110
+ raise LegacyRecordRejected
111
+ return original_account.strip()
112
+
113
+
114
+ def _read_verified_record(
115
+ state_file: Path,
116
+ now_seconds: float,
117
+ current_user_id: int | None,
118
+ ) -> VerifiedRecord:
119
+ if LEGACY_RECORD_NAME_PATTERN.fullmatch(state_file.name) is None:
120
+ raise LegacyRecordRejected
121
+ initial_metadata = _secure_metadata(state_file, current_user_id)
122
+ if now_seconds - initial_metadata.st_mtime < LEGACY_RECORD_STALE_AGE_SECONDS:
123
+ raise LegacyRecordActive
124
+ try:
125
+ record_text = state_file.read_text(encoding="utf-8")
126
+ except (OSError, UnicodeError) as error:
127
+ raise LegacyRecordRejected from error
128
+ original_account = _parse_original_account(record_text)
129
+ initial_fingerprint = _fingerprint(initial_metadata)
130
+ verified_metadata = _secure_metadata(state_file, current_user_id)
131
+ if _fingerprint(verified_metadata) != initial_fingerprint:
132
+ raise LegacyRecordChanged
133
+ return original_account, initial_fingerprint
134
+
135
+
136
+ def _delete_unchanged_record(
137
+ state_file: Path,
138
+ expected_fingerprint: FileFingerprint,
139
+ current_user_id: int | None,
140
+ ) -> None:
141
+ current_metadata = _secure_metadata(state_file, current_user_id)
142
+ if _fingerprint(current_metadata) != expected_fingerprint:
143
+ raise LegacyRecordChanged
144
+ try:
145
+ state_file.unlink()
146
+ except OSError as error:
147
+ raise LegacyRecordChanged from error
148
+
149
+
150
+ def _load_record_with_diagnostics(
151
+ state_file: Path,
152
+ now_seconds: float,
153
+ current_user_id: int | None,
154
+ ) -> tuple[VerifiedRecord | None, int]:
155
+ try:
156
+ return _read_verified_record(state_file, now_seconds, current_user_id), 0
157
+ except LegacyRecordActive:
158
+ sys.stderr.write(LEGACY_RECORD_ACTIVE_MESSAGE)
159
+ return None, RECOVERY_REJECTED_EXIT_CODE
160
+ except LegacyRecordChanged:
161
+ sys.stderr.write(LEGACY_RECORD_CHANGED_MESSAGE)
162
+ return None, RECOVERY_FAILED_EXIT_CODE
163
+ except LegacyRecordRejected:
164
+ sys.stderr.write(LEGACY_RECORD_REJECTED_MESSAGE)
165
+ return None, RECOVERY_REJECTED_EXIT_CODE
166
+
167
+
168
+ def _restore_and_delete(
169
+ state_file: Path,
170
+ verified_record: VerifiedRecord,
171
+ current_user_id: int | None,
172
+ command_runner: CommandRunner,
173
+ ) -> int:
174
+ original_account, expected_fingerprint = verified_record
175
+ try:
176
+ completed_restore = command_runner(
177
+ [*ALL_GH_AUTH_SWITCH_COMMAND_HEAD, original_account],
178
+ capture_output=True,
179
+ check=False,
180
+ shell=False,
181
+ text=True,
182
+ )
183
+ except OSError:
184
+ sys.stderr.write(LEGACY_RESTORE_FAILED_MESSAGE)
185
+ return RECOVERY_FAILED_EXIT_CODE
186
+ if completed_restore.returncode != 0:
187
+ sys.stderr.write(LEGACY_RESTORE_FAILED_MESSAGE)
188
+ return RECOVERY_FAILED_EXIT_CODE
189
+ try:
190
+ _delete_unchanged_record(state_file, expected_fingerprint, current_user_id)
191
+ except (LegacyRecordChanged, LegacyRecordRejected):
192
+ sys.stderr.write(LEGACY_RECORD_CHANGED_MESSAGE)
193
+ return RECOVERY_FAILED_EXIT_CODE
194
+ return RECOVERY_CLEAN_EXIT_CODE
195
+
196
+
197
+ def _recover_selected_record(
198
+ state_file: Path,
199
+ now_seconds: float,
200
+ current_user_id: int | None,
201
+ command_runner: CommandRunner,
202
+ ) -> int:
203
+ verified_record, exit_code = _load_record_with_diagnostics(
204
+ state_file, now_seconds, current_user_id
205
+ )
206
+ if verified_record is None:
207
+ return exit_code
208
+ return _restore_and_delete(
209
+ state_file, verified_record, current_user_id, command_runner
210
+ )
211
+
212
+
213
+ def main(
214
+ all_arguments: Sequence[str],
215
+ *,
216
+ now_seconds: float,
217
+ current_user_id: int | None,
218
+ command_runner: CommandRunner,
219
+ ) -> int:
220
+ """Recover one confirmed-inactive legacy state record.
221
+
222
+ Args:
223
+ all_arguments: Command arguments after the script name.
224
+ now_seconds: Current wall-clock time in seconds.
225
+ current_user_id: Current POSIX user identifier, or None on Windows.
226
+ command_runner: Process runner used by tests and production.
227
+
228
+ Returns:
229
+ Zero on success, one on failure, two on rejection, or three when unresolved.
230
+ """
231
+ arguments = _build_parser().parse_args(list(all_arguments))
232
+ if not arguments.confirm_inactive:
233
+ sys.stderr.write(LEGACY_RECORD_CONFIRMATION_MESSAGE)
234
+ return RECOVERY_UNRESOLVED_EXIT_CODE
235
+ return _recover_selected_record(
236
+ arguments.state_file,
237
+ now_seconds,
238
+ current_user_id,
239
+ command_runner,
240
+ )
241
+
242
+
243
+ if __name__ == "__main__":
244
+ raise SystemExit(
245
+ main(
246
+ sys.argv[1:],
247
+ now_seconds=time.time(),
248
+ current_user_id=os.getuid() if hasattr(os, "getuid") else None,
249
+ command_runner=subprocess.run,
250
+ )
251
+ )
@@ -0,0 +1,49 @@
1
+ """Tests for explicit GitHub pull request command constants."""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ _SCRIPTS_DIRECTORY = Path(__file__).resolve().parent
7
+ if str(_SCRIPTS_DIRECTORY) not in sys.path:
8
+ sys.path.insert(0, str(_SCRIPTS_DIRECTORY))
9
+
10
+ from github_pr_command_constants.config import constants
11
+
12
+
13
+ def test_action_and_linter_mappings_are_complete() -> None:
14
+ assert constants.ALL_LINTER_ACTIONS_BY_COMMAND == {
15
+ constants.ACTION_COMMENT: constants.LINTER_ACTION_COMMENT,
16
+ constants.ACTION_CREATE: constants.LINTER_ACTION_CREATE,
17
+ constants.ACTION_EDIT: constants.LINTER_ACTION_EDIT,
18
+ constants.ACTION_REVIEW: constants.LINTER_ACTION_REVIEW,
19
+ }
20
+
21
+
22
+ def test_review_event_flags_are_complete() -> None:
23
+ assert constants.ALL_REVIEW_FLAGS_BY_EVENT == {
24
+ constants.REVIEW_EVENT_APPROVE: "--approve",
25
+ constants.REVIEW_EVENT_COMMENT: "--comment",
26
+ constants.REVIEW_EVENT_REQUEST_CHANGES: "--request-changes",
27
+ }
28
+
29
+
30
+ def test_account_boundary_constants_are_safe_and_stable() -> None:
31
+ assert constants.SELECTED_ACCOUNT_ENVIRONMENT_KEY == "GITHUB_DEFAULT_ACCOUNT"
32
+ assert constants.ACCOUNT_LOOKUP_FAILURE_EXIT_CODE == 1
33
+ assert constants.ACCOUNT_LOOKUP_FAILED_MESSAGE.endswith("lookup failed\n")
34
+ assert constants.ACCOUNT_LOOKUP_EMPTY_MESSAGE.endswith("returned no value\n")
35
+
36
+
37
+ def test_legacy_recovery_constants_define_one_record_boundary() -> None:
38
+ assert constants.ALL_GH_AUTH_SWITCH_COMMAND_HEAD == (
39
+ "gh",
40
+ "auth",
41
+ "switch",
42
+ "--user",
43
+ )
44
+ assert constants.LEGACY_RECORD_NAME_PATTERN.fullmatch(
45
+ "gh_pr_author_swap_session-a.json"
46
+ )
47
+ assert not constants.LEGACY_RECORD_NAME_PATTERN.fullmatch("other.json")
48
+ assert constants.LEGACY_RECORD_STALE_AGE_SECONDS == 1800
49
+ assert constants.RECOVERY_UNRESOLVED_EXIT_CODE == 3
@@ -0,0 +1,398 @@
1
+ """Contract tests for process-local pull request publication."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ import threading
9
+ from collections.abc import Callable
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from pathlib import Path
12
+ from unittest.mock import Mock
13
+
14
+ import pytest
15
+
16
+ _SCRIPTS_DIRECTORY = Path(__file__).resolve().parent
17
+ if str(_SCRIPTS_DIRECTORY) not in sys.path:
18
+ sys.path.insert(0, str(_SCRIPTS_DIRECTORY))
19
+
20
+ import pull_request
21
+
22
+ REPOSITORY = "jl-cmd/claude-dev-env"
23
+ PR_NUMBER = "2518"
24
+ PR_TITLE = "feat(skills): add guarded pull request publication"
25
+ ACCOUNT_A = "JonEcho"
26
+ ACCOUNT_B = "ReviewBot"
27
+ BODY_FILENAME = "pull-request-body.md"
28
+ LINTER_PATH = (
29
+ _SCRIPTS_DIRECTORY.parents[1] / "_shared/pr-loop/scripts/durable_post_lint.py"
30
+ )
31
+ COMMENT_CLI = ["comment", "--repo", REPOSITORY, "--number", PR_NUMBER, "--body-file"]
32
+ ACTION_CASES = [
33
+ (
34
+ [
35
+ "create",
36
+ "--repo",
37
+ REPOSITORY,
38
+ "--base",
39
+ "main",
40
+ "--head",
41
+ "feature/post",
42
+ "--title",
43
+ PR_TITLE,
44
+ "--body-file",
45
+ BODY_FILENAME,
46
+ ],
47
+ "pr-create",
48
+ [
49
+ "gh",
50
+ "pr",
51
+ "create",
52
+ "--draft",
53
+ "--repo",
54
+ REPOSITORY,
55
+ "--base",
56
+ "main",
57
+ "--head",
58
+ "feature/post",
59
+ "--title",
60
+ PR_TITLE,
61
+ "--body-file",
62
+ BODY_FILENAME,
63
+ ],
64
+ ),
65
+ (
66
+ [
67
+ "edit",
68
+ "--repo",
69
+ REPOSITORY,
70
+ "--number",
71
+ PR_NUMBER,
72
+ "--title",
73
+ PR_TITLE,
74
+ "--body-file",
75
+ BODY_FILENAME,
76
+ ],
77
+ "pr-edit",
78
+ [
79
+ "gh",
80
+ "pr",
81
+ "edit",
82
+ PR_NUMBER,
83
+ "--repo",
84
+ REPOSITORY,
85
+ "--title",
86
+ PR_TITLE,
87
+ "--body-file",
88
+ BODY_FILENAME,
89
+ ],
90
+ ),
91
+ (
92
+ [*COMMENT_CLI, BODY_FILENAME],
93
+ "pr-comment",
94
+ [
95
+ "gh",
96
+ "pr",
97
+ "comment",
98
+ PR_NUMBER,
99
+ "--repo",
100
+ REPOSITORY,
101
+ "--body-file",
102
+ BODY_FILENAME,
103
+ ],
104
+ ),
105
+ (
106
+ [
107
+ "review",
108
+ "--repo",
109
+ REPOSITORY,
110
+ "--number",
111
+ PR_NUMBER,
112
+ "--body-file",
113
+ BODY_FILENAME,
114
+ ],
115
+ "pr-review",
116
+ [
117
+ "gh",
118
+ "pr",
119
+ "review",
120
+ PR_NUMBER,
121
+ "--repo",
122
+ REPOSITORY,
123
+ "--comment",
124
+ "--body-file",
125
+ BODY_FILENAME,
126
+ ],
127
+ ),
128
+ ]
129
+
130
+
131
+ def _completion(
132
+ all_arguments: list[str], code: int = 0, stdout: str = "", stderr: str = ""
133
+ ) -> subprocess.CompletedProcess[str]:
134
+ return subprocess.CompletedProcess(all_arguments, code, stdout, stderr)
135
+
136
+
137
+ @pytest.fixture
138
+ def body_file(tmp_path: Path) -> Path:
139
+ post_file = tmp_path / BODY_FILENAME
140
+ post_file.write_text("Durable body text.", encoding="utf-8")
141
+ return post_file
142
+
143
+
144
+ def _comment_arguments(body_file: Path) -> list[str]:
145
+ return [*COMMENT_CLI, str(body_file)]
146
+
147
+
148
+ def _account_text(account_name: str) -> str:
149
+ return account_name[::-1]
150
+
151
+
152
+ def _calls(command_runner: Mock) -> list[list[str]]:
153
+ return [each_call.args[0] for each_call in command_runner.call_args_list]
154
+
155
+
156
+ def _run_comment(
157
+ body_file: Path, command_runner: Mock, environment: dict[str, str]
158
+ ) -> int:
159
+ return pull_request.main(
160
+ _comment_arguments(body_file),
161
+ all_environment=environment,
162
+ command_runner=command_runner,
163
+ )
164
+
165
+
166
+ def _account_runner(
167
+ *, auth_code: int = 0, auth_stdout: str, action_code: int = 0, auth_stderr: str = ""
168
+ ) -> Mock:
169
+ return Mock(
170
+ side_effect=[
171
+ _completion([]),
172
+ _completion([], auth_code, auth_stdout, auth_stderr),
173
+ _completion([], action_code),
174
+ ]
175
+ )
176
+
177
+
178
+ @pytest.mark.parametrize(
179
+ ("all_cli_arguments", "linter_action", "expected_gh"), ACTION_CASES
180
+ )
181
+ def test_actions_run_exact_linter_then_gh_arguments(
182
+ all_cli_arguments: list[str], linter_action: str, expected_gh: list[str]
183
+ ) -> None:
184
+ command_runner = Mock(side_effect=[_completion([]), _completion([])])
185
+ exit_code = pull_request.main(
186
+ all_cli_arguments, all_environment={}, command_runner=command_runner
187
+ )
188
+ title_arguments = ["--title", PR_TITLE] if "--title" in all_cli_arguments else []
189
+ expected_linter = [
190
+ sys.executable,
191
+ str(LINTER_PATH),
192
+ "--action",
193
+ linter_action,
194
+ *title_arguments,
195
+ "--body-file",
196
+ BODY_FILENAME,
197
+ ]
198
+ assert exit_code == 0
199
+ assert _calls(command_runner) == [expected_linter, expected_gh]
200
+
201
+
202
+ def test_body_transport_uses_files_only(body_file: Path) -> None:
203
+ command_runner = Mock(side_effect=[_completion([]), _completion([])])
204
+ assert _run_comment(body_file, command_runner, {}) == 0
205
+ for each_command in _calls(command_runner):
206
+ assert "--body-file" in each_command
207
+ assert "--body" not in each_command
208
+ assert "Durable body text." not in each_command
209
+
210
+
211
+ def test_linter_failure_stops_credential_lookup_and_action(body_file: Path) -> None:
212
+ command_runner = Mock(return_value=_completion([], 1))
213
+ exit_code = _run_comment(
214
+ body_file, command_runner, {"GITHUB_DEFAULT_ACCOUNT": ACCOUNT_A}
215
+ )
216
+ assert exit_code == 1
217
+ assert command_runner.call_count == 1
218
+ assert Path(_calls(command_runner)[0][1]).name == "durable_post_lint.py"
219
+
220
+
221
+ def test_account_lookup_scopes_action_environment(body_file: Path) -> None:
222
+ account_text = _account_text(ACCOUNT_A)
223
+ command_runner = _account_runner(auth_stdout=f"{account_text}\n")
224
+ parent_environment = {
225
+ "GITHUB_DEFAULT_ACCOUNT": ACCOUNT_A,
226
+ "GITHUB_TOKEN": "parent-setting",
227
+ "UNCHANGED": "same",
228
+ }
229
+ assert _run_comment(body_file, command_runner, parent_environment) == 0
230
+ assert _calls(command_runner)[1] == ["gh", "auth", "token", "--user", ACCOUNT_A]
231
+ action_environment = command_runner.call_args_list[2].kwargs["env"]
232
+ assert action_environment["GH_TOKEN"] == account_text
233
+ assert "GITHUB_TOKEN" not in action_environment
234
+ assert action_environment["UNCHANGED"] == "same"
235
+
236
+
237
+ def test_absent_account_uses_copied_parent_environment(body_file: Path) -> None:
238
+ command_runner = Mock(side_effect=[_completion([]), _completion([])])
239
+ parent_environment = {"GITHUB_TOKEN": "parent-setting", "UNCHANGED": "same"}
240
+ assert _run_comment(body_file, command_runner, parent_environment) == 0
241
+ action_environment = command_runner.call_args_list[1].kwargs["env"]
242
+ assert action_environment == parent_environment
243
+ assert action_environment is not parent_environment
244
+ assert command_runner.call_count == 2
245
+
246
+
247
+ def test_token_lookup_failure_prints_generic_safe_stderr(
248
+ body_file: Path, capsys: pytest.CaptureFixture[str]
249
+ ) -> None:
250
+ account_text = _account_text(ACCOUNT_A)
251
+ command_runner = _account_runner(
252
+ auth_code=1, auth_stdout=account_text, auth_stderr=f"unsafe {account_text}"
253
+ )
254
+ exit_code = _run_comment(
255
+ body_file, command_runner, {"GITHUB_DEFAULT_ACCOUNT": ACCOUNT_A}
256
+ )
257
+ captured = capsys.readouterr()
258
+ assert exit_code == 1
259
+ assert captured.err == "error: GitHub account lookup failed\n"
260
+ assert account_text not in captured.out + captured.err
261
+ assert command_runner.call_count == 2
262
+ command_runner = Mock(side_effect=[_completion([]), OSError("unavailable")])
263
+ assert (
264
+ _run_comment(body_file, command_runner, {"GITHUB_DEFAULT_ACCOUNT": ACCOUNT_A})
265
+ == 1
266
+ )
267
+ assert capsys.readouterr().err == "error: GitHub account lookup failed\n"
268
+
269
+
270
+ def test_empty_account_token_stops_before_action(
271
+ body_file: Path, capsys: pytest.CaptureFixture[str]
272
+ ) -> None:
273
+ command_runner = _account_runner(auth_stdout=" \n")
274
+ exit_code = _run_comment(
275
+ body_file, command_runner, {"GITHUB_DEFAULT_ACCOUNT": ACCOUNT_A}
276
+ )
277
+ captured = capsys.readouterr()
278
+ assert exit_code == 1
279
+ assert captured.err == "error: GitHub account lookup returned no value\n"
280
+ assert command_runner.call_count == 2
281
+
282
+
283
+ def test_action_child_results_pass_through_or_report_safely(
284
+ body_file: Path, capsys: pytest.CaptureFixture[str]
285
+ ) -> None:
286
+ command_runner = Mock(side_effect=[_completion([]), _completion([], 7)])
287
+ assert _run_comment(body_file, command_runner, {}) == 7
288
+ command_runner = Mock(side_effect=[_completion([]), OSError("unavailable")])
289
+ assert _run_comment(body_file, command_runner, {}) == 1
290
+ assert capsys.readouterr().err == "error: GitHub action failed\n"
291
+
292
+
293
+ def test_supplied_parent_environment_remains_unchanged(body_file: Path) -> None:
294
+ command_runner = _account_runner(auth_stdout=_account_text(ACCOUNT_A))
295
+ parent_environment = {
296
+ "GITHUB_DEFAULT_ACCOUNT": ACCOUNT_A,
297
+ "GITHUB_TOKEN": "parent-setting",
298
+ "GH_TOKEN": "parent-setting",
299
+ }
300
+ original_environment = dict(parent_environment)
301
+ assert _run_comment(body_file, command_runner, parent_environment) == 0
302
+ assert parent_environment == original_environment
303
+
304
+
305
+ def test_process_environment_remains_unchanged(
306
+ body_file: Path, monkeypatch: pytest.MonkeyPatch
307
+ ) -> None:
308
+ monkeypatch.setenv("GITHUB_DEFAULT_ACCOUNT", ACCOUNT_A)
309
+ monkeypatch.setenv("GITHUB_TOKEN", "parent-setting")
310
+ monkeypatch.setenv("GH_TOKEN", "parent-setting")
311
+ original_environment = dict(os.environ)
312
+ command_runner = _account_runner(auth_stdout=_account_text(ACCOUNT_A))
313
+ exit_code = pull_request.main(
314
+ _comment_arguments(body_file),
315
+ all_environment=os.environ,
316
+ command_runner=command_runner,
317
+ )
318
+ assert exit_code == 0
319
+ assert dict(os.environ) == original_environment
320
+
321
+
322
+ def _concurrent_runner(
323
+ all_environments: list[dict[str, str]],
324
+ all_commands: list[list[str]],
325
+ record_lock: threading.Lock,
326
+ ) -> Callable[..., subprocess.CompletedProcess[str]]:
327
+ def run_command(
328
+ all_arguments: list[str], **keyword_arguments: object
329
+ ) -> subprocess.CompletedProcess[str]:
330
+ with record_lock:
331
+ all_commands.append(all_arguments)
332
+ if all_arguments[0] == sys.executable:
333
+ return _completion(all_arguments)
334
+ if all_arguments[:3] == ["gh", "auth", "token"]:
335
+ if all_arguments[-1] == ACCOUNT_A:
336
+ return _completion(all_arguments, stdout=_account_text(ACCOUNT_A))
337
+ return _completion(all_arguments, 1)
338
+ child_environment = keyword_arguments["env"]
339
+ assert isinstance(child_environment, dict)
340
+ with record_lock:
341
+ all_environments.append(dict(child_environment))
342
+ return _completion(all_arguments)
343
+
344
+ return run_command
345
+
346
+
347
+ def test_concurrent_accounts_keep_tokens_isolated(body_file: Path) -> None:
348
+ all_environments: list[dict[str, str]] = []
349
+ all_commands: list[list[str]] = []
350
+ command_runner = _concurrent_runner(
351
+ all_environments, all_commands, threading.Lock()
352
+ )
353
+ with ThreadPoolExecutor(max_workers=2) as executor:
354
+ first_run = executor.submit(
355
+ pull_request.main,
356
+ _comment_arguments(body_file),
357
+ all_environment={"GITHUB_DEFAULT_ACCOUNT": ACCOUNT_A},
358
+ command_runner=command_runner,
359
+ )
360
+ second_run = executor.submit(
361
+ pull_request.main,
362
+ _comment_arguments(body_file),
363
+ all_environment={"GITHUB_DEFAULT_ACCOUNT": ACCOUNT_B},
364
+ command_runner=command_runner,
365
+ )
366
+ assert {first_run.result(), second_run.result()} == {0, 1}
367
+ assert len(all_environments) == 1
368
+ assert all_environments[0]["GH_TOKEN"] == _account_text(ACCOUNT_A)
369
+ assert all(
370
+ each_command[:3] != ["gh", "auth", "switch"] for each_command in all_commands
371
+ )
372
+
373
+
374
+ def test_token_never_reaches_captured_output(
375
+ body_file: Path, capsys: pytest.CaptureFixture[str]
376
+ ) -> None:
377
+ account_text = _account_text(ACCOUNT_A)
378
+ command_runner = _account_runner(auth_stdout=f"{account_text}\n")
379
+ assert (
380
+ _run_comment(body_file, command_runner, {"GITHUB_DEFAULT_ACCOUNT": ACCOUNT_A})
381
+ == 0
382
+ )
383
+ captured = capsys.readouterr()
384
+ assert account_text not in captured.out + captured.err
385
+
386
+
387
+ def test_cli_rejects_inline_body(capsys: pytest.CaptureFixture[str]) -> None:
388
+ command_runner = Mock()
389
+ with pytest.raises(SystemExit) as raised_exit:
390
+ pull_request.main(
391
+ [*COMMENT_CLI[:-1], "--body", "Inline body text."],
392
+ all_environment={},
393
+ command_runner=command_runner,
394
+ )
395
+ captured = capsys.readouterr()
396
+ assert raised_exit.value.code == 2
397
+ assert "--body-file" in captured.err
398
+ command_runner.assert_not_called()