prizmkit 1.1.190 → 1.1.192

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 (189) hide show
  1. package/bin/create-prizmkit.js +4 -4
  2. package/bundled/VERSION.json +3 -3
  3. package/bundled/adapters/antigravity/assets/prizmkit-hook.cjs +150 -0
  4. package/bundled/adapters/antigravity/hooks-adapter.js +195 -0
  5. package/bundled/adapters/antigravity/paths.js +14 -0
  6. package/bundled/adapters/antigravity/rules-adapter.js +54 -0
  7. package/bundled/adapters/antigravity/skill-adapter.js +38 -0
  8. package/bundled/adapters/codex/skill-adapter.js +28 -8
  9. package/bundled/adapters/cursor/skill-adapter.js +13 -4
  10. package/bundled/adapters/pi/skill-adapter.js +28 -7
  11. package/bundled/dev-pipeline/.env.example +4 -12
  12. package/bundled/dev-pipeline/README.md +21 -15
  13. package/bundled/dev-pipeline/assets/skill-subagent-integration.md +3 -6
  14. package/bundled/dev-pipeline/prizmkit_runtime/atomic_io.py +48 -0
  15. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +66 -23
  16. package/bundled/dev-pipeline/prizmkit_runtime/cli.py +10 -7
  17. package/bundled/dev-pipeline/prizmkit_runtime/commands.py +2 -21
  18. package/bundled/dev-pipeline/prizmkit_runtime/config.py +29 -70
  19. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +125 -67
  20. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +89 -442
  21. package/bundled/dev-pipeline/prizmkit_runtime/heartbeat.py +93 -49
  22. package/bundled/dev-pipeline/prizmkit_runtime/interoperability.py +1 -3
  23. package/bundled/dev-pipeline/prizmkit_runtime/paths.py +0 -6
  24. package/bundled/dev-pipeline/prizmkit_runtime/platform_detection.py +49 -18
  25. package/bundled/dev-pipeline/prizmkit_runtime/processes.py +206 -151
  26. package/bundled/dev-pipeline/prizmkit_runtime/reset.py +2 -23
  27. package/bundled/dev-pipeline/prizmkit_runtime/reset_preserve.py +15 -134
  28. package/bundled/dev-pipeline/prizmkit_runtime/results.py +25 -0
  29. package/bundled/dev-pipeline/prizmkit_runtime/runner_bookkeeping.py +68 -83
  30. package/bundled/dev-pipeline/prizmkit_runtime/runner_classification.py +15 -5
  31. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +1 -29
  32. package/bundled/dev-pipeline/prizmkit_runtime/runner_prompts.py +0 -2
  33. package/bundled/dev-pipeline/prizmkit_runtime/runner_status.py +7 -2
  34. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +282 -217
  35. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +124 -122
  36. package/bundled/dev-pipeline/prizmkit_runtime/runtime_helper.py +90 -9
  37. package/bundled/dev-pipeline/prizmkit_runtime/sessions.py +369 -154
  38. package/bundled/dev-pipeline/prizmkit_runtime/status.py +3 -3
  39. package/bundled/dev-pipeline/prizmkit_runtime/stream_progress.py +2780 -0
  40. package/bundled/dev-pipeline/prizmkit_runtime/task_checkout.py +27 -101
  41. package/bundled/dev-pipeline/prizmkit_runtime/test_result.py +58 -4
  42. package/bundled/dev-pipeline/scripts/check-session-status.py +43 -19
  43. package/bundled/dev-pipeline/scripts/continuation.py +6 -4
  44. package/bundled/dev-pipeline/scripts/detect-stuck.py +28 -28
  45. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +7 -2
  46. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +7 -2
  47. package/bundled/dev-pipeline/scripts/init-bugfix-pipeline.py +10 -7
  48. package/bundled/dev-pipeline/scripts/init-change-artifact.py +8 -2
  49. package/bundled/dev-pipeline/scripts/init-pipeline.py +14 -69
  50. package/bundled/dev-pipeline/scripts/parse-stream-progress.py +31 -2328
  51. package/bundled/dev-pipeline/scripts/patch-completion-notes.py +4 -24
  52. package/bundled/dev-pipeline/scripts/prompt_framework.py +56 -9
  53. package/bundled/dev-pipeline/scripts/status_common.py +591 -0
  54. package/bundled/dev-pipeline/scripts/update-bug-status.py +85 -463
  55. package/bundled/dev-pipeline/scripts/update-checkpoint.py +227 -65
  56. package/bundled/dev-pipeline/scripts/update-feature-status.py +76 -509
  57. package/bundled/dev-pipeline/scripts/utils.py +10 -15
  58. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +4 -4
  59. package/bundled/dev-pipeline/templates/bug-fix-list-schema.json +7 -0
  60. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +1 -1
  61. package/bundled/dev-pipeline/templates/sections/artifact-manifest.md +1 -1
  62. package/bundled/dev-pipeline/templates/sections/bugfix-phase-manual-verification.md +1 -1
  63. package/bundled/dev-pipeline/templates/sections/bugfix-phase-review.md +1 -1
  64. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +2 -1
  65. package/bundled/dev-pipeline/templates/sections/checkpoint-system.md +1 -1
  66. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-auto.md +1 -1
  67. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-opencli.md +2 -2
  68. package/bundled/dev-pipeline/templates/sections/phase-browser-verification.md +2 -2
  69. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +2 -1
  70. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +1 -1
  71. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +3 -6
  72. package/bundled/dev-pipeline/templates/session-status-schema.json +2 -5
  73. package/bundled/dev-pipeline/tests/_helpers.py +418 -0
  74. package/bundled/dev-pipeline/tests/conftest.py +45 -1
  75. package/bundled/dev-pipeline/tests/live_ai_cli_log_smoke.py +1 -0
  76. package/bundled/dev-pipeline/tests/test_auto_skip.py +4 -69
  77. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +126 -1
  78. package/bundled/dev-pipeline/tests/test_daemon_and_scripts.py +257 -0
  79. package/bundled/dev-pipeline/tests/test_e2e_pipeline_run.py +500 -0
  80. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +59 -117
  81. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +12 -10
  82. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +561 -3094
  83. package/bundled/dev-pipeline/tests/test_recovery_workflow.py +7 -8
  84. package/bundled/dev-pipeline/tests/test_repository_bootstrap.py +0 -1
  85. package/bundled/dev-pipeline/tests/test_reset_modes.py +15 -27
  86. package/bundled/dev-pipeline/tests/test_reset_preserve.py +54 -139
  87. package/bundled/dev-pipeline/tests/test_runner_bookkeeping.py +766 -0
  88. package/bundled/dev-pipeline/tests/test_runner_lifecycle.py +1257 -0
  89. package/bundled/dev-pipeline/tests/test_runtime_helper.py +97 -20
  90. package/bundled/dev-pipeline/tests/test_session_launch.py +1101 -0
  91. package/bundled/dev-pipeline/tests/test_stream_progress.py +585 -0
  92. package/bundled/dev-pipeline/tests/test_unified_cli.py +490 -2006
  93. package/bundled/dev-pipeline/tests/test_utils.py +3 -3
  94. package/bundled/rules/USAGE.md +1 -0
  95. package/bundled/skills/_metadata.json +9 -63
  96. package/bundled/skills/app-planner/SKILL.md +32 -303
  97. package/bundled/skills/app-planner/references/app-design-guide.md +0 -4
  98. package/bundled/skills/app-planner/references/generated-plan-review.md +2 -1
  99. package/bundled/skills/app-planner/references/project-brief-guide.md +14 -0
  100. package/bundled/skills/app-planner/references/project-conventions-discovery.md +4 -6
  101. package/bundled/skills/app-planner/references/project-state-detection.md +2 -3
  102. package/bundled/skills/bug-fix-workflow/SKILL.md +1 -2
  103. package/bundled/skills/bug-fix-workflow/references/bug-diagnosis.md +4 -7
  104. package/bundled/skills/bug-planner/SKILL.md +54 -435
  105. package/bundled/skills/bug-planner/references/generated-plan-review.md +3 -2
  106. package/bundled/skills/bug-planner/references/input-formats.md +32 -0
  107. package/bundled/skills/bugfix-pipeline-launcher/SKILL.md +4 -6
  108. package/bundled/skills/bugfix-pipeline-launcher/references/configuration.md +4 -28
  109. package/bundled/skills/feature-pipeline-launcher/SKILL.md +4 -6
  110. package/bundled/skills/feature-pipeline-launcher/references/configuration.md +4 -28
  111. package/bundled/skills/feature-planner/SKILL.md +60 -439
  112. package/bundled/skills/feature-planner/assets/planning-guide.md +1 -1
  113. package/bundled/skills/feature-planner/references/completeness-review.md +34 -0
  114. package/bundled/skills/feature-planner/references/decomposition-patterns.md +2 -2
  115. package/bundled/skills/feature-planner/references/error-recovery.md +1 -1
  116. package/bundled/skills/feature-planner/references/generated-plan-review.md +3 -2
  117. package/bundled/skills/feature-planner/references/incremental-feature-planning.md +3 -1
  118. package/bundled/skills/feature-workflow/SKILL.md +1 -2
  119. package/bundled/skills/prizmkit/SKILL.md +7 -1
  120. package/bundled/skills/prizmkit-code-review/SKILL.md +14 -6
  121. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +7 -4
  122. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +16 -0
  123. package/bundled/skills/prizmkit-code-review/scripts/render_review_report.py +58 -20
  124. package/bundled/skills/prizmkit-implement/SKILL.md +1 -1
  125. package/bundled/skills/prizmkit-init/SKILL.md +25 -128
  126. package/bundled/skills/prizmkit-init/assets/project-brief-template.md +3 -3
  127. package/bundled/skills/prizmkit-init/references/config-schema.md +2 -2
  128. package/bundled/skills/prizmkit-plan/SKILL.md +6 -8
  129. package/bundled/skills/prizmkit-plan/references/clarify-guide.md +1 -1
  130. package/bundled/skills/prizmkit-plan/references/independent-plan-review.md +5 -2
  131. package/bundled/skills/prizmkit-plan/references/review-plan-spec-loop.md +6 -5
  132. package/bundled/skills/prizmkit-prizm-docs/SKILL.md +1 -13
  133. package/bundled/skills/prizmkit-prizm-docs/assets/prizm-docs-format.md +1 -1
  134. package/bundled/skills/prizmkit-prizm-docs/references/op-init.md +1 -1
  135. package/bundled/skills/prizmkit-prizm-docs/references/op-update.md +1 -1
  136. package/bundled/skills/prizmkit-retrospective/SKILL.md +6 -4
  137. package/bundled/skills/prizmkit-test/SKILL.md +25 -133
  138. package/bundled/skills/prizmkit-test/references/independent-test-review.md +5 -2
  139. package/bundled/skills/prizmkit-test/references/test-coverage-model.md +6 -0
  140. package/bundled/skills/prizmkit-workflow/SKILL.md +2 -3
  141. package/bundled/skills/prizmkit-workflow/references/workflow-state-protocol.md +4 -3
  142. package/bundled/skills/recovery-workflow/SKILL.md +7 -7
  143. package/bundled/skills/recovery-workflow/evals/evals.json +1 -1
  144. package/bundled/skills/recovery-workflow/references/detection.md +1 -3
  145. package/bundled/skills/recovery-workflow/scripts/detect-recovery-state.py +0 -6
  146. package/bundled/templates/project-memory-template.md +1 -2
  147. package/package.json +1 -1
  148. package/src/ai-cli-launch.js +1 -1
  149. package/src/clean.js +40 -4
  150. package/src/config.js +64 -4
  151. package/src/detect-platform.js +10 -6
  152. package/src/external-skills.js +2 -2
  153. package/src/index.js +1 -0
  154. package/src/manifest.js +1 -1
  155. package/src/platforms.js +6 -2
  156. package/src/prompts.js +11 -3
  157. package/src/scaffold.js +87 -11
  158. package/src/upgrade.js +9 -3
  159. package/bundled/dev-pipeline/SCHEMA_ANALYSIS.md +0 -53
  160. package/bundled/dev-pipeline/scripts/generate-refactor-prompt.py +0 -649
  161. package/bundled/dev-pipeline/scripts/init-refactor-pipeline.py +0 -463
  162. package/bundled/dev-pipeline/scripts/update-refactor-status.py +0 -1512
  163. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +0 -240
  164. package/bundled/dev-pipeline/templates/refactor-list-schema.json +0 -266
  165. package/bundled/dev-pipeline/templates/sections/refactor-critical-paths.md +0 -15
  166. package/bundled/dev-pipeline/templates/sections/refactor-mission.md +0 -9
  167. package/bundled/dev-pipeline/templates/sections/refactor-phase-commit-report.md +0 -24
  168. package/bundled/dev-pipeline/templates/sections/refactor-phase-implement.md +0 -16
  169. package/bundled/dev-pipeline/templates/sections/refactor-phase-init.md +0 -9
  170. package/bundled/dev-pipeline/templates/sections/refactor-phase-plan.md +0 -22
  171. package/bundled/dev-pipeline/templates/sections/refactor-phase-review.md +0 -19
  172. package/bundled/dev-pipeline/templates/sections/refactor-phase-test.md +0 -24
  173. package/bundled/dev-pipeline/templates/sections/refactor-reminders.md +0 -12
  174. package/bundled/dev-pipeline/templates/sections/refactor-session-context.md +0 -6
  175. package/bundled/dev-pipeline/templates/sections/refactor-task-contract.md +0 -52
  176. package/bundled/dev-pipeline/tests/test_generate_refactor_prompt.py +0 -478
  177. package/bundled/skills/feature-planner/assets/evaluation-guide.md +0 -44
  178. package/bundled/skills/refactor-pipeline-launcher/SKILL.md +0 -219
  179. package/bundled/skills/refactor-pipeline-launcher/references/configuration.md +0 -78
  180. package/bundled/skills/refactor-planner/SKILL.md +0 -467
  181. package/bundled/skills/refactor-planner/assets/planning-guide.md +0 -291
  182. package/bundled/skills/refactor-planner/references/behavior-preservation.md +0 -187
  183. package/bundled/skills/refactor-planner/references/error-recovery.md +0 -45
  184. package/bundled/skills/refactor-planner/references/fast-path.md +0 -59
  185. package/bundled/skills/refactor-planner/references/generated-plan-review.md +0 -107
  186. package/bundled/skills/refactor-planner/references/planning-phases.md +0 -172
  187. package/bundled/skills/refactor-planner/references/refactor-scoping-guide.md +0 -230
  188. package/bundled/skills/refactor-planner/scripts/validate-and-generate-refactor.py +0 -1120
  189. package/bundled/skills/refactor-workflow/SKILL.md +0 -205
@@ -1,2331 +1,44 @@
1
1
  #!/usr/bin/env python3
2
2
  """
3
- parse-stream-progress.py - Real-time stream-json progress parser
3
+ parse-stream-progress.py - Real-time stream-json progress parser CLI shim.
4
4
 
5
- Continuously reads an AI CLI session log (JSONL from --output-format stream-json),
6
- extracts tool calls, phase changes, and activity metrics, and writes structured
7
- progress to a progress.json file for heartbeat monitoring.
8
-
9
- Usage:
10
- python3 parse-stream-progress.py --session-log <path> --progress-file <path>
11
-
12
- The script runs until:
13
- - The session log stops growing and the CLI process exits
14
- - It receives SIGTERM/SIGINT
5
+ Core parser classes live in ``prizmkit_runtime.stream_progress``. This wrapper
6
+ preserves direct script invocation and module compatibility for tests.
15
7
  """
16
8
 
9
+ from __future__ import annotations
10
+
17
11
  import argparse
18
- import hashlib
19
12
  import json
20
13
  import os
21
- import re
22
14
  import signal
23
15
  import sys
24
- import tempfile
25
16
  import time
26
- from collections import Counter, deque
27
- from dataclasses import dataclass
28
- from datetime import datetime, timezone
29
17
  from pathlib import Path
30
18
 
31
-
32
- # Ordered pipeline phases — index defines forward-only progression.
33
- # Phase detection is monotonic: once a phase is reached, earlier phases
34
- # cannot be re-entered (prevents false positives from file content mentions).
35
- PHASE_ORDER = ["plan", "implement", "code-review", "retrospective", "commit"]
36
-
37
- # Keywords for phase detection.
38
- # "strong" keywords are skill invocations — high confidence, but still
39
- # forward-only (a mention of prizmkit-plan while in commit phase is noise).
40
- # "weak" keywords are contextual hints — also forward-only, used when no
41
- # strong keyword matches.
42
- PHASE_KEYWORDS = {
43
- "plan": {
44
- "strong": ["prizmkit-plan"],
45
- "weak": ["spec.md", "plan.md", "specification", "architecture", "task checklist", "task breakdown", "gathering requirements"],
46
- },
47
- "implement": {
48
- "strong": ["prizmkit-implement"],
49
- "weak": ["implement", "writing code", "TDD", "coding"],
50
- },
51
- "code-review": {
52
- "strong": ["prizmkit-code-review"],
53
- "weak": ["code review", "review verdict", "reviewing"],
54
- },
55
- "retrospective": {
56
- "strong": ["prizmkit-retrospective"],
57
- "weak": ["retrospective", "structural sync", "architecture knowledge", ".prizmkit/prizm-docs/ sync"],
58
- },
59
- "commit": {
60
- "strong": ["prizmkit-committer"],
61
- "weak": ["git commit", "committing", "feat(", "fix("],
62
- },
63
- }
64
-
65
- CONTEXT_OVERFLOW_CODE = "context_overflow"
66
-
67
- # Exact machine/wrapper signals. These are only treated as self-sufficient when
68
- # they appear in structured error-code fields or as explicit wrapper markers.
69
- CONTEXT_CODE_PATTERNS = [
70
- re.compile(pattern, re.IGNORECASE)
71
- for pattern in (
72
- r"\bcontext_overflow\b",
73
- r"\bcontext_too_large\b",
74
- r"\bcontext_length_exceeded\b",
75
- r"\bmodel_context_window_exceeded\b",
76
- )
77
- ]
78
-
79
- WRAPPER_CONTEXT_ERROR_PATTERNS = [
80
- re.compile(pattern, re.IGNORECASE)
81
- for pattern in (
82
- r"\bPRIZMKIT_FATAL_ERROR\s*=\s*context_overflow\b",
83
- )
84
- ]
85
-
86
- # Natural-language provider messages are weak signals: they require an adjacent
87
- # runtime/API error context unless a structured field already proves the result
88
- # is an error.
89
- WEAK_CONTEXT_ERROR_PATTERNS = [
90
- re.compile(pattern, re.IGNORECASE)
91
- for pattern in (
92
- r"Your input exceeds the context window",
93
- r"input exceeds (?:the )?(?:model )?context window",
94
- r"context window of this model",
95
- r"context window (?:was )?exceeded",
96
- r"exceeded (?:the )?context window",
97
- r"maximum context length exceeded",
98
- r"prompt is too long",
99
- r"too many tokens",
100
- r"input token count exceeds",
101
- r"input tokens? exceeds?",
102
- r"token count exceeds",
103
- )
104
- ]
105
-
106
- REQUEST_TOO_LARGE_PATTERN = re.compile(r"\brequest (?:is )?too large\b", re.IGNORECASE)
107
- REQUEST_TOO_LARGE_SEMANTIC_PATTERN = re.compile(
108
- r"\b(context|token|tokens|prompt|input|model)\b",
109
- re.IGNORECASE,
19
+ _PIPELINE_ROOT = str(Path(__file__).resolve().parents[1])
20
+ if _PIPELINE_ROOT not in sys.path:
21
+ sys.path.insert(0, _PIPELINE_ROOT)
22
+
23
+ from prizmkit_runtime.stream_progress import ( # noqa: E402, F401
24
+ CONTEXT_CODE_PATTERNS,
25
+ CONTEXT_OVERFLOW_CODE,
26
+ ERROR_CONTEXT_PATTERNS,
27
+ PHASE_KEYWORDS,
28
+ PHASE_ORDER,
29
+ REQUEST_TOO_LARGE_PATTERN,
30
+ REQUEST_TOO_LARGE_SEMANTIC_PATTERN,
31
+ TERMINAL_SUBAGENT_STATUSES,
32
+ WEAK_CONTEXT_ERROR_PATTERNS,
33
+ WRAPPER_CONTEXT_ERROR_PATTERNS,
34
+ ProgressTracker,
35
+ SemanticLogEvent,
36
+ SemanticLogNormalizer,
37
+ SemanticLogRenderer,
38
+ atomic_write_json,
39
+ detect_api_error_code,
110
40
  )
111
41
 
112
- ERROR_CONTEXT_PATTERNS = [
113
- re.compile(pattern, re.IGNORECASE)
114
- for pattern in (
115
- r"\bapi error\b",
116
- r"invalid_request_error",
117
- r"\bbad request\b",
118
- r"\bstatus\s*[:=]?\s*(400|413)\b",
119
- r"\bapi_error_status\b",
120
- r"\bapi_error_code\b",
121
- r"\blast_result_is_error\b\s*[\"':=]*\s*true\b",
122
- r"\bis_error\b\s*[\"':=]*\s*true\b",
123
- r"\berror\s*[:=]",
124
- r"\bfatal\s*[:=]",
125
- )
126
- ]
127
-
128
-
129
- def _has_error_context(text):
130
- """Return true when free text looks like a runtime/provider error."""
131
- if not text:
132
- return False
133
- return any(pattern.search(text) for pattern in ERROR_CONTEXT_PATTERNS)
134
-
135
-
136
- def _has_context_overflow_signal(text, structured_code=False):
137
- """Return true when text contains a context-window/token overflow signal."""
138
- if not text:
139
- return False
140
- if any(pattern.search(text) for pattern in WRAPPER_CONTEXT_ERROR_PATTERNS):
141
- return True
142
- if structured_code and any(pattern.search(text) for pattern in CONTEXT_CODE_PATTERNS):
143
- return True
144
- if any(pattern.search(text) for pattern in CONTEXT_CODE_PATTERNS):
145
- return True
146
- if any(pattern.search(text) for pattern in WEAK_CONTEXT_ERROR_PATTERNS):
147
- return True
148
- if REQUEST_TOO_LARGE_PATTERN.search(text) and REQUEST_TOO_LARGE_SEMANTIC_PATTERN.search(text):
149
- return True
150
- return False
151
-
152
-
153
- def detect_api_error_code(text, require_error_context=False, structured_code=False):
154
- """Return a normalized fatal/runtime error code from terminal text.
155
-
156
- Structured error-code fields and explicit wrapper markers can be matched
157
- directly. Natural-language provider messages require runtime/API context to
158
- avoid false positives from prompts, tests, or documentation that merely
159
- mention context windows or token limits.
160
- """
161
- if not text:
162
- return ""
163
- if any(pattern.search(text) for pattern in WRAPPER_CONTEXT_ERROR_PATTERNS):
164
- return CONTEXT_OVERFLOW_CODE
165
- if structured_code and any(pattern.search(text) for pattern in CONTEXT_CODE_PATTERNS):
166
- return CONTEXT_OVERFLOW_CODE
167
- if require_error_context and not _has_error_context(text):
168
- return ""
169
- if _has_context_overflow_signal(text, structured_code=structured_code):
170
- return CONTEXT_OVERFLOW_CODE
171
- return ""
172
-
173
-
174
- TERMINAL_SUBAGENT_STATUSES = {
175
- "completed",
176
- "failed",
177
- "cancelled",
178
- "canceled",
179
- "killed",
180
- "stopped",
181
- "success",
182
- "error",
183
- }
184
-
185
-
186
- def _stable_subagent_digest(*parts):
187
- """Return a short stable digest for provider events without durable ids."""
188
- canonical = json.dumps(parts, ensure_ascii=False, sort_keys=True, default=str)
189
- return hashlib.sha1(canonical.encode("utf-8")).hexdigest()[:16]
190
-
191
-
192
- def _normalize_status(status, default="unknown"):
193
- """Normalize provider status values while preserving provider-specific names."""
194
- text = str(status or "").strip().lower()
195
- if not text:
196
- return default
197
- if text == "cancelled":
198
- return "canceled"
199
- return text
200
-
201
-
202
- def _cursor_tool_call_parts(event):
203
- """Return Cursor tool name, arguments, result, and error signal."""
204
- tool_call = event.get("tool_call") if isinstance(event, dict) else None
205
- if not isinstance(tool_call, dict) or not tool_call:
206
- return "unknown", {}, {}, False
207
- key, payload = next(iter(tool_call.items()))
208
- payload = payload if isinstance(payload, dict) else {}
209
- if key == "function":
210
- name = str(payload.get("name") or "function")
211
- arguments = payload.get("arguments") or payload.get("args") or {}
212
- else:
213
- name = re.sub(r"ToolCall$", "", str(key)) or "unknown"
214
- name = name[:1].upper() + name[1:]
215
- arguments = payload.get("args") or {}
216
- result = payload.get("result") or {}
217
- is_error = bool(event.get("is_error"))
218
- if isinstance(result, dict):
219
- is_error = is_error or bool(result.get("error") or result.get("failure"))
220
- return name, arguments, result, is_error
221
-
222
-
223
- def _cursor_compact_value(value, limit=800):
224
- """Render Cursor tool metadata without copying full file content into logs."""
225
- def compact(item, key=""):
226
- if key in {"fileText", "content"} and isinstance(item, str):
227
- return f"<{len(item)} chars>"
228
- if isinstance(item, dict):
229
- return {child_key: compact(child, child_key) for child_key, child in item.items()}
230
- if isinstance(item, list):
231
- return [compact(child) for child in item]
232
- return item
233
-
234
- value = compact(value)
235
- rendered = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
236
- return rendered[:limit]
237
-
238
-
239
- @dataclass(frozen=True)
240
- class SemanticLogEvent:
241
- """One provider-neutral semantic fragment destined for session.log."""
242
-
243
- kind: str
244
- payload: str = ""
245
- stream_id: str = ""
246
- mode: str = "complete"
247
- deduplicate: bool = False
248
-
249
-
250
- class SemanticLogRenderer:
251
- """Render semantic fragments without consulting their source format."""
252
-
253
- LABELS = {
254
- "think": "[THINK]",
255
- "action": "[ACTION]",
256
- "observation": "[OBSERVATION]",
257
- "error": "[ERROR]",
258
- "final": "[FINAL]",
259
- "session_end": "[SESSION_END]",
260
- "output": "[OUTPUT]",
261
- }
262
-
263
- def __init__(self):
264
- self._active_stream = ""
265
-
266
- def _close_active(self):
267
- if not self._active_stream:
268
- return ""
269
- self._active_stream = ""
270
- return "\n"
271
-
272
- def render(self, event):
273
- label = self.LABELS.get(event.kind, "[OUTPUT]")
274
- payload = str(event.payload or "")
275
- mode = event.mode or "complete"
276
- stream_id = event.stream_id or f"{event.kind}:anonymous"
277
-
278
- if mode == "complete":
279
- prefix = self._close_active()
280
- suffix = "" if payload.endswith("\n") else "\n"
281
- spacer = " " if payload else ""
282
- return f"{prefix}{label}{spacer}{payload}{suffix}"
283
-
284
- if mode == "start":
285
- prefix = self._close_active()
286
- self._active_stream = stream_id
287
- return f"{prefix}{label} {payload}"
288
-
289
- if mode == "delta":
290
- if self._active_stream == stream_id:
291
- return payload
292
- prefix = self._close_active()
293
- self._active_stream = stream_id
294
- return f"{prefix}{label} {payload}"
295
-
296
- if mode == "end":
297
- if self._active_stream == stream_id:
298
- self._active_stream = ""
299
- return f"{payload}\n"
300
- if not payload:
301
- return ""
302
- prefix = self._close_active()
303
- suffix = "" if payload.endswith("\n") else "\n"
304
- return f"{prefix}{label} {payload}{suffix}"
305
-
306
- return self.render(SemanticLogEvent(event.kind, payload, stream_id, "complete"))
307
-
308
- def finish(self):
309
- return self._close_active()
310
-
311
-
312
- class SemanticLogNormalizer:
313
- """Adapt supported structured shapes into one compact semantic log stream."""
314
-
315
- _SUCCESS_STOPS = {"stop", "end_turn", "completed", "success"}
316
- _ERROR_STOPS = {"error", "aborted", "failed", "cancelled", "canceled"}
317
-
318
- def __init__(self):
319
- self.renderer = SemanticLogRenderer()
320
- self._scope = 0
321
- self._block_streams = {}
322
- self._stream_buffers = {}
323
- self._snapshots = {}
324
- self._recent_digests = deque()
325
- self._recent_digest_set = set()
326
- self._recent_action_ids = deque()
327
- self._recent_action_id_set = set()
328
- self._recent_output_ids = deque()
329
- self._recent_output_id_set = set()
330
- self._max_recent = 256
331
- self._terminal_emitted = False
332
-
333
- @staticmethod
334
- def _json_text(value):
335
- if isinstance(value, str):
336
- return value
337
- return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
338
-
339
- @classmethod
340
- def _value_text(cls, value):
341
- if value in (None, ""):
342
- return ""
343
- if isinstance(value, str):
344
- return value
345
- if isinstance(value, list):
346
- return "".join(cls._value_text(item) for item in value)
347
- if isinstance(value, dict):
348
- for key in ("text", "output", "content"):
349
- if key in value:
350
- return cls._value_text(value.get(key))
351
- return cls._json_text(value)
352
- return str(value)
353
-
354
- def _digest(self, kind, payload):
355
- canonical_payload = str(payload or "").rstrip()
356
- return hashlib.sha1(f"{self._scope}\0{kind}\0{canonical_payload}".encode("utf-8")).hexdigest()
357
-
358
- def _remember_digest(self, kind, payload):
359
- if not payload:
360
- return
361
- digest = self._digest(kind, payload)
362
- if digest in self._recent_digest_set:
363
- return
364
- if len(self._recent_digests) >= self._max_recent:
365
- old = self._recent_digests.popleft()
366
- self._recent_digest_set.discard(old)
367
- self._recent_digests.append(digest)
368
- self._recent_digest_set.add(digest)
369
-
370
- def _is_recent(self, kind, payload):
371
- return bool(payload) and self._digest(kind, payload) in self._recent_digest_set
372
-
373
- def _remember_action_id(self, action_id):
374
- action_id = str(action_id or "")
375
- if not action_id or action_id in self._recent_action_id_set:
376
- return
377
- if len(self._recent_action_ids) >= self._max_recent:
378
- old = self._recent_action_ids.popleft()
379
- self._recent_action_id_set.discard(old)
380
- self._recent_action_ids.append(action_id)
381
- self._recent_action_id_set.add(action_id)
382
-
383
- def _remember_output_id(self, output_id):
384
- output_id = str(output_id or "")
385
- if not output_id or output_id in self._recent_output_id_set:
386
- return
387
- if len(self._recent_output_ids) >= self._max_recent:
388
- old = self._recent_output_ids.popleft()
389
- self._recent_output_id_set.discard(old)
390
- self._recent_output_ids.append(output_id)
391
- self._recent_output_id_set.add(output_id)
392
-
393
- def _emit(self, event):
394
- payload = str(event.payload or "")
395
- if event.mode == "complete":
396
- if event.deduplicate and self._is_recent(event.kind, payload):
397
- return ""
398
- if event.deduplicate:
399
- self._remember_digest(event.kind, payload)
400
- return self.renderer.render(event)
401
-
402
- stream_id = event.stream_id or f"{event.kind}:anonymous"
403
- if event.mode == "start":
404
- self._stream_buffers[stream_id] = payload
405
- elif event.mode == "delta":
406
- self._stream_buffers[stream_id] = self._stream_buffers.get(stream_id, "") + payload
407
- elif event.mode == "end":
408
- complete = self._stream_buffers.pop(stream_id, "") + payload
409
- self._remember_digest(event.kind, complete)
410
- return self.renderer.render(event)
411
-
412
- def _complete(self, kind, payload, *, deduplicate=False):
413
- payload = str(payload or "")
414
- if not payload:
415
- return ""
416
- return self._emit(SemanticLogEvent(kind, payload, deduplicate=deduplicate))
417
-
418
- def _session_end(self, payload):
419
- if self._terminal_emitted:
420
- return ""
421
- self._terminal_emitted = True
422
- return self._complete("session_end", payload)
423
-
424
- def _stream(self, kind, stream_id, mode, payload=""):
425
- return self._emit(SemanticLogEvent(kind, str(payload or ""), stream_id, mode))
426
-
427
- def _snapshot(self, kind, stream_id, value, final=False):
428
- """Render cumulative snapshots while retaining only one active full value."""
429
- value = str(value or "")
430
- previous = self._snapshots.get(stream_id)
431
- rendered = ""
432
- if previous is None:
433
- self._snapshots[stream_id] = value
434
- if value:
435
- rendered += self.renderer.render(SemanticLogEvent(kind, value, stream_id, "start"))
436
- elif value == previous:
437
- pass
438
- elif value.startswith(previous):
439
- self._snapshots[stream_id] = value
440
- rendered += self.renderer.render(
441
- SemanticLogEvent(kind, value[len(previous):], stream_id, "delta")
442
- )
443
- else:
444
- rendered += self.renderer.render(SemanticLogEvent(kind, "", stream_id, "end"))
445
- self._snapshots[stream_id] = value
446
- if value:
447
- rendered += self.renderer.render(SemanticLogEvent(kind, value, stream_id, "start"))
448
- if final:
449
- rendered += self.renderer.render(SemanticLogEvent(kind, "", stream_id, "end"))
450
- self._snapshots.pop(stream_id, None)
451
- return rendered
452
-
453
- def _message_parts(self, message):
454
- if not isinstance(message, dict):
455
- return ""
456
- rendered = ""
457
- content = message.get("content")
458
- if isinstance(content, str):
459
- rendered += self._complete("final", content)
460
- elif isinstance(content, list):
461
- for block in content:
462
- if not isinstance(block, dict):
463
- continue
464
- block_type = str(block.get("type") or "")
465
- if block_type in {"text", "output_text"}:
466
- rendered += self._complete(
467
- "final",
468
- block.get("text") or block.get("content") or "",
469
- deduplicate=True,
470
- )
471
- elif block_type in {"thinking", "reasoning"}:
472
- rendered += self._complete(
473
- "think",
474
- block.get("thinking") or block.get("text") or "",
475
- deduplicate=True,
476
- )
477
- elif block_type == "tool_use":
478
- action_id = block.get("id") or block.get("tool_use_id")
479
- self._remember_action_id(action_id)
480
- rendered += self._complete(
481
- "action",
482
- f"{block.get('name') or 'tool'} {self._json_text(block.get('input') or {})}",
483
- )
484
- elif block_type == "tool_result":
485
- rendered += self._complete("observation", self._value_text(block.get("content")))
486
- return rendered
487
-
488
- def _tool_result_parts(self, message):
489
- if not isinstance(message, dict):
490
- return ""
491
- rendered = ""
492
- content = message.get("content")
493
- if not isinstance(content, list):
494
- return rendered
495
- for block in content:
496
- if isinstance(block, dict) and block.get("type") == "tool_result":
497
- rendered += self._complete("observation", self._value_text(block.get("content")))
498
- return rendered
499
-
500
- def _pi_message_update(self, event):
501
- update = event.get("assistantMessageEvent")
502
- if not isinstance(update, dict):
503
- return ""
504
- subtype = str(update.get("type") or "")
505
- index = update.get("contentIndex", 0)
506
- stream_id = f"turn:{self._scope}:content:{index}"
507
- if subtype == "thinking_start":
508
- return self._stream("think", f"{stream_id}:think", "start")
509
- if subtype == "thinking_delta":
510
- return self._stream("think", f"{stream_id}:think", "delta", update.get("delta"))
511
- if subtype == "thinking_end":
512
- return self._stream("think", f"{stream_id}:think", "end")
513
- if subtype == "text_start":
514
- return self._stream("final", f"{stream_id}:final", "start")
515
- if subtype == "text_delta":
516
- return self._stream("final", f"{stream_id}:final", "delta", update.get("delta"))
517
- if subtype == "text_end":
518
- return self._stream("final", f"{stream_id}:final", "end")
519
- if subtype == "toolcall_start":
520
- partial = update.get("partial")
521
- blocks = partial.get("content") if isinstance(partial, dict) else []
522
- block = blocks[index] if isinstance(blocks, list) and isinstance(index, int) and index < len(blocks) else {}
523
- action_id = block.get("id") if isinstance(block, dict) else ""
524
- self._remember_action_id(action_id)
525
- prefix = f"{block.get('name') or 'tool'} " if isinstance(block, dict) else "tool "
526
- return self._stream("action", f"{stream_id}:action", "start", prefix)
527
- if subtype == "toolcall_delta":
528
- return self._stream("action", f"{stream_id}:action", "delta", update.get("delta"))
529
- if subtype == "toolcall_end":
530
- tool_call = update.get("toolCall")
531
- if isinstance(tool_call, dict):
532
- self._remember_action_id(tool_call.get("id"))
533
- return self._stream("action", f"{stream_id}:action", "end")
534
- return ""
535
-
536
- def _content_block_event(self, event):
537
- event_type = str(event.get("type") or "")
538
- index = event.get("index", 0)
539
- stream_id = f"block:{self._scope}:{index}"
540
- if event_type == "content_block_start":
541
- block = event.get("content_block") if isinstance(event.get("content_block"), dict) else {}
542
- block_type = str(block.get("type") or "")
543
- if block_type in {"thinking", "reasoning"}:
544
- self._block_streams[index] = ("think", stream_id)
545
- return self._stream("think", stream_id, "start", block.get("thinking") or "")
546
- if block_type == "text":
547
- self._block_streams[index] = ("final", stream_id)
548
- return self._stream("final", stream_id, "start", block.get("text") or "")
549
- if block_type == "tool_use":
550
- self._block_streams[index] = ("action", stream_id)
551
- self._remember_action_id(block.get("id"))
552
- return self._stream("action", stream_id, "start", f"{block.get('name') or 'tool'} ")
553
- return ""
554
- if event_type == "content_block_delta":
555
- delta = event.get("delta") if isinstance(event.get("delta"), dict) else {}
556
- delta_type = str(delta.get("type") or "")
557
- if delta_type in {"thinking_delta", "reasoning_delta"}:
558
- kind = "think"
559
- payload = delta.get("thinking") or delta.get("text") or ""
560
- elif delta_type == "text_delta":
561
- kind = "final"
562
- payload = delta.get("text") or ""
563
- elif delta_type == "input_json_delta":
564
- kind = "action"
565
- payload = delta.get("partial_json") or ""
566
- else:
567
- return ""
568
- active_kind, active_id = self._block_streams.get(index, (kind, stream_id))
569
- return self._stream(active_kind, active_id, "delta", payload)
570
- if event_type == "content_block_stop":
571
- kind, active_id = self._block_streams.pop(index, ("output", stream_id))
572
- return self._stream(kind, active_id, "end")
573
- return ""
574
-
575
- def process_text(self, text):
576
- text = str(text or "")
577
- return self._complete("output", text.rstrip("\n")) if text.strip() else ""
578
-
579
- def process_event(self, event):
580
- if not isinstance(event, dict):
581
- return self.process_text(event)
582
- event_type = str(event.get("type") or "")
583
- rendered = ""
584
-
585
- if event_type == "turn_start" or event_type == "turn.started":
586
- self._scope += 1
587
-
588
- if event_type == "message_update" and isinstance(event.get("assistantMessageEvent"), dict):
589
- return self._pi_message_update(event)
590
-
591
- if event_type == "message_end":
592
- message = event.get("message")
593
- if isinstance(message, dict):
594
- role = str(message.get("role") or "")
595
- if role == "assistant":
596
- rendered += self._message_parts(message)
597
- elif role == "toolResult":
598
- output_id = str(message.get("toolCallId") or "")
599
- if output_id not in self._recent_output_id_set:
600
- self._remember_output_id(output_id)
601
- rendered += self._complete("observation", self._value_text(message.get("content")))
602
- stop_reason = str(message.get("stopReason") or "")
603
- if stop_reason in self._ERROR_STOPS:
604
- rendered += self._complete("error", message.get("errorMessage") or stop_reason)
605
- return rendered
606
-
607
- if event_type in {"turn_end", "agent_settled", "agent_start", "session", "thread.started", "turn.started"}:
608
- return ""
609
-
610
- if event_type == "tool_execution_start":
611
- action_id = str(event.get("toolCallId") or event.get("id") or "")
612
- if action_id in self._recent_action_id_set:
613
- return ""
614
- self._remember_action_id(action_id)
615
- return self._complete(
616
- "action",
617
- f"{event.get('toolName') or 'tool'} {self._json_text(event.get('args') or {})}",
618
- )
619
-
620
- if event_type == "tool_execution_update":
621
- stream_id = f"tool:{event.get('toolCallId') or event.get('id') or 'active'}:output"
622
- return self._snapshot("observation", stream_id, self._value_text(event.get("partialResult")))
623
-
624
- if event_type == "tool_execution_end":
625
- output_id = str(event.get("toolCallId") or event.get("id") or "")
626
- self._remember_output_id(output_id)
627
- stream_id = f"tool:{output_id or 'active'}:output"
628
- result_text = self._value_text(event.get("result"))
629
- had_output = stream_id in self._snapshots and bool(self._snapshots.get(stream_id))
630
- rendered += self._snapshot("observation", stream_id, result_text, final=True)
631
- if event.get("isError"):
632
- error_payload = f"{event.get('toolName') or 'tool'} failed"
633
- if not had_output and result_text:
634
- error_payload = f"{error_payload}: {result_text}"
635
- rendered += self._complete("error", error_payload)
636
- return rendered
637
-
638
- if event_type == "auto_retry_start":
639
- message = event.get("errorMessage") or event.get("finalError") or "retrying transient error"
640
- return self._complete("error", f"retry attempt {event.get('attempt') or '?'}: {message}")
641
- if event_type in {"auto_retry_end", "queue_update"}:
642
- return ""
643
- if event_type == "compaction_start":
644
- return self._complete("action", "context compaction started")
645
- if event_type == "compaction_end":
646
- if event.get("errorMessage") or event.get("finalError"):
647
- return self._complete("error", event.get("errorMessage") or event.get("finalError"))
648
- return self._complete("observation", "context compaction completed")
649
-
650
- if event_type == "agent_end":
651
- messages = event.get("messages") if isinstance(event.get("messages"), list) else []
652
- last_message = messages[-1] if messages and isinstance(messages[-1], dict) else {}
653
- stop_reason = str(last_message.get("stopReason") or "")
654
- will_retry = bool(event.get("willRetry"))
655
- if will_retry:
656
- return ""
657
- status = "error" if stop_reason in self._ERROR_STOPS else "success"
658
- details = f"status={status}"
659
- if stop_reason:
660
- details += f" stop_reason={stop_reason}"
661
- return self._session_end(details)
662
-
663
- if event_type in {"content_block_start", "content_block_delta", "content_block_stop"}:
664
- return self._content_block_event(event)
665
- if event_type == "message_start":
666
- self._scope += 1
667
- return ""
668
- if event_type == "message_stop":
669
- return self.renderer.finish()
670
-
671
- if event_type == "tool_call":
672
- tool_name, arguments, result, is_error = _cursor_tool_call_parts(event)
673
- call_id = str(event.get("call_id") or "")
674
- if event.get("subtype") == "started":
675
- self._remember_action_id(call_id)
676
- return self._complete("action", f"{tool_name} {_cursor_compact_value(arguments)}")
677
- if event.get("subtype") == "completed":
678
- rendered += self._complete("observation", f"{tool_name} {_cursor_compact_value(result)}")
679
- if is_error:
680
- rendered += self._complete("error", f"{tool_name} failed")
681
- return rendered
682
- return ""
683
-
684
- if event_type == "assistant":
685
- self._scope += 1
686
- return self._message_parts(event.get("message"))
687
- if event_type == "message" and isinstance(event.get("sessionId"), str):
688
- if event.get("role") == "assistant":
689
- self._scope += 1
690
- return self._message_parts(event)
691
- return ""
692
- if event_type == "tool_result":
693
- return self._complete("observation", self._value_text(event.get("content")))
694
- if event_type == "user" and not isinstance(event.get("sessionId"), str):
695
- return self._tool_result_parts(event.get("message"))
696
- if event_type == "function_call":
697
- self._remember_action_id(event.get("id") or event.get("call_id"))
698
- return self._complete(
699
- "action",
700
- f"{event.get('name') or 'tool'} {self._value_text(event.get('arguments'))}",
701
- )
702
- if event_type == "function_call_result":
703
- return self._complete("observation", self._value_text(event.get("output") or event.get("result")))
704
-
705
- if event_type in {"item.started", "item.completed"}:
706
- item = event.get("item") if isinstance(event.get("item"), dict) else {}
707
- item_type = str(item.get("type") or "")
708
- item_id = str(item.get("id") or item.get("call_id") or _stable_subagent_digest(item))
709
- if item_type in {"reasoning", "analysis"} and event_type == "item.completed":
710
- return self._complete("think", self._value_text(item.get("text") or item.get("summary") or ""))
711
- if item_type == "agent_message" and event_type == "item.completed":
712
- return self._complete("final", item.get("text") or "")
713
- if item_type in {"command_execution", "mcp_tool_call", "collab_tool_call"}:
714
- command = item.get("command") or item.get("tool") or item.get("name") or item_type
715
- if event_type == "item.started":
716
- self._remember_action_id(item_id)
717
- return self._complete("action", self._value_text(command))
718
- if item_id not in self._recent_action_id_set:
719
- self._remember_action_id(item_id)
720
- rendered += self._complete("action", self._value_text(command))
721
- output = item.get("aggregated_output") or item.get("output") or item.get("result")
722
- rendered += self._complete("observation", self._value_text(output))
723
- if str(item.get("status") or "") in self._ERROR_STOPS:
724
- rendered += self._complete("error", self._value_text(item.get("error") or "command failed"))
725
- return rendered
726
- if event_type == "item.completed" and item_type in {"file_change", "web_search"}:
727
- return self._complete("action", self._value_text(item))
728
- return ""
729
-
730
- if event_type == "turn.completed":
731
- return self._session_end("status=success")
732
- if event_type == "turn.failed":
733
- error_text = self._value_text(event.get("error") or event.get("message") or "turn failed")
734
- return self._complete("error", error_text) + self._session_end("status=error")
735
- if event_type == "result":
736
- subtype = str(event.get("subtype") or event.get("result_subtype") or "")
737
- normalized_subtype = subtype.lower()
738
- is_error = bool(event.get("is_error")) or normalized_subtype in self._ERROR_STOPS or normalized_subtype.startswith(("error", "failed", "cancel"))
739
- result_text = self._value_text(event.get("result") or event.get("message"))
740
- if result_text:
741
- rendered += self._complete(
742
- "error" if is_error else "final",
743
- result_text,
744
- deduplicate=not is_error,
745
- )
746
- rendered += self._session_end(
747
- f"status={'error' if is_error else 'success'}" + (f" stop_reason={event.get('stop_reason')}" if event.get("stop_reason") else ""),
748
- )
749
- return rendered
750
- if event_type == "error" or event.get("error"):
751
- return self._complete("error", self._value_text(event.get("error") or event.get("message") or "runtime error"))
752
- return ""
753
-
754
- def finish(self):
755
- rendered = self.renderer.finish()
756
- if not self._terminal_emitted:
757
- rendered += self._session_end("status=stream_closed")
758
- self._stream_buffers.clear()
759
- self._snapshots.clear()
760
- return rendered
761
-
762
-
763
- class ProgressTracker:
764
- """Tracks progress state from stream-json events."""
765
-
766
- def __init__(self, session_log=None, provider_hint=None):
767
- self.session_log_path = Path(session_log).expanduser() if session_log else None
768
- self.provider_hint = str(provider_hint or "").strip().lower()
769
- self.message_count = 0
770
- self.event_type_counts = Counter()
771
- self.current_tool = None
772
- self.current_tool_input_summary = ""
773
- self.current_phase = None
774
- self.detected_phases = []
775
- self.tool_call_counts = Counter()
776
- self.total_tool_calls = 0
777
- self.last_text_snippet = ""
778
- self.last_result_is_error = False
779
- self.api_error_status = None
780
- self.api_error_code = ""
781
- self.terminal_result_text = ""
782
- self.terminal_success_at = ""
783
- self.fatal_error_code = ""
784
- self.is_active = True
785
- self.errors = []
786
- self.event_format = ""
787
- self.active_subagents = 0
788
- self.subagent_status_counts = Counter()
789
- self.subagents_spawned = 0
790
- self.subagent_records = {}
791
- self.subagent_aliases = {}
792
- self.subagent_source_providers = set()
793
- self.subagent_source_events = Counter()
794
- self.parent_subagent_activity_ids = set()
795
- self.codex_child_thread_ids = set()
796
- self.cb_session_id = ""
797
- self.cursor_session_id = ""
798
- self.result_subtype = ""
799
- self.stop_reason = ""
800
- self.has_usage = False
801
- self.permission_denials = []
802
- self.cb_cwd = ""
803
- self.claude_session_id = ""
804
- self.claude_cwd = ""
805
- self.claude_task_states = {}
806
- self.child_session_files = []
807
- self.child_total_bytes = 0
808
- self.child_activity_signature = ""
809
- self.last_child_activity_at = ""
810
- self._codex_child_session_paths = {}
811
- self._claude_child_session_files = []
812
- self._cb_child_session_files = []
813
- self._last_child_scan_at = 0.0
814
- self._last_claude_fallback_scan_at = 0.0
815
- self._last_claude_fallback_scan_key = ""
816
- self._claude_fallback_scan_interval_seconds = 10.0
817
- self._text_buffer = ""
818
- self._in_tool_use = False
819
- self._current_tool_input_parts = []
820
- self._current_tool_id = ""
821
- self._pi_retrying_terminal_error = False
822
-
823
- def process_event(self, event):
824
- """Process a single stream-json event and update state.
825
-
826
- Supports Claude API/CLI, CodeBuddy, Codex JSONL, and Pi JSONL formats.
827
- """
828
- event_type = event.get("type", "")
829
- if event_type:
830
- self.event_type_counts[str(event_type)] += 1
831
- self._detect_structured_terminal_fields(event)
832
- self._record_usage_and_permission_metadata(event)
833
- parent_tool_use_id = event.get("parent_tool_use_id")
834
- if isinstance(parent_tool_use_id, str) and parent_tool_use_id.strip():
835
- parent_tool_use_id = parent_tool_use_id.strip()
836
- self.parent_subagent_activity_ids.add(parent_tool_use_id)
837
- self._record_subagent_event(
838
- "claude",
839
- "parent_tool_use_id",
840
- identifier=parent_tool_use_id,
841
- aliases=[parent_tool_use_id],
842
- status="running",
843
- active=True,
844
- spawn=False,
845
- metadata={"parent_tool_use_id": parent_tool_use_id},
846
- )
847
-
848
- self._record_structured_subagent_metadata(event)
849
-
850
- # ── Cursor Agent --output-format stream-json ─────────────────
851
- is_cursor_event = (
852
- self.provider_hint == "cursor"
853
- or event_type == "tool_call"
854
- or self.event_format == "cursor-stream-json"
855
- )
856
- if is_cursor_event:
857
- self.event_format = "cursor-stream-json"
858
- if event_type == "tool_call" and not self.cursor_session_id and self.claude_session_id:
859
- self.cursor_session_id = self.claude_session_id
860
- self.claude_session_id = ""
861
- self.claude_cwd = ""
862
- session_id = event.get("session_id")
863
- if isinstance(session_id, str) and session_id.strip() and not self.cursor_session_id:
864
- self.cursor_session_id = session_id.strip()
865
- if event_type == "system" and event.get("subtype") == "init":
866
- self.is_active = True
867
- elif event_type == "assistant":
868
- self.message_count += 1
869
- self.is_active = True
870
- message = event.get("message") if isinstance(event.get("message"), dict) else {}
871
- content = message.get("content")
872
- texts = []
873
- if isinstance(content, str):
874
- texts = [content]
875
- elif isinstance(content, list):
876
- texts = [
877
- str(item.get("text") or "")
878
- for item in content
879
- if isinstance(item, dict) and item.get("type") in {"text", "output_text"}
880
- ]
881
- text = "\n".join(part for part in texts if part)
882
- if text.strip():
883
- self.last_text_snippet = text.strip()[-120:]
884
- self._detect_phase(text)
885
- self._detect_terminal_error(text, require_error_context=True)
886
- elif event_type == "tool_call":
887
- tool_name, arguments, result, is_error = _cursor_tool_call_parts(event)
888
- subtype = str(event.get("subtype") or "")
889
- if subtype == "started":
890
- self.current_tool = tool_name
891
- self.tool_call_counts[tool_name] += 1
892
- self.total_tool_calls += 1
893
- self.is_active = True
894
- if isinstance(arguments, dict):
895
- self._extract_tool_summary_from_dict(arguments)
896
- else:
897
- self._extract_tool_summary(str(arguments))
898
- self._detect_phase(_cursor_compact_value(arguments, 500))
899
- self._record_agent_tool_call(
900
- "cursor",
901
- tool_name,
902
- arguments,
903
- source_event="tool_call.started",
904
- event_id=str(event.get("call_id") or ""),
905
- )
906
- elif subtype == "completed":
907
- self.current_tool = None
908
- if is_error:
909
- error_text = _cursor_compact_value(result, 500)
910
- self.errors.append(error_text)
911
- self._detect_terminal_error(error_text, require_error_context=True)
912
- elif event_type == "result":
913
- self.current_tool = None
914
- self.is_active = False
915
- self.result_subtype = str(event.get("subtype") or "")
916
- result_text = str(event.get("result") or event.get("message") or "")
917
- self._record_terminal_result(
918
- text=result_text,
919
- is_error=bool(event.get("is_error")) or self.result_subtype.lower() != "success",
920
- api_error_status=event.get("api_error_status"),
921
- api_error_code=str(event.get("error_code") or ""),
922
- stop_reason=str(event.get("stop_reason") or ""),
923
- )
924
- elif event_type == "error":
925
- error_text = str(event.get("error") or event.get("message") or "Cursor Agent error")
926
- self.errors.append(error_text[:500])
927
- self._detect_terminal_error(error_text, require_error_context=True)
928
- return
929
-
930
- # ── Pi --mode json JSONL format ─────────────────────────────
931
- pi_event_types = {
932
- "session", "agent_start", "agent_end", "turn_start", "turn_end",
933
- "message_start", "message_update", "message_end",
934
- "tool_execution_start", "tool_execution_update", "tool_execution_end",
935
- "queue_update", "compaction_start", "compaction_end",
936
- "auto_retry_start", "auto_retry_end",
937
- }
938
- if event_type == "session" or (self.event_format == "pi-json" and event_type in pi_event_types):
939
- self.event_format = "pi-json"
940
- if event_type in {"agent_start", "turn_start", "message_start", "message_update", "tool_execution_start", "tool_execution_update", "compaction_start", "auto_retry_start"}:
941
- self.is_active = True
942
- if event_type == "agent_start" and self._pi_retrying_terminal_error:
943
- self.result_subtype = ""
944
- self.stop_reason = ""
945
- self.last_result_is_error = False
946
- self.api_error_status = None
947
- self.api_error_code = ""
948
- self.fatal_error_code = ""
949
- self.terminal_result_text = ""
950
- self.terminal_success_at = ""
951
- if event_type == "turn_start":
952
- self.message_count += 1
953
- elif event_type in {"message_update", "message_end"}:
954
- assistant_event = event.get("assistantMessageEvent")
955
- message = event.get("message")
956
- text = ""
957
- if isinstance(assistant_event, dict):
958
- text = str(assistant_event.get("delta") or assistant_event.get("text") or "")
959
- if not text and isinstance(message, dict):
960
- content = message.get("content")
961
- if isinstance(content, str):
962
- text = content
963
- elif isinstance(content, list):
964
- text = "\n".join(
965
- str(item.get("text") or "")
966
- for item in content if isinstance(item, dict)
967
- )
968
- if text.strip():
969
- self.last_text_snippet = text.strip()[-120:]
970
- self._detect_phase(text)
971
- if (
972
- event_type == "message_end"
973
- and isinstance(message, dict)
974
- and message.get("role") == "assistant"
975
- ):
976
- stop_reason = str(message.get("stopReason") or "")
977
- if stop_reason:
978
- self.stop_reason = stop_reason
979
- if stop_reason in {"error", "aborted"}:
980
- error_text = str(message.get("errorMessage") or stop_reason)
981
- self.result_subtype = "error"
982
- self.last_result_is_error = True
983
- self.terminal_result_text = error_text[:1000]
984
- self.errors.append(error_text[:500])
985
- self._detect_terminal_error(error_text, require_error_context=True)
986
- elif event_type == "tool_execution_start":
987
- tool_name = str(event.get("toolName") or "unknown")
988
- self.current_tool = tool_name
989
- self.tool_call_counts[tool_name] += 1
990
- self.total_tool_calls += 1
991
- args = event.get("args")
992
- if isinstance(args, dict):
993
- self._extract_tool_summary_from_dict(args)
994
- self._detect_phase(json.dumps(args, ensure_ascii=False)[:500])
995
- elif event_type == "tool_execution_end":
996
- self.current_tool = None
997
- if event.get("isError"):
998
- result = event.get("result")
999
- error_text = json.dumps(result, ensure_ascii=False, default=str)
1000
- self.errors.append(error_text[:500])
1001
- self._detect_terminal_error(error_text, require_error_context=True)
1002
- elif event_type in {"compaction_end", "auto_retry_end"}:
1003
- error_text = str(event.get("errorMessage") or event.get("finalError") or "")
1004
- if error_text:
1005
- self.errors.append(error_text[:500])
1006
- self._detect_terminal_error(error_text, require_error_context=True)
1007
- elif event_type == "agent_end":
1008
- self.current_tool = None
1009
- self.is_active = False
1010
- messages = event.get("messages") if isinstance(event.get("messages"), list) else []
1011
- final_message = messages[-1] if messages and isinstance(messages[-1], dict) else {}
1012
- final_stop_reason = str(final_message.get("stopReason") or self.stop_reason or "")
1013
- will_retry = bool(event.get("willRetry"))
1014
- if will_retry:
1015
- self._pi_retrying_terminal_error = bool(
1016
- self.result_subtype == "error"
1017
- or self.last_result_is_error
1018
- or self.fatal_error_code
1019
- )
1020
- elif final_stop_reason not in {"error", "aborted", "failed", "cancelled", "canceled"} and (
1021
- self.result_subtype != "error"
1022
- or self._pi_retrying_terminal_error
1023
- ):
1024
- self.result_subtype = "success"
1025
- self.stop_reason = final_stop_reason or self.stop_reason
1026
- self.last_result_is_error = False
1027
- if self._pi_retrying_terminal_error:
1028
- self.api_error_status = None
1029
- self.api_error_code = ""
1030
- self.fatal_error_code = ""
1031
- final_text = ""
1032
- content = final_message.get("content") if isinstance(final_message, dict) else None
1033
- if isinstance(content, str):
1034
- final_text = content
1035
- elif isinstance(content, list):
1036
- final_text = "\n".join(
1037
- str(item.get("text") or "")
1038
- for item in content
1039
- if isinstance(item, dict) and item.get("type") == "text"
1040
- )
1041
- if final_text.strip():
1042
- self.terminal_result_text = final_text[:1000]
1043
- self.last_text_snippet = final_text.strip()[-120:]
1044
- self.terminal_success_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
1045
- self._pi_retrying_terminal_error = False
1046
- return
1047
-
1048
- # ── Codex exec --json JSONL format ──────────────────────────
1049
- if event_type in (
1050
- "thread.started", "turn.started", "turn.completed",
1051
- "turn.failed", "item.started", "item.completed", "error",
1052
- ):
1053
- self.event_format = "codex-json"
1054
- self.is_active = True
1055
-
1056
- if event_type == "turn.started":
1057
- self.message_count += 1
1058
-
1059
- elif event_type in ("item.started", "item.completed"):
1060
- item = event.get("item", {})
1061
- item_type = item.get("type", "")
1062
-
1063
- if item_type == "agent_message":
1064
- text = item.get("text", "")
1065
- if text.strip():
1066
- self.last_text_snippet = text.strip()[:120]
1067
- self._detect_phase(text)
1068
-
1069
- elif item_type == "collab_tool_call":
1070
- tool_name = item.get("tool", "collab")
1071
- if event_type == "item.started":
1072
- self.current_tool = tool_name
1073
- self.tool_call_counts[tool_name] += 1
1074
- self.total_tool_calls += 1
1075
- elif item.get("status") == "completed":
1076
- self.current_tool = None
1077
- self._extract_tool_summary_from_dict(item)
1078
-
1079
- prompt = item.get("prompt")
1080
- if prompt:
1081
- self._detect_phase(prompt)
1082
-
1083
- else:
1084
- tool_name = item.get("tool") or item.get("name")
1085
- if tool_name:
1086
- if event_type == "item.started":
1087
- self.current_tool = tool_name
1088
- self.tool_call_counts[tool_name] += 1
1089
- self.total_tool_calls += 1
1090
- elif item.get("status") == "completed":
1091
- self.current_tool = None
1092
- self._extract_tool_summary_from_dict(item)
1093
-
1094
- elif event_type == "turn.completed":
1095
- self.current_tool = None
1096
- self.is_active = False
1097
- if not self.fatal_error_code:
1098
- self.result_subtype = "success"
1099
- self.stop_reason = "completed"
1100
- self.last_result_is_error = False
1101
- self.terminal_success_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
1102
-
1103
- elif event_type == "turn.failed":
1104
- error = event.get("error") or event.get("message") or "Codex turn failed"
1105
- self.errors.append(str(error))
1106
- self._detect_terminal_error(str(error))
1107
- self.result_subtype = "error"
1108
- self.stop_reason = "failed"
1109
- self.last_result_is_error = True
1110
- self.terminal_result_text = str(error)[:1000]
1111
- self.current_tool = None
1112
- self.is_active = False
1113
-
1114
- elif event_type == "error":
1115
- error = event.get("error") or event.get("message") or "Unknown error"
1116
- self.errors.append(str(error))
1117
- self._detect_terminal_error(str(error))
1118
-
1119
- return
1120
-
1121
- # ── CodeBuddy stream-json format ──────────────────────────────
1122
- # cbc --print -y --output-format stream-json emits:
1123
- # message (role=user/assistant), function_call, function_call_result,
1124
- # file-history-snapshot, error. The first user message carries
1125
- # sessionId and cwd metadata; later function_call items carry the
1126
- # same fields.
1127
- # NOTE: cbc emits tool invocations as EITHER tool_use blocks inside a
1128
- # message (role=assistant) event OR as standalone function_call events,
1129
- # but not both for the same invocation. The two handlers are
1130
- # complementary rather than redundant, so no deduplication is needed.
1131
- # Detect via event_type=="message" with a "sessionId" field.
1132
- # Must run before the Claude Code assistant / tool_result branches
1133
- # because those also accept those types but use different internals.
1134
- if event_type == "message" and isinstance(event.get("sessionId"), str):
1135
- self.event_format = self.event_format or "stream-json"
1136
- role = event.get("role", "")
1137
- sid = event.get("sessionId", "")
1138
- cwd = event.get("cwd", "")
1139
- if sid and not self.cb_session_id:
1140
- self.cb_session_id = sid.strip()
1141
- if cwd and not self.cb_cwd:
1142
- self.cb_cwd = cwd.strip()
1143
- if role == "assistant":
1144
- self.message_count += 1
1145
- self.is_active = True
1146
- content = event.get("content", [])
1147
- if isinstance(content, list):
1148
- for block in content:
1149
- block_type = block.get("type", "")
1150
- if block_type == "tool_use":
1151
- tool_name = block.get("name", "unknown")
1152
- self.current_tool = tool_name
1153
- self.tool_call_counts[tool_name] += 1
1154
- self.total_tool_calls += 1
1155
- tool_input = block.get("input", {})
1156
- if isinstance(tool_input, dict):
1157
- self._extract_tool_summary_from_dict(tool_input)
1158
- self._detect_phase(
1159
- json.dumps(tool_input, ensure_ascii=False)[:500]
1160
- )
1161
- # Track CodeBuddy Agent/Task tool invocations as
1162
- # session-log authoritative sub-agent spawns.
1163
- self._record_cb_agent_tool_call(
1164
- tool_name,
1165
- tool_input,
1166
- event_id=str(block.get("id") or block.get("tool_use_id") or block.get("call_id") or ""),
1167
- source_event="message.tool_use",
1168
- )
1169
- elif block_type == "text":
1170
- text = block.get("text", "")
1171
- if text.strip():
1172
- self.last_text_snippet = text.strip()[:120]
1173
- self._detect_phase(text)
1174
- self._detect_terminal_error(
1175
- text, require_error_context=True
1176
- )
1177
- return
1178
-
1179
- # CodeBuddy function_call / function_call_result in stream-json
1180
- if event_type in ("function_call", "function_call_result"):
1181
- self.event_format = self.event_format or "stream-json"
1182
- sid = event.get("sessionId", "")
1183
- cwd = event.get("cwd", "")
1184
- if sid and not self.cb_session_id:
1185
- self.cb_session_id = sid.strip()
1186
- if cwd and not self.cb_cwd:
1187
- self.cb_cwd = cwd.strip()
1188
- if event_type == "function_call":
1189
- tool_name = event.get("name", "unknown")
1190
- self.current_tool = tool_name
1191
- self.tool_call_counts[tool_name] += 1
1192
- self.total_tool_calls += 1
1193
- self.is_active = True
1194
- # Extract summary from arguments
1195
- raw_args = event.get("arguments", "")
1196
- if isinstance(raw_args, str) and raw_args.strip():
1197
- self._extract_tool_summary(raw_args)
1198
- self._detect_phase(raw_args[:500])
1199
- # Track Agent/Task tool invocations as session-log sub-agent spawns.
1200
- self._record_cb_agent_tool_call(
1201
- tool_name,
1202
- raw_args,
1203
- event_id=str(event.get("id") or event.get("call_id") or event.get("callId") or ""),
1204
- source_event="function_call",
1205
- )
1206
- elif event_type == "function_call_result":
1207
- self.current_tool = None
1208
- # Check result text for phase / error hints
1209
- result_text = event.get("output") or ""
1210
- if result_text and isinstance(result_text, str):
1211
- stripped = result_text.strip()
1212
- if stripped:
1213
- self.last_text_snippet = stripped[:120]
1214
- self._detect_phase(stripped)
1215
- self._detect_terminal_error(stripped, require_error_context=True)
1216
- return
1217
-
1218
- # ── Claude Code verbose format ──────────────────────────────
1219
- if event_type == "assistant":
1220
- self.event_format = self.event_format or "stream-json"
1221
- self.message_count += 1
1222
- self.is_active = True
1223
- message = event.get("message", {})
1224
- content_blocks = message.get("content", [])
1225
- for block in content_blocks:
1226
- block_type = block.get("type", "")
1227
- if block_type == "tool_use":
1228
- tool_name = block.get("name", "unknown")
1229
- self.current_tool = tool_name
1230
- self.tool_call_counts[tool_name] += 1
1231
- self.total_tool_calls += 1
1232
- # Extract summary from input
1233
- tool_input = block.get("input", {})
1234
- if isinstance(tool_input, dict):
1235
- self._extract_tool_summary_from_dict(tool_input)
1236
- self._detect_phase(json.dumps(tool_input, ensure_ascii=False)[:500])
1237
- self._record_agent_tool_call(
1238
- "claude",
1239
- tool_name,
1240
- tool_input,
1241
- source_event="assistant.tool_use",
1242
- event_id=str(block.get("id") or block.get("tool_use_id") or ""),
1243
- )
1244
- elif block_type == "text":
1245
- text = block.get("text", "")
1246
- if text.strip():
1247
- self.last_text_snippet = text.strip()[:120]
1248
- self._detect_phase(text)
1249
- self._detect_terminal_error(text, require_error_context=True)
1250
-
1251
- elif event_type == "tool_result" or (
1252
- event_type == "user"
1253
- and not isinstance(event.get("sessionId"), str)
1254
- ):
1255
- # tool_result contains output from tool execution
1256
- self.event_format = self.event_format or "stream-json"
1257
- self.is_active = True
1258
-
1259
- # Check for error patterns in tool_result content (supports both formats):
1260
- # A) Top-level tool_result events: event["content"] is the result text
1261
- # B) Nested user events: event["message"]["content"][] has type=="tool_result" items
1262
- content_candidates = []
1263
-
1264
- # Format A: top-level tool_result (Claude Code)
1265
- if event_type == "tool_result":
1266
- content_candidates.append(str(event.get("content", "")))
1267
-
1268
- # Format B: nested inside user event (Claude Code, NOT CodeBuddy)
1269
- if event_type == "user":
1270
- message = event.get("message", {})
1271
- content_list = message.get("content", [])
1272
- if isinstance(content_list, list):
1273
- for item in content_list:
1274
- if isinstance(item, dict) and item.get("type") == "tool_result":
1275
- content_candidates.append(str(item.get("content", "")))
1276
-
1277
- for result_text in content_candidates:
1278
- if "shorter than the provided offset" in result_text:
1279
- self.errors.append({
1280
- "type": "read_offset_overflow",
1281
- "tool": self.current_tool,
1282
- "at": datetime.now(timezone.utc).isoformat(),
1283
- })
1284
- break # one error per event is enough
1285
- elif "Wasted call" in result_text:
1286
- self.errors.append({
1287
- "type": "wasted_call",
1288
- "tool": self.current_tool,
1289
- "at": datetime.now(timezone.utc).isoformat(),
1290
- })
1291
- break
1292
-
1293
- # Keep only last 20 errors to prevent unbounded growth in progress.json
1294
- if len(self.errors) > 20:
1295
- self.errors = self.errors[-20:]
1296
-
1297
- elif event_type == "system":
1298
- # System events (hooks, init, task notifications, etc.) — track but don't count as messages.
1299
- self.event_format = self.event_format or "stream-json"
1300
- subtype = event.get("subtype", "")
1301
- if subtype == "init":
1302
- self.is_active = True
1303
- session_id = event.get("session_id")
1304
- if isinstance(session_id, str) and session_id.strip():
1305
- self.claude_session_id = session_id.strip()
1306
- cwd = event.get("cwd")
1307
- if isinstance(cwd, str) and cwd.strip():
1308
- self.claude_cwd = cwd.strip()
1309
- elif subtype == "task_started":
1310
- task_id = event.get("task_id")
1311
- if isinstance(task_id, str) and task_id.strip():
1312
- self.claude_task_states[task_id.strip()] = {
1313
- "status": "running",
1314
- "summary": str(event.get("description") or "")[:120],
1315
- "tool_use_id": str(event.get("tool_use_id") or ""),
1316
- "task_type": str(event.get("task_type") or ""),
1317
- "subagent_type": str(event.get("subagent_type") or ""),
1318
- }
1319
- self._update_claude_subagent_status_counts()
1320
- elif subtype in ("task_updated", "task_progress"):
1321
- task_id = event.get("task_id")
1322
- if isinstance(task_id, str) and task_id.strip():
1323
- state = self.claude_task_states.setdefault(task_id.strip(), {})
1324
- patch = event.get("patch") if isinstance(event.get("patch"), dict) else {}
1325
- status = patch.get("status") or event.get("status")
1326
- if status:
1327
- state["status"] = str(status)
1328
- summary = patch.get("summary") or patch.get("description") or event.get("summary") or event.get("description")
1329
- if summary:
1330
- state["summary"] = str(summary)[:120]
1331
- else:
1332
- state.setdefault("summary", "")
1333
- tool_use_id = patch.get("tool_use_id") or event.get("tool_use_id")
1334
- if tool_use_id:
1335
- state["tool_use_id"] = str(tool_use_id)
1336
- else:
1337
- state.setdefault("tool_use_id", "")
1338
- task_type = patch.get("task_type") or event.get("task_type")
1339
- if task_type:
1340
- state["task_type"] = str(task_type)
1341
- else:
1342
- state.setdefault("task_type", "")
1343
- subagent_type = patch.get("subagent_type") or event.get("subagent_type")
1344
- if subagent_type:
1345
- state["subagent_type"] = str(subagent_type)
1346
- else:
1347
- state.setdefault("subagent_type", "")
1348
- self._update_claude_subagent_status_counts()
1349
- elif subtype == "task_notification":
1350
- task_id = event.get("task_id")
1351
- if isinstance(task_id, str) and task_id.strip():
1352
- state = self.claude_task_states.setdefault(task_id.strip(), {})
1353
- status = event.get("status") or "completed"
1354
- state["status"] = str(status)
1355
- state["summary"] = str(event.get("summary") or state.get("summary") or "")[:120]
1356
- state.setdefault("tool_use_id", str(event.get("tool_use_id") or ""))
1357
- task_type = event.get("task_type")
1358
- if task_type:
1359
- state["task_type"] = str(task_type)
1360
- else:
1361
- state.setdefault("task_type", "")
1362
- subagent_type = event.get("subagent_type")
1363
- if subagent_type:
1364
- state["subagent_type"] = str(subagent_type)
1365
- else:
1366
- state.setdefault("subagent_type", "")
1367
- self._update_claude_subagent_status_counts()
1368
-
1369
- elif event_type == "result":
1370
- self.result_subtype = str(event.get("subtype") or event.get("result_subtype") or "")
1371
- self.stop_reason = str(event.get("stop_reason") or "")
1372
- self.event_format = self.event_format or "stream-json"
1373
- self.is_active = False
1374
- result_text = event.get("result") or event.get("message") or ""
1375
- error_obj = event.get("error")
1376
- if isinstance(error_obj, dict):
1377
- error_text = " ".join(
1378
- str(error_obj.get(key) or "")
1379
- for key in ("type", "code", "message")
1380
- if error_obj.get(key)
1381
- )
1382
- result_text = " ".join(part for part in (str(result_text), error_text) if part)
1383
- api_error_code = event.get("api_error_code") or event.get("error_code") or ""
1384
- if isinstance(error_obj, dict) and not api_error_code:
1385
- api_error_code = error_obj.get("code") or error_obj.get("type") or ""
1386
- self._record_terminal_result(
1387
- text=str(result_text or ""),
1388
- is_error=bool(event.get("is_error")),
1389
- api_error_status=event.get("api_error_status"),
1390
- api_error_code=str(api_error_code or ""),
1391
- stop_reason=str(event.get("stop_reason") or ""),
1392
- )
1393
-
1394
- # ── Claude API raw stream format ────────────────────────────
1395
- elif event_type == "message_start":
1396
- self.event_format = self.event_format or "stream-json"
1397
- self.message_count += 1
1398
- self.is_active = True
1399
-
1400
- elif event_type == "message_stop":
1401
- self.current_tool = None
1402
- self.current_tool_input_summary = ""
1403
- self._in_tool_use = False
1404
- self._current_tool_input_parts = []
1405
- self._current_tool_id = ""
1406
-
1407
- elif event_type == "content_block_start":
1408
- content_block = event.get("content_block", {})
1409
- block_type = content_block.get("type", "")
1410
-
1411
- if block_type == "tool_use":
1412
- tool_name = content_block.get("name", "unknown")
1413
- self.current_tool = tool_name
1414
- self.current_tool_input_summary = ""
1415
- self.tool_call_counts[tool_name] += 1
1416
- self.total_tool_calls += 1
1417
- self._in_tool_use = True
1418
- self._current_tool_input_parts = []
1419
- self._current_tool_id = str(content_block.get("id") or content_block.get("tool_use_id") or "")
1420
-
1421
- elif block_type == "text":
1422
- self._text_buffer = ""
1423
- self._in_tool_use = False
1424
- self._current_tool_id = ""
1425
-
1426
- elif event_type == "content_block_delta":
1427
- delta = event.get("delta", {})
1428
- delta_type = delta.get("type", "")
1429
-
1430
- if delta_type == "text_delta":
1431
- text = delta.get("text", "")
1432
- self._text_buffer += text
1433
- # Keep last meaningful snippet
1434
- stripped = text.strip()
1435
- if stripped:
1436
- self.last_text_snippet = stripped[:120]
1437
- # Try to detect phase from text
1438
- self._detect_phase(text)
1439
- self._detect_terminal_error(text, require_error_context=True)
1440
-
1441
- elif delta_type == "input_json_delta":
1442
- partial = delta.get("partial_json", "")
1443
- self._current_tool_input_parts.append(partial)
1444
- # Build a summary from accumulated input
1445
- accumulated = "".join(self._current_tool_input_parts)
1446
- self.current_tool_input_summary = accumulated[:150]
1447
-
1448
- elif event_type == "content_block_stop":
1449
- if self._in_tool_use:
1450
- # Try to extract a better summary from complete tool input
1451
- full_input = "".join(self._current_tool_input_parts)
1452
- self._extract_tool_summary(full_input)
1453
- self._detect_phase(full_input)
1454
- self._record_agent_tool_call(
1455
- "claude",
1456
- self.current_tool,
1457
- full_input,
1458
- source_event="content_block.tool_use",
1459
- event_id=self._current_tool_id,
1460
- )
1461
- else:
1462
- # Text block finished - detect phase and terminal errors from accumulated text
1463
- if self._text_buffer:
1464
- self._detect_phase(self._text_buffer)
1465
- self._detect_terminal_error(
1466
- self._text_buffer,
1467
- require_error_context=True,
1468
- )
1469
- self._in_tool_use = False
1470
- self._current_tool_input_parts = []
1471
- self._current_tool_id = ""
1472
-
1473
- elif event_type == "error":
1474
- self.event_format = self.event_format or "stream-json"
1475
- error_msg = event.get("error", {}).get("message", "Unknown error")
1476
- errors = event.get("errors") or []
1477
- if isinstance(errors, list) and errors:
1478
- error_msg = "; ".join(str(e) for e in errors[:3])
1479
- self.errors.append(error_msg)
1480
- self._detect_terminal_error(str(error_msg))
1481
-
1482
- # ── CodeBuddy file-history-snapshot (ignore) ─────────────────
1483
- elif event_type == "file-history-snapshot":
1484
- return
1485
-
1486
- # Check for subagent indicator
1487
- if event.get("parent_tool_use_id"):
1488
- # Already recorded as child activity metadata near the top of process_event.
1489
- pass
1490
-
1491
-
1492
- def _canonical_subagent_key(self, provider, identifier, aliases=()):
1493
- """Return the existing canonical key for any alias, otherwise a new key."""
1494
- provider = str(provider or "unknown").strip() or "unknown"
1495
- keys = []
1496
- if identifier:
1497
- keys.append(f"{provider}:{identifier}")
1498
- for alias in aliases or ():
1499
- if alias:
1500
- alias_text = str(alias).strip()
1501
- if alias_text:
1502
- keys.append(f"{provider}:{alias_text}")
1503
- for key in keys:
1504
- canonical = self.subagent_aliases.get(key)
1505
- if canonical:
1506
- return canonical
1507
- return keys[0] if keys else f"{provider}:unknown:{len(self.subagent_records) + 1}"
1508
-
1509
- def _record_subagent_event(
1510
- self,
1511
- provider,
1512
- source_event,
1513
- *,
1514
- identifier="",
1515
- aliases=(),
1516
- status="unknown",
1517
- active=None,
1518
- spawn=False,
1519
- metadata=None,
1520
- ):
1521
- """Record authoritative session-log-derived subagent statistics."""
1522
- provider = str(provider or "unknown").strip() or "unknown"
1523
- source_event = str(source_event or "unknown").strip() or "unknown"
1524
- identifier = str(identifier or "").strip()
1525
- alias_values = [str(alias).strip() for alias in aliases or () if str(alias or "").strip()]
1526
- canonical = self._canonical_subagent_key(provider, identifier, alias_values)
1527
- record = self.subagent_records.setdefault(
1528
- canonical,
1529
- {
1530
- "id": identifier or canonical.split(":", 1)[-1],
1531
- "provider": provider,
1532
- "source_events": set(),
1533
- "aliases": set(),
1534
- "status": "unknown",
1535
- "active": False,
1536
- "spawned": False,
1537
- "metadata": {},
1538
- },
1539
- )
1540
- for alias in [identifier, *alias_values]:
1541
- if alias:
1542
- alias_key = f"{provider}:{alias}"
1543
- self.subagent_aliases[alias_key] = canonical
1544
- record["aliases"].add(alias)
1545
- if identifier:
1546
- if not record.get("id") or str(record.get("id", "")).startswith("unknown:"):
1547
- record["id"] = identifier
1548
- record.setdefault("observed_ids", set()).add(identifier)
1549
- for alias in alias_values:
1550
- record.setdefault("observed_ids", set()).add(alias)
1551
- record["source_events"].add(source_event)
1552
- self.subagent_source_providers.add(provider)
1553
- self.subagent_source_events[f"{provider}:{source_event}"] += 1
1554
- existing_status = _normalize_status(record.get("status"), default="unknown")
1555
- normalized_status = _normalize_status(status, default=existing_status)
1556
- if (
1557
- source_event == "parent_tool_use_id"
1558
- and existing_status in TERMINAL_SUBAGENT_STATUSES
1559
- ):
1560
- normalized_status = existing_status
1561
- active = False
1562
- if normalized_status:
1563
- record["status"] = normalized_status
1564
- if active is None:
1565
- record["active"] = record["status"] not in TERMINAL_SUBAGENT_STATUSES
1566
- else:
1567
- record["active"] = bool(active)
1568
- if spawn:
1569
- record["spawned"] = True
1570
- if isinstance(metadata, dict):
1571
- for key, value in metadata.items():
1572
- if value not in (None, "", [], {}):
1573
- record["metadata"][str(key)] = str(value)[:200]
1574
- self._refresh_normalized_subagent_totals()
1575
- return canonical
1576
-
1577
- def _refresh_normalized_subagent_totals(self):
1578
- """Refresh normalized totals from authoritative subagent records."""
1579
- counts = Counter()
1580
- active = 0
1581
- spawned = 0
1582
- for record in self.subagent_records.values():
1583
- status = _normalize_status(record.get("status"), default="unknown")
1584
- counts[status] += 1
1585
- if bool(record.get("active")):
1586
- active += 1
1587
- if bool(record.get("spawned")):
1588
- spawned += 1
1589
- self.subagent_status_counts = counts
1590
- self.active_subagents = active
1591
- self.subagents_spawned = spawned
1592
-
1593
- def _subagent_statistics(self):
1594
- """Return additive normalized subagent statistics for progress.json."""
1595
- records = []
1596
- for key, record in sorted(self.subagent_records.items()):
1597
- records.append(
1598
- {
1599
- "key": key,
1600
- "id": str(record.get("id") or ""),
1601
- "provider": str(record.get("provider") or "unknown"),
1602
- "status": _normalize_status(record.get("status"), default="unknown"),
1603
- "active": bool(record.get("active")),
1604
- "spawned": bool(record.get("spawned")),
1605
- "source_events": sorted(record.get("source_events") or []),
1606
- "aliases": sorted(record.get("aliases") or []),
1607
- "observed_ids": sorted(record.get("observed_ids") or []),
1608
- "metadata": dict(record.get("metadata") or {}),
1609
- }
1610
- )
1611
- observed_ids = []
1612
- for record in records:
1613
- identifier = record.get("id") or record.get("key")
1614
- if identifier:
1615
- observed_ids.append(str(identifier))
1616
- for observed in record.get("observed_ids") or []:
1617
- observed_ids.append(str(observed))
1618
- states = [
1619
- {"status": status, "count": count}
1620
- for status, count in self.subagent_status_counts.most_common()
1621
- ]
1622
- return {
1623
- "source": "session_log",
1624
- "providers": sorted(self.subagent_source_providers),
1625
- "spawned": self.subagents_spawned,
1626
- "active": self.active_subagents,
1627
- "status_counts": dict(self.subagent_status_counts),
1628
- "states": states,
1629
- "observed_ids": sorted(set(observed_ids)),
1630
- "source_events": dict(sorted(self.subagent_source_events.items())),
1631
- "parent_activity_ids": sorted(self.parent_subagent_activity_ids),
1632
- "records": records,
1633
- "child_activity_source": "filesystem_liveness_only",
1634
- }
1635
-
1636
- def _record_structured_subagent_metadata(self, event):
1637
- """Extract provider-specific subagent metadata when fields appear anywhere."""
1638
- if not isinstance(event, dict):
1639
- return
1640
- receiver_ids = event.get("receiver_thread_ids")
1641
- if isinstance(receiver_ids, list):
1642
- self._record_codex_child_thread_ids(receiver_ids)
1643
- agents_states = event.get("agents_states")
1644
- if isinstance(agents_states, dict):
1645
- self._update_subagent_status_counts(agents_states)
1646
- item = event.get("item")
1647
- if isinstance(item, dict):
1648
- nested_receivers = item.get("receiver_thread_ids")
1649
- if isinstance(nested_receivers, list):
1650
- self._record_codex_child_thread_ids(nested_receivers)
1651
- nested_states = item.get("agents_states")
1652
- if isinstance(nested_states, dict):
1653
- self._update_subagent_status_counts(nested_states)
1654
-
1655
- def _record_usage_and_permission_metadata(self, event):
1656
- """Record additive metadata required by Python runtime parity tests."""
1657
- if not isinstance(event, dict):
1658
- return
1659
- if event.get("usage") not in (None, "", {}):
1660
- self.has_usage = True
1661
- denial_text = json.dumps(event, ensure_ascii=False).lower()
1662
- if any(
1663
- marker in denial_text
1664
- for marker in (
1665
- "permission denied",
1666
- "permission_denied",
1667
- "permission denial",
1668
- "denied by user",
1669
- "user denied",
1670
- "not permitted",
1671
- )
1672
- ):
1673
- self.permission_denials.append(json.dumps(event, ensure_ascii=False)[:500])
1674
- self.permission_denials = self.permission_denials[-10:]
1675
-
1676
- def _detect_structured_terminal_fields(self, event):
1677
- """Detect provider-neutral terminal/context errors before format routing."""
1678
- if not isinstance(event, dict):
1679
- return
1680
-
1681
- code_parts = []
1682
- text_parts = []
1683
- terminal_parts = []
1684
-
1685
- for key in ("fatal_error_code", "api_error_code", "error_code", "stop_reason"):
1686
- value = event.get(key)
1687
- if isinstance(value, (str, int, float)) and str(value).strip():
1688
- code_parts.append(str(value))
1689
-
1690
- for key in ("terminal_result_text", "message", "result"):
1691
- value = event.get(key)
1692
- if isinstance(value, (str, int, float)) and str(value).strip():
1693
- text_parts.append(str(value))
1694
- terminal_parts.append(str(value))
1695
-
1696
- error_obj = event.get("error")
1697
- if isinstance(error_obj, dict):
1698
- for key in ("type", "code", "message"):
1699
- value = error_obj.get(key)
1700
- if isinstance(value, (str, int, float)) and str(value).strip():
1701
- text_parts.append(str(value))
1702
- terminal_parts.append(str(value))
1703
- elif isinstance(error_obj, (str, int, float)) and str(error_obj).strip():
1704
- text_parts.append(str(error_obj))
1705
- terminal_parts.append(str(error_obj))
1706
-
1707
- combined_code_text = " ".join(code_parts)
1708
- combined_text = " ".join(code_parts + text_parts)
1709
- if not combined_text:
1710
- return
1711
-
1712
- error_like = (
1713
- bool(code_parts)
1714
- or event.get("api_error_status") not in (None, "")
1715
- or bool(event.get("last_result_is_error"))
1716
- or bool(event.get("is_error"))
1717
- or _has_error_context(combined_text)
1718
- )
1719
- normalized_code = detect_api_error_code(
1720
- combined_code_text,
1721
- require_error_context=False,
1722
- structured_code=True,
1723
- ) or detect_api_error_code(
1724
- combined_text,
1725
- require_error_context=not error_like,
1726
- structured_code=bool(code_parts),
1727
- )
1728
- if not normalized_code:
1729
- return
1730
-
1731
- self.last_result_is_error = True
1732
- api_error_status = event.get("api_error_status") or event.get("status")
1733
- if api_error_status not in (None, ""):
1734
- try:
1735
- self.api_error_status = int(api_error_status)
1736
- except (TypeError, ValueError):
1737
- self.api_error_status = api_error_status
1738
- self.api_error_code = normalized_code
1739
- self.fatal_error_code = normalized_code
1740
- terminal_text = " ".join(terminal_parts) or combined_text
1741
- self.terminal_result_text = terminal_text[:1000]
1742
- if terminal_text.strip():
1743
- self.last_text_snippet = terminal_text.strip()[:120]
1744
- if not self.errors or self.errors[-1] != normalized_code:
1745
- self.errors.append(normalized_code)
1746
-
1747
- def _record_agent_tool_call(self, provider, tool_name, raw_args, *, source_event="tool_use", event_id=""):
1748
- """Record delegated execution tool calls as session-log subagent spawns."""
1749
- if tool_name not in {"Agent", "Task"}:
1750
- return
1751
- if isinstance(raw_args, dict):
1752
- args = raw_args
1753
- elif isinstance(raw_args, str):
1754
- try:
1755
- args = json.loads(raw_args)
1756
- except (json.JSONDecodeError, TypeError):
1757
- args = {"raw_args": raw_args}
1758
- else:
1759
- args = {}
1760
- if not any(args.get(key) for key in ("subagent_type", "prompt", "description")):
1761
- return
1762
- explicit_ids = []
1763
- for key in ("id", "tool_use_id", "call_id", "callId", "task_id", "taskId"):
1764
- value = args.get(key) if isinstance(args, dict) else None
1765
- if value:
1766
- explicit_ids.append(str(value))
1767
- if event_id:
1768
- explicit_ids.append(str(event_id))
1769
- fallback = _stable_subagent_digest(provider, tool_name, args)
1770
- identifier = explicit_ids[0] if explicit_ids else f"{tool_name}:{fallback}"
1771
- aliases = [*explicit_ids, f"{tool_name}:{fallback}"]
1772
- metadata = {
1773
- "tool": tool_name,
1774
- "subagent_type": args.get("subagent_type", "") if isinstance(args, dict) else "",
1775
- "description": args.get("description", "") if isinstance(args, dict) else "",
1776
- "run_in_background": args.get("run_in_background", "") if isinstance(args, dict) else "",
1777
- }
1778
- self._record_subagent_event(
1779
- provider,
1780
- source_event,
1781
- identifier=identifier,
1782
- aliases=aliases,
1783
- status="running",
1784
- active=True,
1785
- spawn=True,
1786
- metadata=metadata,
1787
- )
1788
-
1789
- def _record_cb_agent_tool_call(self, tool_name, raw_args, *, event_id="", source_event="tool_use"):
1790
- """Record a CodeBuddy delegated execution invocation for sub-agent tracking."""
1791
- self._record_agent_tool_call(
1792
- "codebuddy",
1793
- tool_name,
1794
- raw_args,
1795
- source_event=source_event,
1796
- event_id=event_id,
1797
- )
1798
-
1799
- def _record_terminal_result(self, text="", is_error=False, api_error_status=None, api_error_code="", stop_reason=""):
1800
- """Record a Claude Code terminal result event."""
1801
- terminal_text = str(text or "")
1802
- self.last_result_is_error = bool(is_error)
1803
- if api_error_status not in (None, ""):
1804
- try:
1805
- self.api_error_status = int(api_error_status)
1806
- except (TypeError, ValueError):
1807
- self.api_error_status = api_error_status
1808
- error_like_result = (
1809
- self.last_result_is_error
1810
- or api_error_status not in (None, "")
1811
- or bool(api_error_code)
1812
- or _has_error_context(terminal_text)
1813
- )
1814
- normalized_code = detect_api_error_code(
1815
- " ".join([str(api_error_code or ""), terminal_text]),
1816
- require_error_context=not error_like_result,
1817
- )
1818
- if normalized_code:
1819
- self.api_error_code = normalized_code
1820
- self.fatal_error_code = normalized_code
1821
- elif api_error_code:
1822
- self.api_error_code = str(api_error_code)
1823
- self.terminal_result_text = terminal_text[:1000]
1824
- if terminal_text.strip():
1825
- self.last_text_snippet = terminal_text.strip()[:120]
1826
- if not self.last_result_is_error and not self.fatal_error_code:
1827
- self.terminal_success_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
1828
- elif self.fatal_error_code:
1829
- self.errors.append(self.fatal_error_code)
1830
-
1831
- def _detect_terminal_error(self, text, require_error_context=False):
1832
- """Detect fatal context-window errors from unstructured text."""
1833
- code = detect_api_error_code(
1834
- str(text or ""),
1835
- require_error_context=require_error_context,
1836
- )
1837
- if not code:
1838
- return
1839
- self.last_result_is_error = True
1840
- self.api_error_code = code
1841
- self.fatal_error_code = code
1842
- self.terminal_result_text = str(text or "")[:1000]
1843
- if text:
1844
- self.last_text_snippet = str(text).strip()[:120]
1845
-
1846
- def _detect_phase(self, text):
1847
- """Detect pipeline phase from text content.
1848
-
1849
- Uses monotonic (forward-only) progression to avoid false positives.
1850
- Strong keywords (skill invocations) always trigger; weak keywords
1851
- only trigger for phases at or ahead of the current position.
1852
- """
1853
- text_lower = text.lower()
1854
- current_idx = (
1855
- PHASE_ORDER.index(self.current_phase)
1856
- if self.current_phase in PHASE_ORDER
1857
- else -1
1858
- )
1859
-
1860
- for phase, kw_groups in PHASE_KEYWORDS.items():
1861
- phase_idx = PHASE_ORDER.index(phase)
1862
-
1863
- # Check strong keywords — high confidence but still forward-only
1864
- for keyword in kw_groups.get("strong", []):
1865
- if keyword.lower() in text_lower:
1866
- if phase_idx >= current_idx:
1867
- self.current_phase = phase
1868
- if phase not in self.detected_phases:
1869
- self.detected_phases.append(phase)
1870
- return
1871
- # Backward strong match — skip this phase but do NOT
1872
- # early-return, so forward weak matches can still fire.
1873
- break
1874
-
1875
- # Check weak keywords — only trigger for forward phases
1876
- if phase_idx >= current_idx:
1877
- for keyword in kw_groups.get("weak", []):
1878
- if keyword.lower() in text_lower:
1879
- self.current_phase = phase
1880
- if phase not in self.detected_phases:
1881
- self.detected_phases.append(phase)
1882
- return
1883
-
1884
- def _extract_tool_summary(self, raw_input):
1885
- """Extract a human-readable summary from tool input JSON string."""
1886
- try:
1887
- data = json.loads(raw_input)
1888
- self._extract_tool_summary_from_dict(data)
1889
- except (json.JSONDecodeError, TypeError):
1890
- # Keep whatever partial summary we had
1891
- pass
1892
-
1893
- def _extract_tool_summary_from_dict(self, data):
1894
- """Extract a human-readable summary from tool input dict."""
1895
- if isinstance(data, dict):
1896
- # Common patterns in tool inputs
1897
- if "description" in data:
1898
- self.current_tool_input_summary = str(data["description"])[:100]
1899
- elif "command" in data:
1900
- self.current_tool_input_summary = str(data["command"])[:100]
1901
- elif "file_path" in data:
1902
- self.current_tool_input_summary = str(data["file_path"])[:100]
1903
- elif "pattern" in data:
1904
- self.current_tool_input_summary = str(data["pattern"])[:100]
1905
- elif "query" in data:
1906
- self.current_tool_input_summary = str(data["query"])[:100]
1907
- elif "prompt" in data:
1908
- self.current_tool_input_summary = str(data["prompt"])[:100]
1909
-
1910
- def _update_subagent_status_counts(self, agents_states):
1911
- """Track Codex subagent state counts from session-log collab items."""
1912
- if not isinstance(agents_states, dict):
1913
- return
1914
- for agent_id, state in agents_states.items():
1915
- if not isinstance(state, dict):
1916
- continue
1917
- status = _normalize_status(state.get("status"), default="unknown")
1918
- message = state.get("message")
1919
- if message:
1920
- self.last_text_snippet = str(message).strip()[:120]
1921
- self._detect_phase(str(message))
1922
- identifier = str(state.get("thread_id") or state.get("id") or agent_id or "")
1923
- aliases = [agent_id, state.get("thread_id", ""), state.get("id", "")]
1924
- self._record_subagent_event(
1925
- "codex",
1926
- "agents_states",
1927
- identifier=identifier,
1928
- aliases=aliases,
1929
- status=status,
1930
- active=status not in TERMINAL_SUBAGENT_STATUSES,
1931
- spawn=True,
1932
- metadata={
1933
- "message": message or "",
1934
- "name": state.get("name", ""),
1935
- "role": state.get("role", ""),
1936
- },
1937
- )
1938
-
1939
- def _record_codex_child_thread_ids(self, thread_ids):
1940
- """Remember Codex child thread IDs reported by session-log collab tool calls."""
1941
- if not isinstance(thread_ids, list):
1942
- return
1943
- for thread_id in thread_ids:
1944
- if isinstance(thread_id, str) and thread_id.strip():
1945
- thread_id = thread_id.strip()
1946
- self.codex_child_thread_ids.add(thread_id)
1947
- self._record_subagent_event(
1948
- "codex",
1949
- "receiver_thread_ids",
1950
- identifier=thread_id,
1951
- aliases=[thread_id],
1952
- status="running",
1953
- active=True,
1954
- spawn=True,
1955
- metadata={"thread_id": thread_id},
1956
- )
1957
-
1958
- def _codex_sessions_dir(self):
1959
- """Return the Codex sessions directory for the current environment."""
1960
- codex_home = os.environ.get("CODEX_HOME")
1961
- if codex_home:
1962
- return Path(codex_home).expanduser() / "sessions"
1963
- return Path.home() / ".codex" / "sessions"
1964
-
1965
- def _find_codex_child_session_file(self, thread_id):
1966
- """Find a Codex transcript file for a child thread ID."""
1967
- sessions_dir = self._codex_sessions_dir()
1968
- if not sessions_dir.exists():
1969
- return None
1970
-
1971
- try:
1972
- matches = list(sessions_dir.rglob(f"*{thread_id}.jsonl"))
1973
- except OSError:
1974
- return None
1975
-
1976
- if not matches:
1977
- return None
1978
-
1979
- try:
1980
- matches.sort(key=lambda path: path.stat().st_mtime, reverse=True)
1981
- except OSError:
1982
- pass
1983
- return str(matches[0])
1984
-
1985
- def _is_tracked_claude_subagent_state(self, state):
1986
- """Return true for Claude Code task events representing in-process agents."""
1987
- if not isinstance(state, dict):
1988
- return False
1989
- task_type = str(state.get("task_type") or "")
1990
- task_type_lower = task_type.lower()
1991
- subagent_type = str(state.get("subagent_type") or "")
1992
- if task_type_lower == "local_bash":
1993
- return False
1994
- tracked_types = {"in_process_teammate", "subagent", "agent", "teammate"}
1995
- if task_type_lower in tracked_types:
1996
- return True
1997
- if task_type_lower == "local_agent" and subagent_type:
1998
- return True
1999
- summary = str(state.get("summary") or "")
2000
- return bool(
2001
- not task_type
2002
- and summary.lower().startswith(("dev:", "reviewer:", "agent:"))
2003
- )
2004
-
2005
- def _has_tracked_claude_subagent_task(self):
2006
- """Return true once a Claude Code local-agent/subagent task has been observed."""
2007
- return any(
2008
- self._is_tracked_claude_subagent_state(state)
2009
- for state in self.claude_task_states.values()
2010
- )
2011
-
2012
- def _update_claude_subagent_status_counts(self):
2013
- """Track Claude Code in-process teammate task state counts from session.log."""
2014
- for task_id, state in self.claude_task_states.items():
2015
- if not self._is_tracked_claude_subagent_state(state):
2016
- continue
2017
- status = _normalize_status(state.get("status"), default="unknown")
2018
- summary = state.get("summary") or state.get("subagent_type")
2019
- if summary:
2020
- self.last_text_snippet = str(summary).strip()[:120]
2021
- self._detect_phase(str(summary))
2022
- self._record_subagent_event(
2023
- "claude",
2024
- "system.task",
2025
- identifier=str(task_id),
2026
- aliases=[state.get("tool_use_id", "")],
2027
- status=status,
2028
- active=status not in TERMINAL_SUBAGENT_STATUSES,
2029
- spawn=True,
2030
- metadata={
2031
- "task_type": state.get("task_type", ""),
2032
- "subagent_type": state.get("subagent_type", ""),
2033
- "summary": state.get("summary", ""),
2034
- "tool_use_id": state.get("tool_use_id", ""),
2035
- },
2036
- )
2037
-
2038
- def _claude_projects_dir(self):
2039
- """Return the Claude Code projects directory for transcript lookup."""
2040
- projects_dir = os.environ.get("CLAUDE_PROJECTS_DIR")
2041
- if projects_dir:
2042
- return Path(projects_dir).expanduser()
2043
- claude_config_dir = os.environ.get("CLAUDE_CONFIG_DIR")
2044
- if claude_config_dir:
2045
- return Path(claude_config_dir).expanduser() / "projects"
2046
- claude_home = os.environ.get("CLAUDE_HOME")
2047
- if claude_home:
2048
- return Path(claude_home).expanduser() / "projects"
2049
- return Path.home() / ".claude" / "projects"
2050
-
2051
- def _claude_project_key(self):
2052
- """Encode cwd the same way Claude Code stores project transcript dirs."""
2053
- cwd = self.claude_cwd
2054
- if not cwd:
2055
- return ""
2056
- return cwd.replace("\\", "-").replace("/", "-").replace(":", "")
2057
-
2058
- def _find_claude_child_session_files(self):
2059
- """Find Claude Code subagent transcripts for this parent session."""
2060
- if not self.claude_session_id:
2061
- return []
2062
-
2063
- projects_dir = self._claude_projects_dir()
2064
- if not projects_dir.exists():
2065
- return []
2066
-
2067
- candidates = []
2068
- project_key = self._claude_project_key()
2069
- if project_key:
2070
- candidates.append(
2071
- projects_dir / project_key / self.claude_session_id / "subagents"
2072
- )
2073
-
2074
- for candidate in candidates:
2075
- if candidate.exists():
2076
- try:
2077
- return sorted(candidate.glob("*.jsonl"))
2078
- except OSError:
2079
- return []
2080
-
2081
- # Fallback for non-standard cwd encoding or custom Claude homes. Avoid
2082
- # repeatedly walking every stored transcript before any Agent task exists.
2083
- if not self._has_tracked_claude_subagent_task():
2084
- return []
2085
-
2086
- fallback_scan_key = f"{projects_dir}:{self.claude_session_id}"
2087
- now = time.monotonic()
2088
- if (
2089
- self._last_claude_fallback_scan_key == fallback_scan_key
2090
- and now - self._last_claude_fallback_scan_at < self._claude_fallback_scan_interval_seconds
2091
- ):
2092
- return self._claude_child_session_files
2093
- self._last_claude_fallback_scan_key = fallback_scan_key
2094
- self._last_claude_fallback_scan_at = now
2095
- try:
2096
- matches = sorted(projects_dir.rglob(f"{self.claude_session_id}/subagents/*.jsonl"))
2097
- except OSError:
2098
- return []
2099
- return matches
2100
-
2101
- def _cb_projects_dir(self):
2102
- """Return the CodeBuddy projects directory for transcript lookup.
2103
-
2104
- CodeBuddy stores per-project session transcripts and sub-agent data
2105
- under ~/.codebuddy/projects/{projectDir}/{sessionId}/.
2106
- """
2107
- cb_config = os.environ.get("CODEBUDDY_CONFIG_DIR")
2108
- if cb_config:
2109
- return Path(cb_config).expanduser() / "projects"
2110
- cb_home = os.environ.get("CODEBUDDY_HOME")
2111
- if cb_home:
2112
- return Path(cb_home).expanduser() / "projects"
2113
- return Path.home() / ".codebuddy" / "projects"
2114
-
2115
- def _cb_project_key(self):
2116
- """Encode cwd the same way CodeBuddy stores project subdirs.
2117
-
2118
- CodeBuddy uses the same sanitisation as Claude Code (\\, /, : → -)
2119
- but strips the leading '-' so "/Users/test/MyProject" becomes
2120
- "Users-test-MyProject".
2121
- """
2122
- cwd = self.cb_cwd
2123
- if not cwd:
2124
- return ""
2125
- return cwd.replace("\\", "-").replace("/", "-").replace(":", "").lstrip("-")
2126
-
2127
- def _find_cb_child_session_files(self):
2128
- """Find CodeBuddy subagent transcript data for this parent session.
2129
-
2130
- CodeBuddy sub-agents store tool-results/{callId}.txt files; conversation
2131
- transcripts are not (as of 2026) written as agent-*.jsonl files in the
2132
- subagents/ directory. We track the tool-results .txt files as a proxy
2133
- for child activity so the heartbeat monitor can extend the stale-kill
2134
- window while sub-agents are running.
2135
- """
2136
- if not self.cb_session_id:
2137
- return []
2138
-
2139
- projects_dir = self._cb_projects_dir()
2140
- if not projects_dir.exists():
2141
- return []
2142
-
2143
- project_key = self._cb_project_key()
2144
- if not project_key:
2145
- return []
2146
-
2147
- subagents_dir = (
2148
- projects_dir / project_key / self.cb_session_id / "subagents"
2149
- )
2150
- if not subagents_dir.exists():
2151
- return []
2152
-
2153
- # Collect all files under each agent-{id} subdirectory. These are
2154
- # currently tool-results/{callId}.txt files, but the glob also picks
2155
- # up future agent-*.jsonl transcripts should CodeBuddy add them.
2156
- try:
2157
- return sorted(
2158
- p for p in subagents_dir.glob("**/*")
2159
- if p.is_file()
2160
- )
2161
- except OSError:
2162
- return []
2163
-
2164
- def refresh_child_session_activity(self, force=False):
2165
- """Refresh child transcript file stats.
2166
-
2167
- The heartbeat monitor uses this activity signature to treat subagent
2168
- transcript growth as real progress while the parent session is blocked
2169
- waiting for a child agent/tool result. Supports Codex child threads,
2170
- Claude Code in-process teammate transcripts, and CodeBuddy sub-agent
2171
- file activity under subagents/.
2172
- """
2173
- previous_signature = self.child_activity_signature
2174
-
2175
- if (
2176
- not self.codex_child_thread_ids
2177
- and not self.claude_session_id
2178
- and not self.cb_session_id
2179
- ):
2180
- self.child_session_files = []
2181
- self.child_total_bytes = 0
2182
- self.child_activity_signature = ""
2183
- self.last_child_activity_at = ""
2184
- return previous_signature != self.child_activity_signature
2185
-
2186
- now = time.monotonic()
2187
- should_scan = (
2188
- force
2189
- or self._last_child_scan_at == 0.0
2190
- or (now - self._last_child_scan_at >= 2.0)
2191
- )
2192
- if should_scan:
2193
- for thread_id in sorted(self.codex_child_thread_ids):
2194
- path = self._codex_child_session_paths.get(thread_id)
2195
- if not path or not os.path.exists(path):
2196
- found = self._find_codex_child_session_file(thread_id)
2197
- if found:
2198
- self._codex_child_session_paths[thread_id] = found
2199
- self._claude_child_session_files = self._find_claude_child_session_files()
2200
- self._cb_child_session_files = self._find_cb_child_session_files()
2201
- self._last_child_scan_at = now
2202
-
2203
- # Filesystem scanning below is intentionally liveness-only. The
2204
- # session-log-derived subagent_* fields are updated exclusively by
2205
- # process_event()/record helpers and are not inferred from file counts.
2206
- files = []
2207
- signature_parts = []
2208
- total_bytes = 0
2209
- max_mtime = 0.0
2210
-
2211
- def add_file(kind, identifier, path):
2212
- nonlocal total_bytes, max_mtime
2213
- try:
2214
- stat = os.stat(path)
2215
- except OSError:
2216
- return
2217
- path_str = str(path)
2218
- total_bytes += stat.st_size
2219
- max_mtime = max(max_mtime, stat.st_mtime)
2220
- mtime_ns = getattr(stat, "st_mtime_ns", int(stat.st_mtime * 1_000_000_000))
2221
- signature_parts.append(f"{kind}:{identifier}:{stat.st_size}:{mtime_ns}")
2222
- files.append(
2223
- {
2224
- "kind": kind,
2225
- "thread_id": identifier,
2226
- "path": path_str,
2227
- "size": stat.st_size,
2228
- "mtime": datetime.fromtimestamp(
2229
- stat.st_mtime, timezone.utc
2230
- ).strftime("%Y-%m-%dT%H:%M:%SZ"),
2231
- }
2232
- )
2233
-
2234
- for thread_id in sorted(self.codex_child_thread_ids):
2235
- path = self._codex_child_session_paths.get(thread_id)
2236
- if path:
2237
- add_file("codex", thread_id, path)
2238
-
2239
- for path in self._claude_child_session_files:
2240
- add_file("claude", path.stem, path)
2241
-
2242
- for path in self._cb_child_session_files:
2243
- # Identifier for CodeBuddy sub-agent files: use the parent
2244
- # directory name (agent-{id}) so heartbeat can distinguish
2245
- # activity across different sub-agent instances.
2246
- parent_name = path.parent.name if hasattr(path, "parent") else ""
2247
- identifier = parent_name if parent_name.startswith("agent-") else path.name
2248
- add_file("codebuddy", identifier, path)
2249
-
2250
- self.child_session_files = files
2251
- self.child_total_bytes = total_bytes
2252
- self.child_activity_signature = "|".join(signature_parts)
2253
- self.last_child_activity_at = (
2254
- datetime.fromtimestamp(max_mtime, timezone.utc).strftime(
2255
- "%Y-%m-%dT%H:%M:%SZ"
2256
- )
2257
- if max_mtime
2258
- else ""
2259
- )
2260
- return previous_signature != self.child_activity_signature
2261
-
2262
- def to_dict(self):
2263
- """Export current state as a dictionary for JSON serialization."""
2264
- self.refresh_child_session_activity()
2265
- tool_calls = [
2266
- {"name": name, "count": count}
2267
- for name, count in self.tool_call_counts.most_common()
2268
- ]
2269
- subagent_stats = self._subagent_statistics()
2270
- return {
2271
- "updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
2272
- "event_format": self.event_format,
2273
- "event_type_counts": dict(self.event_type_counts),
2274
- "claude_session_id": self.claude_session_id,
2275
- "result_subtype": self.result_subtype,
2276
- "stop_reason": self.stop_reason,
2277
- "cursor_session_id": self.cursor_session_id,
2278
- "has_usage": self.has_usage,
2279
- "permission_denial_count": len(self.permission_denials),
2280
- "permission_denials": self.permission_denials[-10:],
2281
- "message_count": self.message_count,
2282
- "current_tool": self.current_tool,
2283
- "current_tool_input_summary": self.current_tool_input_summary,
2284
- "current_phase": self.current_phase,
2285
- "detected_phases": self.detected_phases,
2286
- "tool_calls": tool_calls,
2287
- "total_tool_calls": self.total_tool_calls,
2288
- "subagent_statistics": subagent_stats,
2289
- "child_activity_source": "filesystem_liveness_only",
2290
- "child_thread_ids": sorted(self.codex_child_thread_ids),
2291
- # Filesystem child activity is a heartbeat liveness fallback only.
2292
- # Authoritative subagent counts/statuses above come from session.log.
2293
- "child_session_files": self.child_session_files,
2294
- "child_total_bytes": self.child_total_bytes,
2295
- "child_activity_signature": self.child_activity_signature,
2296
- "last_child_activity_at": self.last_child_activity_at,
2297
- "cb_session_id": self.cb_session_id,
2298
- "cb_cwd": self.cb_cwd,
2299
- "last_text_snippet": self.last_text_snippet,
2300
- "last_result_is_error": self.last_result_is_error,
2301
- "api_error_status": self.api_error_status,
2302
- "api_error_code": self.api_error_code,
2303
- "terminal_result_text": self.terminal_result_text,
2304
- "terminal_success_at": self.terminal_success_at,
2305
- "fatal_error_code": self.fatal_error_code,
2306
- "is_active": self.is_active,
2307
- "errors": self.errors[-10:], # Keep last 10 errors
2308
- }
2309
-
2310
-
2311
- def atomic_write_json(data, filepath):
2312
- """Write JSON data atomically using tmp file + rename."""
2313
- dir_path = os.path.dirname(filepath)
2314
- tmp_path = None
2315
- try:
2316
- fd, tmp_path = tempfile.mkstemp(dir=dir_path, suffix=".tmp")
2317
- with os.fdopen(fd, "w") as f:
2318
- json.dump(data, f, indent=2)
2319
- f.write("\n")
2320
- os.rename(tmp_path, filepath)
2321
- except OSError:
2322
- # Best effort - remove tmp file if rename failed
2323
- if tmp_path:
2324
- try:
2325
- os.unlink(tmp_path)
2326
- except OSError:
2327
- pass
2328
-
2329
42
 
2330
43
  def tail_and_parse(session_log, progress_file, poll_interval=0.5):
2331
44
  """Tail session log and parse stream-json events."""
@@ -2348,16 +61,15 @@ def tail_and_parse(session_log, progress_file, poll_interval=0.5):
2348
61
  tuple(state.get("errors", [])),
2349
62
  )
2350
63
 
2351
- # Wait for log file to appear
2352
64
  wait_count = 0
2353
65
  while not os.path.exists(session_log):
2354
66
  time.sleep(poll_interval)
2355
67
  wait_count += 1
2356
- if wait_count > 120: # 60 seconds max wait
68
+ if wait_count > 120:
2357
69
  sys.stderr.write(f"Timeout waiting for {session_log}\n")
2358
70
  sys.exit(1)
2359
71
 
2360
- with open(session_log, "r") as f:
72
+ with open(session_log, "r", encoding="utf-8", errors="replace") as f:
2361
73
  idle_count = 0
2362
74
  while True:
2363
75
  line = f.readline()
@@ -2370,10 +82,6 @@ def tail_and_parse(session_log, progress_file, poll_interval=0.5):
2370
82
  event = json.loads(line)
2371
83
  tracker.process_event(event)
2372
84
  except json.JSONDecodeError:
2373
- # Not a JSON line (could be stderr mixed in). Use it as a
2374
- # text snippet and only treat it as terminal when it has a
2375
- # strong API/runtime error marker; ordinary assistant prose
2376
- # can discuss context limits without being fatal.
2377
85
  stripped = line.strip()
2378
86
  if stripped and len(stripped) > 5:
2379
87
  tracker.last_text_snippet = stripped[:120]
@@ -2385,7 +93,6 @@ def tail_and_parse(session_log, progress_file, poll_interval=0.5):
2385
93
  last_write_state = current_state_key
2386
94
  continue
2387
95
 
2388
- # Write progress if state changed
2389
96
  current_state = tracker.to_dict()
2390
97
  current_state_key = state_key(current_state)
2391
98
  if current_state_key != last_write_state:
@@ -2393,8 +100,6 @@ def tail_and_parse(session_log, progress_file, poll_interval=0.5):
2393
100
  last_write_state = current_state_key
2394
101
  else:
2395
102
  idle_count += 1
2396
- # Every 2 seconds of no parent log data, refresh child Codex
2397
- # transcript stats and write if child activity advanced.
2398
103
  if idle_count % 4 == 0:
2399
104
  current_state = tracker.to_dict()
2400
105
  current_state_key = state_key(current_state)
@@ -2402,7 +107,6 @@ def tail_and_parse(session_log, progress_file, poll_interval=0.5):
2402
107
  atomic_write_json(current_state, progress_file)
2403
108
  last_write_state = current_state_key
2404
109
 
2405
- # After 3600 idle cycles (30 min), mark inactive and exit
2406
110
  if idle_count > 3600:
2407
111
  tracker.is_active = False
2408
112
  atomic_write_json(tracker.to_dict(), progress_file)
@@ -2410,7 +114,6 @@ def tail_and_parse(session_log, progress_file, poll_interval=0.5):
2410
114
 
2411
115
  time.sleep(poll_interval)
2412
116
 
2413
- # Final write
2414
117
  tracker.is_active = False
2415
118
  atomic_write_json(tracker.to_dict(), progress_file)
2416
119
 
@@ -2421,7 +124,6 @@ def main():
2421
124
  parser.add_argument("--progress-file", required=True, help="Path to write progress.json")
2422
125
  args = parser.parse_args()
2423
126
 
2424
- # Handle graceful shutdown
2425
127
  def handle_signal(signum, frame):
2426
128
  sys.exit(0)
2427
129
 
@@ -2430,8 +132,9 @@ def main():
2430
132
 
2431
133
  try:
2432
134
  tail_and_parse(args.session_log, args.progress_file)
2433
- except SystemExit:
2434
- pass
135
+ except SystemExit as exc:
136
+ if exc.code not in (None, 0):
137
+ raise
2435
138
  except Exception as e:
2436
139
  sys.stderr.write(f"parse-stream-progress.py error: {e}\n")
2437
140
  sys.exit(1)