@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +149 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3633 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +141 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +93 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +288 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +426 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +400 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +59531 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,403 @@
1
+ #!/usr/bin/env python3
2
+ """Readiness check and synthetic local filter probe; records no metrics and never starts a Devin session."""
3
+ # CLI startup imports only builtins until isolated re-execution.
4
+ import sys
5
+ if __name__ == '__main__' and not sys.flags.isolated:
6
+ import posix
7
+ try:
8
+ posix.execv(sys.executable, [sys.executable, '-I', *sys.argv])
9
+ except OSError as _isolation_error:
10
+ print('Token Optimizer: isolated startup refused: ' + str(_isolation_error), file=sys.stderr)
11
+ raise SystemExit(2)
12
+
13
+
14
+ import argparse
15
+ import hashlib
16
+ import stat
17
+ import json
18
+ import os
19
+ from pathlib import Path
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+
24
+ # Bootstrap uses only stdlib already imported by the entrypoint.
25
+ _source_root = Path(__file__).resolve().parent
26
+ # Source development is the canonical checkout layout, not a directory-name bypass.
27
+ _source_checkout = _source_root.parent.parent.parent
28
+ _source_development = (
29
+ _source_root == _source_checkout / 'skills/token-optimizer/scripts'
30
+ and (_source_root / 'devin_install.py').is_file()
31
+ and (_source_checkout / 'devin/SKILL.md').is_file()
32
+ and (_source_checkout / 'README.md').is_file()
33
+ and not any((directory / leaf).exists() or (directory / leaf).is_symlink()
34
+ for directory in (_source_root, *_source_root.parents)
35
+ for leaf in ('install.json', 'consent.json'))
36
+ )
37
+ if _source_development and __name__ == '__main__':
38
+ # -I removed ambient paths; restore only the checked development scripts root.
39
+ sys.path.insert(0, str(_source_root))
40
+ if not _source_development:
41
+ try:
42
+ if __name__ != '__main__' and not any(
43
+ getattr(finder, '_devin_source_root', None) == _source_root for finder in sys.meta_path):
44
+ raise ImportError('installed entrypoint requires command-line use or prior activation')
45
+ def _bootstrap_read(path, limit):
46
+ for component in [*reversed(path.parents), path]:
47
+ if component.is_symlink():
48
+ raise ImportError('symlink bootstrap path refused')
49
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
50
+ try:
51
+ info = os.fstat(fd)
52
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid()
53
+ or info.st_nlink != 1 or info.st_mode & 0o077 or info.st_size > limit):
54
+ raise ImportError('private bounded bootstrap file required')
55
+ with os.fdopen(fd, 'rb', closefd=False) as stream:
56
+ content = stream.read(limit + 1)
57
+ if len(content) > limit:
58
+ raise ImportError('bootstrap file exceeds bound')
59
+ return content
60
+ finally:
61
+ os.close(fd)
62
+ _source_path = _source_root / 'devin_source.py'
63
+ _source_record = json.loads(_bootstrap_read(_source_root.parent / 'install.json', 65536))
64
+ if (not isinstance(_source_record, dict) or _source_record.get('owner') != 'devin-output-filter-v1'
65
+ or not isinstance(_source_record.get('files'), dict)):
66
+ raise ImportError('invalid bootstrap manifest')
67
+ _source_bytes = _bootstrap_read(_source_path, 8 * 1024 * 1024)
68
+ if hashlib.sha256(_source_bytes).hexdigest() != _source_record['files'].get(str(_source_path)):
69
+ raise ImportError('bootstrap source differs from install manifest')
70
+ _source_namespace = {}
71
+ exec(compile(_source_bytes, str(_source_path), 'exec'), _source_namespace)
72
+ _source_namespace['activate'](_source_root)
73
+ except (OSError, ValueError, TypeError, ImportError, SyntaxError, RecursionError) as _bootstrap_error:
74
+ _bootstrap_message = 'Token Optimizer: bootstrap manifest gate refused: ' + str(_bootstrap_error) + '. Originals remain unchanged.'
75
+ if __name__ == '__main__':
76
+ print(_bootstrap_message, file=sys.stderr)
77
+ raise SystemExit(2)
78
+ raise ImportError(_bootstrap_message) from None
79
+
80
+
81
+ try:
82
+ import devin_state as state
83
+ except (ImportError, SyntaxError) as _initial_error:
84
+ _initial_message = 'Token Optimizer: bootstrap manifest gate refused: ' + str(_initial_error) + '. Originals remain unchanged.'
85
+ if __name__ == '__main__':
86
+ print(_initial_message, file=sys.stderr)
87
+ raise SystemExit(2)
88
+ raise ImportError(_initial_message) from None
89
+
90
+
91
+ def _desktop_app_roots():
92
+ """Heuristic locations/layout only, not an authoritative app inventory."""
93
+ # Candidate paths and applicationName are unverified heuristics; vendor
94
+ # documentation does not list them as a supported detection interface.
95
+ return [Path('/Applications/Devin.app/Contents/Resources/app'),
96
+ Path.home() / 'Applications/Devin.app/Contents/Resources/app',
97
+ Path.home() / '.local/share/Devin/resources/app']
98
+
99
+
100
+ def local_agent_surfaces() -> dict:
101
+ desktop = []
102
+ bundled = []
103
+ for root in _desktop_app_roots():
104
+ try:
105
+ state.no_symlinks(root)
106
+ product = root / 'product.json'
107
+ fd = os.open(product, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
108
+ try:
109
+ info = os.fstat(fd)
110
+ if not stat.S_ISREG(info.st_mode) or info.st_size > 1024 * 1024:
111
+ continue
112
+ # Regular-file reads stay bounded; O_NONBLOCK avoids waiting on
113
+ # a special-file substitution before the fstat refusal above.
114
+ raw = os.read(fd, 1024 * 1024 + 1)
115
+ finally:
116
+ os.close(fd)
117
+ if len(raw) > 1024 * 1024:
118
+ continue
119
+ metadata = json.loads(raw)
120
+ if not isinstance(metadata, dict) or metadata.get('applicationName') != 'devin-desktop':
121
+ continue
122
+ desktop.append(str(root))
123
+ # Historical Windsurf-layout candidate, not a required dependency.
124
+ agent = root / 'extensions/windsurf/devin/bin/devin'
125
+ try:
126
+ state.no_symlinks(agent)
127
+ if stat.S_ISREG(agent.lstat().st_mode):
128
+ bundled.append(str(agent))
129
+ except OSError:
130
+ pass
131
+ except (OSError, ValueError, TypeError, RuntimeError):
132
+ continue
133
+ return {
134
+ 'cli_on_path': bool(shutil.which('devin')),
135
+ 'desktop_bundle_present': bool(desktop),
136
+ 'bundled_agent_file_found': bool(bundled),
137
+ 'desktop_bundle_paths': desktop,
138
+ 'bundled_agent_paths': bundled,
139
+ 'desktop_search_scope': 'heuristic paths and product/layout match; relocated, remote and other installs may be missed',
140
+ 'desktop_presence_basis': 'filesystem metadata only; product.json is not authenticated',
141
+ 'desktop_loading_verified': False,
142
+ 'desktop_execution_verified': False,
143
+ }
144
+
145
+
146
+ PROBE_LINES = 2000
147
+
148
+
149
+ def _devin_log_hooks():
150
+ """The newest 'hooks discovery' line Devin wrote: proof Devin itself loaded
151
+ global hooks, not just that our command works when we run it."""
152
+ import re
153
+ logs = Path.home() / '.local/share/devin/cli/logs'
154
+ try:
155
+ candidates = sorted((entry for entry in os.scandir(logs) if entry.name.endswith('.log')),
156
+ key=lambda entry: entry.stat().st_mtime, reverse=True)[:40]
157
+ except OSError:
158
+ return {'seen': False, 'reason': 'no Devin CLI logs at ' + str(logs)}
159
+ for entry in candidates:
160
+ try:
161
+ with open(entry.path, 'rb') as handle:
162
+ handle.seek(max(0, entry.stat().st_size - 4 * 1024 * 1024))
163
+ tail = handle.read().decode('utf-8', 'replace')
164
+ except OSError:
165
+ continue
166
+ found = re.findall(r'hooks discovery: .*?loaded=(\d+) \(global=(\d+)', tail)
167
+ if found:
168
+ loaded, global_count = found[-1]
169
+ return {'seen': True, 'log': entry.path, 'global_hooks_loaded': int(global_count),
170
+ 'log_time': entry.stat().st_mtime}
171
+ return {'seen': False, 'reason': 'no Devin session has started since logging began'}
172
+
173
+
174
+ def _run_hook(command, payload, cwd):
175
+ """Run a configured hook command exactly as written, through the shell Devin uses."""
176
+ run = subprocess.run(['/bin/sh', '-c', command], input=json.dumps(payload).encode(), cwd=cwd,
177
+ capture_output=True, timeout=30)
178
+ try:
179
+ decision = json.loads(run.stdout) if run.stdout.strip() else None
180
+ except ValueError:
181
+ decision = 'unparseable'
182
+ return run.returncode, decision
183
+
184
+
185
+ def automatic_status(probe=False):
186
+ """Automatic mode: recorded entries, what the Devin config holds, and with
187
+ probe=True a real round trip through the configured hook commands."""
188
+ import devin_hooks as hooks
189
+ import shlex
190
+ import tempfile
191
+ import time
192
+ root = state.data_dir()
193
+ config_path = state.home() / 'config.json'
194
+ out = {'mode': 'manual', 'config': str(config_path)}
195
+ record_path = root / hooks.RECORD
196
+ try:
197
+ state.private_path(record_path)
198
+ record = json.loads(record_path.read_text()) if record_path.exists() else None
199
+ except (OSError, ValueError) as exc:
200
+ out.update(mode='broken', error='hook record unreadable: ' + str(exc))
201
+ return out
202
+ try:
203
+ config = json.loads(config_path.read_text()) if config_path.exists() else {}
204
+ except (OSError, ValueError) as exc:
205
+ config = None
206
+ config_error = str(exc)
207
+ if not isinstance(record, dict) or not isinstance(record.get('entries'), dict):
208
+ if isinstance(config, dict) and any(found == 'edited' for found in hooks.installed_state(
209
+ config, hooks.owned_entries('python3', str(root / 'plugin/devin_compress.py'))).values()):
210
+ out['warning'] = 'Token Optimizer hook entries are in the Devin config but not recorded; remove them by hand'
211
+ return out
212
+ if config is None:
213
+ out.update(mode='broken', error='Devin config unreadable: ' + config_error)
214
+ return out
215
+ entries = record['entries']
216
+ wiring = hooks.installed_state(config, entries)
217
+ out['wiring'] = wiring
218
+ out['attested'] = record.get('org_policy') == hooks.ATTESTATION
219
+ out['mode'] = 'automatic' if all(v == 'wired' for v in wiring.values()) and out['attested'] else 'broken'
220
+ if out['mode'] == 'broken':
221
+ out['error'] = 'hook entries missing or edited; rerun install.sh --devin --auto'
222
+ try:
223
+ hook_python = shlex.split(entries['PreToolUse']['hooks'][0]['command'])[0]
224
+ except (KeyError, IndexError, TypeError, ValueError):
225
+ hook_python = ''
226
+ if out['mode'] == 'automatic' and not os.access(hook_python, os.X_OK):
227
+ # The hook fails open (nothing breaks) but compression silently stops,
228
+ # typically after a Python upgrade removed the versioned interpreter.
229
+ out.update(mode='broken', error='hook Python is gone (' + hook_python +
230
+ '); rerun install.sh --devin --auto to repoint it')
231
+ out['devin_log'] = _devin_log_hooks()
232
+ if not probe or out['mode'] != 'automatic':
233
+ return out
234
+ pre = entries['PreToolUse']['hooks'][0]['command']
235
+ permission = entries['PermissionRequest']['hooks'][0]['command']
236
+ interpreter = shlex.split(pre)[0]
237
+ result = {'passed': False}
238
+ out['probe'] = result
239
+ with tempfile.TemporaryDirectory(prefix='doctor-probe-', dir=root) as work:
240
+ for index in range(20):
241
+ (Path(work) / ('module%02d.py' % index)).write_text(
242
+ ''.join('probe = repeated_value(%d)\n' % (i % 7) for i in range(PROBE_LINES // 20)))
243
+ rules = hooks.load_effective_rules(config_path, Path(work))
244
+ candidates = ['grep -rn probe .', 'ls -la']
245
+ command = next((c for c in candidates if hooks.eligible(c, rules, interpreter)), None)
246
+ if command is None:
247
+ result['reason'] = ('no Exec allow rule in your Devin config covers grep or ls, so nothing '
248
+ 'can be shown compressing here; commands your rules allow still compress')
249
+ return out
250
+ result['command'] = command
251
+ tool_use_id = 'doctor-probe-' + os.urandom(8).hex()
252
+ payload = {'hook_event_name': 'PreToolUse', 'tool_name': 'exec', 'tool_input': {'command': command},
253
+ 'tool_use_id': tool_use_id, 'session_id': 'doctor-probe', 'cwd': work}
254
+ code, decision = _run_hook(pre, payload, work)
255
+ wrapper = (decision or {}).get('hookSpecificOutput', {}).get('updatedInput', {}).get('command') \
256
+ if isinstance(decision, dict) else None
257
+ result['pre_tool_use_rewrote'] = bool(wrapper) and code == 0
258
+ if not wrapper:
259
+ result['reason'] = 'PreToolUse hook returned no rewrite (exit %d)' % code
260
+ return out
261
+ payload.update(hook_event_name='PermissionRequest', tool_input={'command': wrapper})
262
+ code, decision = _run_hook(permission, payload, work)
263
+ result['permission_approved_once'] = isinstance(decision, dict) and decision.get('decision') == 'approve'
264
+ _, again = _run_hook(permission, payload, work)
265
+ result['second_request_still_prompts'] = again is None
266
+ other = dict(payload, tool_use_id='doctor-probe-other')
267
+ _, foreign = _run_hook(permission, other, work)
268
+ result['other_tool_call_still_prompts'] = foreign is None
269
+ started = time.monotonic()
270
+ raw = subprocess.run(shlex.split(command), cwd=work, capture_output=True, timeout=60)
271
+ wrapped = subprocess.run(shlex.split(wrapper), cwd=work, capture_output=True, timeout=60)
272
+ result['raw_bytes'] = len(raw.stdout) + len(raw.stderr)
273
+ result['delivered_bytes'] = len(wrapped.stdout) + len(wrapped.stderr)
274
+ result['exit_code_preserved'] = raw.returncode == wrapped.returncode
275
+ result['seconds'] = round(time.monotonic() - started, 2)
276
+ result['passed'] = all(result[k] for k in ('pre_tool_use_rewrote', 'permission_approved_once',
277
+ 'second_request_still_prompts', 'other_tool_call_still_prompts',
278
+ 'exit_code_preserved'))
279
+ return out
280
+
281
+
282
+ def diagnose(probe=False):
283
+ root = state.data_dir()
284
+ skill = state.home() / 'skills/token-optimizer-output/SKILL.md'
285
+ recovery_pending = (root/'pending-install.json').exists() or (root/'pending-install.json').is_symlink()
286
+ from devin_verify import verify_install
287
+ error=None
288
+ # Numeric estimates are optional: the filter works without them, so an
289
+ # unsafe metrics leaf is its own field and warning, not a readiness failure.
290
+ numeric_errors = []
291
+ for leaf in state.NUMERIC_STATE_LEAVES:
292
+ try:
293
+ state.private_path(root / leaf)
294
+ except OSError as exc:
295
+ numeric_errors.append(str(exc))
296
+ try:
297
+ ready=verify_install()
298
+ from devin_verify import PAYLOAD
299
+ # Import the whole manifested payload through the digest-checked
300
+ # loader, not just the entrypoint bootstrap: a lazily imported module
301
+ # that cannot import must still fail readiness.
302
+ check=subprocess.run(
303
+ [sys.executable,'-I','-c',
304
+ 'import sys\n'
305
+ 'from pathlib import Path\n'
306
+ 'root = Path(sys.argv[1]); namespace = {}\n'
307
+ "exec(compile((root / 'devin_source.py').read_bytes(), 'devin_source.py', 'exec'), namespace)\n"
308
+ "namespace['activate'](root)\n"
309
+ 'for name in sys.argv[2:]:\n'
310
+ ' __import__(name)\n',
311
+ str(root/'plugin'), *(Path(name).stem for name in PAYLOAD)],
312
+ capture_output=True,timeout=15)
313
+ if check.returncode:raise OSError('installed dependencies cannot import')
314
+ except (OSError,ValueError,SyntaxError,TypeError,subprocess.SubprocessError) as exc:
315
+ ready=False;error=str(exc)
316
+ warnings = []
317
+ if recovery_pending:
318
+ ready = False
319
+ error = (error + '; ' if error else '') + 'Recovery is pending: ' + str(root / 'pending-install.json')
320
+ try:
321
+ state.private_path(root / 'pending-install.json')
322
+ except OSError as exc:
323
+ error += ': ' + str(exc)
324
+ if (root / 'pending-install.json').is_dir() and not (root / 'pending-install.json').is_symlink():
325
+ warnings.append(error + '; directory-shaped pending state cannot be recovered or purged. Move it aside after inspecting it.')
326
+ else:
327
+ warnings.append(error + '; ordinary recovery refuses this path. Move it aside or use uninstall --purge to discard adapter state and stored captures.')
328
+ else:
329
+ warnings.append('Recovery is pending; real install/uninstall validates and attempts recovery, but invalid transaction contents can still refuse; uninstall --purge then discards adapter state and also removes stored captures. Dry-run refuses pending recovery.')
330
+ for name in ('.claude/settings.json', '.claude.json'):
331
+ if (Path.home() / name).is_file():
332
+ warnings.append('Claude config exists and Devin imports may load its hooks: ' + name)
333
+ for name in ('.claude/settings.json', '.claude/settings.local.json', '.devin/hooks.v1.json'):
334
+ if (Path.cwd() / name).is_file():
335
+ warnings.append('Project hook/config exists; this adapter does not edit it: ' + name)
336
+ claude=Path(os.environ.get('CLAUDE_CONFIG_DIR',str(Path.home()/'.claude')))
337
+ if (claude/'skills/token-optimizer').exists() or (claude/'skills/token-optimizer').is_symlink():
338
+ warnings.append('Imported Claude token-optimizer skill exists; coexistence is outside this adapter.')
339
+ for base in (Path.cwd()/'.devin',Path.cwd()/'.claude'):
340
+ if (base/'skills/token-optimizer-output/SKILL.md').exists():
341
+ warnings.append('Project token-optimizer-output skill can shadow installed global skill: '+str(base))
342
+ try:
343
+ state.private_path(root / 'install.lock')
344
+ except OSError as exc:
345
+ warnings.append('Install, update and uninstall will refuse until this is fixed: ' + str(exc))
346
+ for message in numeric_errors:
347
+ warnings.append('Numeric estimates will not be recorded: ' + message)
348
+ loader = state.loader_path_info()
349
+ if loader['status'] != 'documented_default':
350
+ warnings.append('Nondefault skill directory: CLI/Desktop discovery is unverified; check the loaded skill source.')
351
+ surfaces = local_agent_surfaces()
352
+ result = {'recovery_pending': recovery_pending, 'local_agent_surfaces': surfaces, 'loader_path': loader, 'surface': 'explicit_capture_filter', 'status': 'recovery-pending' if recovery_pending else 'contract-only beta',
353
+ 'installed': ready, 'readiness_error': error, 'numeric_state_ok': not numeric_errors, 'devin_cli_on_path': surfaces['cli_on_path'],
354
+ 'live_devin_session_tested': False, 'warnings': warnings,
355
+ 'local_probe_passed': None}
356
+ if probe and ready:
357
+ from devin_compress import filter_capture, seal_capture
358
+ tmp = state.prepare_capture()
359
+ out, err = tmp / 'stdout', tmp / 'stderr'
360
+ raw = b'repeated output line\n' * 1000
361
+ try:
362
+ out.write_bytes(raw); err.write_bytes(b'')
363
+ seal_capture(tmp, 0)
364
+ value = filter_capture(out, err, 0, 'generic', 'doctor-local-probe', record_metrics=False)
365
+ result['local_probe_passed'] = value.code == 0 and len(value.stdout) < len(raw) and out.read_bytes() == raw
366
+ finally:
367
+ for leaf in ('stdout','stderr','.prepared','complete.json'):
368
+ (tmp/leaf).unlink(missing_ok=True)
369
+ tmp.rmdir()
370
+ result['probe_scope'] = 'local filter only; not Devin adherence or provider usage'
371
+ if ready:
372
+ try:
373
+ result['automatic'] = automatic_status(probe)
374
+ except (OSError, ValueError, ImportError, subprocess.SubprocessError) as exc:
375
+ result['automatic'] = {'mode': 'broken', 'error': str(exc)}
376
+ automatic = result['automatic']
377
+ if automatic.get('mode') == 'broken':
378
+ warnings.append('Automatic mode is broken: ' + str(automatic.get('error')))
379
+ elif automatic.get('mode') == 'automatic':
380
+ seen = automatic.get('devin_log', {})
381
+ if seen.get('seen') and seen.get('global_hooks_loaded', 0) < 2:
382
+ warnings.append('Devin\'s newest session log shows ' + str(seen.get('global_hooks_loaded')) +
383
+ ' global hooks loaded; restart Devin so it loads the Token Optimizer hooks')
384
+ result['status'] = 'automatic' if automatic.get('mode') == 'automatic' else result['status']
385
+ result['limits'] = 'caller asserts foreground completion and exit code; not a sandbox against malicious same-UID code'
386
+ return result
387
+
388
+
389
+ def main(argv=None):
390
+ p=argparse.ArgumentParser(description=__doc__); p.add_argument('--probe',action='store_true')
391
+ args=p.parse_args(argv)
392
+ try:
393
+ result=diagnose(args.probe); print(json.dumps(result,indent=2))
394
+ automatic_probe = result.get('automatic', {}).get('probe')
395
+ failed = result['local_probe_passed'] is False or (automatic_probe is not None and not automatic_probe.get('passed')
396
+ and 'command' in automatic_probe)
397
+ return 0 if result['installed'] and not failed and result.get('automatic', {}).get('mode') != 'broken' else 1
398
+ except (OSError, ValueError, ImportError, SyntaxError, RecursionError, RuntimeError) as exc:
399
+ print('Token Optimizer: readiness refused: '+str(exc)+'. Originals remain unchanged.',file=sys.stderr)
400
+ return 2
401
+
402
+ if __name__=='__main__':
403
+ raise SystemExit(main())