@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,1086 @@
1
+ #!/usr/bin/env python3
2
+ """Install the Devin output skill; with --auto, also own two hook entries in the Devin user config."""
3
+ from __future__ import annotations
4
+ import argparse
5
+ import ast
6
+ import base64
7
+ from contextlib import contextmanager
8
+ import hashlib
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import re
13
+ import shlex
14
+ import stat
15
+ import shutil
16
+ import sys
17
+ import tempfile
18
+
19
+ SCRIPTS = Path(__file__).resolve().parent
20
+ # Isolated startup (-I) removes the script directory; the installer always
21
+ # runs from a checkout, so restore only this checked scripts root.
22
+ if str(SCRIPTS) not in sys.path:
23
+ sys.path.insert(0, str(SCRIPTS))
24
+
25
+ import devin_state as state
26
+ from devin_verify import PAYLOAD
27
+ from py_trust import py_path_is_trusted
28
+ import devin_hooks as hooks
29
+ SKILL_NAME = 'token-optimizer-output'
30
+ MARKER = 'devin-output-filter-v1'
31
+
32
+
33
+ def _render_payload(name: str) -> bytes:
34
+ """Commit installed bytes, with a direct-execution gate on internal modules."""
35
+ source = (SCRIPTS / name).read_bytes()
36
+ if name in ('devin_compress.py', 'devin_doctor.py'):
37
+ return source
38
+ tree = ast.parse(source)
39
+ prefix_end = 0
40
+ prefix_count = 0
41
+ for index, node in enumerate(tree.body):
42
+ docstring = (index == 0 and isinstance(node, ast.Expr)
43
+ and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str))
44
+ future = isinstance(node, ast.ImportFrom) and node.module == '__future__'
45
+ if not (docstring or future):
46
+ break
47
+ prefix_end = node.end_lineno
48
+ prefix_count += 1
49
+ if any(node.lineno <= prefix_end for node in tree.body[prefix_count:]):
50
+ raise OSError('payload prefix shares a line with executable code')
51
+ lines = source.splitlines(keepends=True)
52
+ guard = (b"\n# Installed Devin payload: internal modules have no CLI contract.\n"
53
+ b"if __name__ == '__main__':\n"
54
+ b" import sys\n"
55
+ b" print('Token Optimizer: internal module requires an activated entrypoint. Originals remain unchanged.', file=sys.stderr)\n"
56
+ b" raise SystemExit(2)\n\n")
57
+ result = b''.join(lines[:prefix_end]) + guard + b''.join(lines[prefix_end:])
58
+ compile(result, name, 'exec')
59
+ return result
60
+
61
+
62
+ def skill_dir() -> Path:
63
+ return state.home() / 'skills' / SKILL_NAME
64
+
65
+
66
+ def manifest_path() -> Path:
67
+ return state.data_dir() / 'install.json'
68
+
69
+
70
+ def _private_bytes(path: Path) -> bytes:
71
+ state.no_symlinks(path)
72
+ fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK)
73
+ try:
74
+ # fstat before fdopen: a directory wraps into a stream that reports the
75
+ # bare descriptor number in its error, not the path being refused.
76
+ before=os.fstat(fd)
77
+ if (not stat.S_ISREG(before.st_mode) or before.st_uid!=os.geteuid()
78
+ or before.st_mode&0o077 or before.st_nlink!=1):
79
+ raise OSError('private single-link ownership file required: ' + str(path))
80
+ with os.fdopen(fd,'rb') as handle:
81
+ fd=-1
82
+ content=handle.read()
83
+ after=os.fstat(handle.fileno())
84
+ finally:
85
+ if fd>=0:
86
+ os.close(fd)
87
+ if (before.st_ino,before.st_size,before.st_mtime_ns)!=(after.st_ino,after.st_size,after.st_mtime_ns):
88
+ raise OSError('ownership file changed while reading')
89
+ return content
90
+
91
+
92
+ def _hash(path: Path) -> str:
93
+ try:return hashlib.sha256(_private_bytes(path)).hexdigest()
94
+ except FileNotFoundError:
95
+ raise OSError('owned file is missing: ' + str(path) + '; uninstall then install to repair while preserving original captures')
96
+
97
+
98
+ def _clear_pending(path: Path) -> None:
99
+ path.unlink(missing_ok=True)
100
+ fd=os.open(path.parent,os.O_RDONLY|os.O_DIRECTORY)
101
+ try:os.fsync(fd)
102
+ finally:os.close(fd)
103
+
104
+
105
+ class _ForeignLayout(OSError):
106
+ """Recorded keys do not map to this version's expected install paths."""
107
+
108
+
109
+ class _EditedInstall(OSError):
110
+ """A recorded file's digest no longer matches the manifest."""
111
+
112
+
113
+ def _resolved_keys(files) -> list:
114
+ """Recorded manifest keys may carry a non-canonical home spelling (for
115
+ example '..' segments) written before the override was resolved; compare
116
+ them by where they resolve."""
117
+ return sorted(str(Path(name).resolve()) for name in files)
118
+
119
+
120
+ def _resolved_files(files) -> dict:
121
+ return {str(Path(name).resolve()): digest for name, digest in files.items()}
122
+
123
+
124
+ def _ownership(*, allow_missing=False) -> dict | None:
125
+ p = state.private_path(manifest_path())
126
+ if not p.exists():
127
+ return None
128
+ if p.exists() and p.stat().st_nlink != 1:raise OSError('ownership record hardlink refused')
129
+ try:
130
+ record = json.loads(_private_bytes(p))
131
+ except (ValueError, RecursionError):
132
+ raise OSError('invalid ownership record; run uninstall --purge (which also removes stored captures) to discard adapter state')
133
+ if not isinstance(record, dict) or record.get('owner') != MARKER or not isinstance(record.get('files'), dict):
134
+ raise OSError('invalid ownership record; run uninstall --purge (which also removes stored captures) to discard adapter state')
135
+ expected = {str(state.data_dir() / 'plugin' / name) for name in PAYLOAD} | {str(skill_dir() / 'SKILL.md')}
136
+ # Earlier releases shipped fewer payload files: 5.13.43 had no hook module,
137
+ # and releases before it also lacked the two plugin-env modules.
138
+ previous = expected - {str(state.data_dir() / 'plugin' / 'devin_hooks.py')}
139
+ legacy = previous - {str(state.data_dir() / 'plugin' / name) for name in ('plugin_env.py', 'refetch_fingerprint.py')}
140
+ try:
141
+ record_keys = _resolved_keys(record['files'])
142
+ except (OSError, ValueError, TypeError, RuntimeError):
143
+ raise OSError('recorded paths cannot be resolved; run uninstall --purge (which also removes stored captures) to discard adapter state')
144
+ if record_keys not in (sorted(expected), sorted(previous), sorted(legacy)):
145
+ # A recorded path routed through a symlink resolves elsewhere; name the
146
+ # real cause before falling through to the version/spelling advice.
147
+ for name in record['files']:
148
+ state.no_symlinks(Path(name))
149
+ raise _ForeignLayout('ownership paths do not match this install; the manifest was recorded by a different adapter version or home spelling -- run uninstall --purge (which also removes stored captures) to discard adapter state')
150
+ for name, digest in record['files'].items():
151
+ raw = Path(name)
152
+ resolved = raw.resolve()
153
+ # A key like plugin/ghost/../x.py resolves onto an owned path yet
154
+ # cannot be traversed; refusing here beats a "successful" removal that
155
+ # silently leaves the file behind. An ordinary missing file or moved
156
+ # folder resolves to nothing and stays tolerable under allow_missing.
157
+ if resolved.exists() and not raw.exists():
158
+ raise OSError('recorded path cannot be reached inside the install directories: ' + name +
159
+ '; move ' + str(state.data_dir()) + ' and ' + str(skill_dir()) + ' aside to repair')
160
+ if allow_missing and not raw.exists():
161
+ state.no_symlinks(raw)
162
+ continue
163
+ if _hash(raw) != digest:
164
+ raise _EditedInstall('installed file changed; refusing overwrite/removal: ' + name +
165
+ '; to remove the adapter anyway move ' + str(state.data_dir()) +
166
+ ' and ' + str(skill_dir()) + ' aside first')
167
+ return record
168
+
169
+
170
+ def _ownership_for_removal(*, purge: bool):
171
+ """Purge tolerates a manifest this version cannot map or read. A digest
172
+ mismatch still refuses, exactly like a plain uninstall, unless every
173
+ mismatching file holds bytes the adapter itself wrote (an interrupted
174
+ refresh): those are not user edits, and the purge sweep removes them."""
175
+ try:
176
+ return _ownership(allow_missing=True)
177
+ except _EditedInstall:
178
+ if not purge:
179
+ raise
180
+ edited = _user_edited_file()
181
+ if edited is None:
182
+ return None
183
+ if edited:
184
+ # Name the file the user changed, not an interrupted-refresh leaf.
185
+ raise _EditedInstall('installed file changed; refusing overwrite/removal: ' + edited +
186
+ '; to remove the adapter anyway move ' + str(state.data_dir()) +
187
+ ' and ' + str(skill_dir()) + ' aside first') from None
188
+ raise
189
+ except (OSError, ValueError, RecursionError):
190
+ if not purge:
191
+ raise
192
+ return None
193
+
194
+
195
+
196
+ def _purge_record_bytes(path):
197
+ """Purge may recover historical digests from loose-mode or linked records."""
198
+ state.no_symlinks(path)
199
+ fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
200
+ try:
201
+ info = os.fstat(fd)
202
+ if not stat.S_ISREG(info.st_mode) or info.st_size > 8 * 1024 * 1024:
203
+ raise OSError('bounded regular purge record required: ' + str(path))
204
+ with os.fdopen(fd, 'rb') as handle:
205
+ fd = -1
206
+ content = handle.read(8 * 1024 * 1024 + 1)
207
+ if len(content) > 8 * 1024 * 1024:
208
+ raise OSError('purge record too large: ' + str(path))
209
+ return content
210
+ finally:
211
+ if fd >= 0:
212
+ os.close(fd)
213
+
214
+
215
+ def _user_edited_file():
216
+ """None when every installed file that differs from the manifest carries a
217
+ digest a transaction record or this checkout produced (an interrupted
218
+ refresh, not an edit). Otherwise the first file with an unknown digest, or
219
+ '' when that cannot be determined; either keeps the refusal."""
220
+ try:
221
+ record = json.loads(_purge_record_bytes(manifest_path()))
222
+ files = record['files'] if isinstance(record, dict) else None
223
+ if not isinstance(files, dict) or not files:
224
+ return ''
225
+ recorded, known = _purge_recorded(expected_only=True), _known_payload_digests()
226
+ for name, digest in files.items():
227
+ path = Path(name)
228
+ state.no_symlinks(path)
229
+ if not path.exists():
230
+ continue
231
+ actual = hashlib.sha256(_private_bytes(path)).hexdigest()
232
+ resolved = str(path.resolve())
233
+ if actual != digest and actual not in recorded.get(resolved, ()) and actual != known.get(resolved):
234
+ return name
235
+ return None
236
+ except (OSError, ValueError, TypeError, RuntimeError, RecursionError):
237
+ return ''
238
+
239
+
240
+ def _purge_recorded(*, expected_only=False) -> dict:
241
+ """Best-effort recorded digests for the purge sweep, as path -> set of
242
+ digests: a well-formed manifest or pending transaction record contributes
243
+ every digest it committed (the intended new bytes and the previous ones);
244
+ anything unreadable yields nothing."""
245
+ out = {}
246
+
247
+ # Lifting the edited-file refusal is limited to this version's own payload
248
+ # paths; the sweep also honours another version's recorded file names.
249
+ expected = ({str((state.data_dir() / 'plugin' / name).resolve()) for name in PAYLOAD}
250
+ | {str((skill_dir() / 'SKILL.md').resolve())})
251
+
252
+ def _put(name, digest):
253
+ resolved = str(Path(name).resolve())
254
+ if not expected_only or resolved in expected:
255
+ out.setdefault(resolved, set()).add(digest)
256
+
257
+ def _add(files):
258
+ if not isinstance(files, dict):
259
+ return
260
+ for name, digest in files.items():
261
+ if (not isinstance(name, str) or not isinstance(digest, str) or len(digest) != 64
262
+ or any(c not in '0123456789abcdef' for c in digest)):
263
+ continue
264
+ try:
265
+ _put(name, digest)
266
+ except (OSError, ValueError, RuntimeError):
267
+ continue
268
+
269
+ for leaf in ('install.json', 'pending-install.json'):
270
+ try:
271
+ record = json.loads(_purge_record_bytes(state.data_dir() / leaf))
272
+ except (OSError, ValueError, RecursionError):
273
+ continue
274
+ if not isinstance(record, dict) or record.get('owner') != MARKER:
275
+ continue
276
+ _add(record.get('files'))
277
+ previous = record.get('previous')
278
+ if isinstance(previous, dict):
279
+ for name, content in previous.items():
280
+ if not isinstance(name, str) or not isinstance(content, str):
281
+ continue
282
+ try:
283
+ _put(name, hashlib.sha256(base64.b64decode(content, validate=True)).hexdigest())
284
+ except (OSError, ValueError, RuntimeError):
285
+ continue
286
+ old_manifest = record.get('previous_manifest')
287
+ if isinstance(old_manifest, str):
288
+ try:
289
+ old = json.loads(base64.b64decode(old_manifest, validate=True))
290
+ except (ValueError, RecursionError):
291
+ old = None
292
+ if isinstance(old, dict):
293
+ _add(old.get('files'))
294
+ return out
295
+
296
+
297
+ def _sweep_candidates(recorded, known) -> list:
298
+ """Files the purge sweep removes: regular files directly inside plugin/
299
+ and the skill folder whose bytes a record or this checkout produced.
300
+ Unreadable or foreign content yields nothing and is preserved."""
301
+ found = []
302
+ for folder in (state.data_dir() / 'plugin', skill_dir()):
303
+ try:
304
+ if folder.is_symlink() or not folder.is_dir():
305
+ continue
306
+ state.no_symlinks(folder)
307
+ items = list(folder.iterdir())
308
+ except OSError:
309
+ continue
310
+ for item in items:
311
+ try:
312
+ if not item.is_file() or item.is_symlink():
313
+ continue
314
+ digest = hashlib.sha256(item.read_bytes()).hexdigest()
315
+ resolved = str(item.resolve())
316
+ except OSError:
317
+ continue
318
+ if digest in recorded.get(resolved, ()) or known.get(resolved) == digest:
319
+ found.append(item)
320
+ return found
321
+
322
+
323
+ def _preflight_sweep_access(recorded, known) -> None:
324
+ """Refuse before any state is purged when unchanged adapter files sit in
325
+ a folder that cannot be modified: purging the records first would strand
326
+ those files with nothing left to identify them."""
327
+ for folder in sorted({item.parent for item in _sweep_candidates(recorded, known)}):
328
+ if not os.access(folder, os.W_OK | os.X_OK, effective_ids=True):
329
+ raise OSError('removal directory is not writable/searchable: ' + str(folder) +
330
+ '; it holds unchanged adapter files. Make it writable (chmod u+wx) and retry removal')
331
+
332
+
333
+ def _known_payload_digests() -> dict:
334
+ """Digests of this tree's rendered payload: unchanged installed bytes are
335
+ safe for purge to remove even when the manifest cannot be read."""
336
+ try:
337
+ known = {str((state.data_dir() / 'plugin' / name).resolve()):
338
+ hashlib.sha256(_render_payload(name)).hexdigest() for name in PAYLOAD}
339
+ source = SCRIPTS.parents[2] / 'devin' / 'SKILL.md'
340
+ if source.is_file():
341
+ text = source.read_text().replace('@PYTHON@', shlex.quote(os.path.realpath(sys.executable)))
342
+ text = text.replace('@FILTER@', shlex.quote(str(state.data_dir() / 'plugin' / 'devin_compress.py')))
343
+ known[str((skill_dir() / 'SKILL.md').resolve())] = hashlib.sha256(text.encode()).hexdigest()
344
+ return known
345
+ except OSError:
346
+ return {}
347
+
348
+
349
+ @contextmanager
350
+ def _lock():
351
+ import fcntl
352
+ state.private_path(state.data_dir(), directory=True, create=True)
353
+ lock = state.private_path(state.data_dir() / 'install.lock', create=True)
354
+ with lock.open('r+') as handle:
355
+ fcntl.flock(handle, fcntl.LOCK_EX)
356
+ yield
357
+
358
+
359
+ def _atomic(path: Path, content: bytes) -> None:
360
+ state.no_symlinks(path)
361
+ # Unique private temp avoids a stale O_EXCL name wedging future attempts.
362
+ # A killed pre-publication temp is retained, never claimed/deleted as owned.
363
+ fd, temporary_name = tempfile.mkstemp(prefix='.install-',dir=state.data_dir())
364
+ temporary=Path(temporary_name)
365
+ try:
366
+ with os.fdopen(fd, 'wb') as handle:
367
+ handle.write(content); handle.flush(); os.fsync(handle.fileno())
368
+ os.replace(temporary, path)
369
+ directory=os.open(path.parent,os.O_RDONLY|os.O_DIRECTORY)
370
+ try:os.fsync(directory)
371
+ finally:os.close(directory)
372
+ finally:
373
+ temporary.unlink(missing_ok=True)
374
+
375
+
376
+ # ── Automatic mode: hook entries in the Devin user config ───────────────────
377
+ # Devin reads global hooks from the "hooks" key of its user config. The adapter
378
+ # owns exactly the entries it recorded; every other key and hook is the
379
+ # user's and survives install, refresh, uninstall and purge byte for byte.
380
+
381
+ HOOK_STATE_LEAVES = (hooks.RECORD, hooks.BINDINGS, hooks.BINDINGS + '.lock', 'auto-captures.json',
382
+ 'auto-captures.json.lock', 'devin-config-backup.json')
383
+ MAX_CONFIG = 4 * 1024 * 1024
384
+ ATTESTATION_NOTICE = ('Automatic mode records your statement that no Devin team or enterprise permission policy '
385
+ 'applies here: those policies are never stored on this machine, so they cannot be checked.')
386
+
387
+
388
+ def devin_config() -> Path:
389
+ return state.home() / 'config.json'
390
+
391
+
392
+ def _hook_entries() -> dict:
393
+ return hooks.owned_entries(os.path.realpath(sys.executable), str(state.data_dir() / 'plugin' / 'devin_compress.py'))
394
+
395
+
396
+ def _hook_record(*, tolerant=False):
397
+ """The recorded hook entries, or None. tolerant: unreadable = None (purge)."""
398
+ path = state.data_dir() / hooks.RECORD
399
+ try:
400
+ state.private_path(path)
401
+ if not path.exists():
402
+ return None
403
+ record = json.loads(_private_bytes(path))
404
+ if (not isinstance(record, dict) or record.get('owner') != MARKER
405
+ or not isinstance(record.get('entries'), dict) or not isinstance(record.get('stale', []), list)):
406
+ raise OSError('invalid hook record: ' + str(path))
407
+ return record
408
+ except (OSError, ValueError, RecursionError) as exc:
409
+ if tolerant:
410
+ return None
411
+ raise OSError('invalid hook record: ' + str(path) + ' (' + str(exc) + ')') from None
412
+
413
+
414
+ def _read_devin_config(path: Path):
415
+ """(config, exact bytes or None when absent, mode). Refuses what it cannot edit safely."""
416
+ state.no_symlinks(path)
417
+ try:
418
+ info = path.lstat()
419
+ except FileNotFoundError:
420
+ return {}, None, 0o600
421
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or info.st_nlink != 1:
422
+ raise OSError('Devin config must be a regular, single-link file you own: ' + str(path))
423
+ if info.st_size > MAX_CONFIG:
424
+ raise OSError('Devin config is too large to edit safely: ' + str(path))
425
+ raw = path.read_bytes()
426
+ try:
427
+ config = json.loads(raw)
428
+ except (ValueError, RecursionError):
429
+ raise OSError('Devin config is not plain JSON (comments or trailing commas?): ' + str(path)) from None
430
+ if not isinstance(config, dict):
431
+ raise OSError('Devin config must be a JSON object: ' + str(path))
432
+ return config, raw, stat.S_IMODE(info.st_mode)
433
+
434
+
435
+ def _write_devin_config(path: Path, config: dict, raw, mode: int) -> None:
436
+ """Atomic, mode-preserving replace; refuses when the file changed meanwhile."""
437
+ if raw is not None:
438
+ # The exact bytes before this edit, private, for manual recovery.
439
+ backup = state.data_dir() / 'devin-config-backup.json'
440
+ state.private_path(backup)
441
+ _atomic(backup, raw)
442
+ indent = 2
443
+ if raw:
444
+ match = re.search(rb'\n( +)"', raw)
445
+ if match:
446
+ indent = len(match.group(1))
447
+ content = (json.dumps(config, indent=indent, ensure_ascii=False) + '\n').encode('utf-8')
448
+ fd, temporary_name = tempfile.mkstemp(prefix='.config-token-optimizer-', dir=path.parent)
449
+ temporary = Path(temporary_name)
450
+ try:
451
+ with os.fdopen(fd, 'wb') as handle:
452
+ handle.write(content); handle.flush(); os.fsync(handle.fileno())
453
+ os.chmod(temporary, mode)
454
+ try:
455
+ current = path.read_bytes()
456
+ except FileNotFoundError:
457
+ current = None
458
+ if current != raw:
459
+ raise OSError('Devin config changed while it was being edited; nothing was written. Retry: ' + str(path))
460
+ os.replace(temporary, path)
461
+ directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
462
+ try: os.fsync(directory)
463
+ finally: os.close(directory)
464
+ finally:
465
+ temporary.unlink(missing_ok=True)
466
+
467
+
468
+ def _recorded_pairs(record) -> list:
469
+ """Every (event, entry) a record may have written: current plus stale."""
470
+ pairs = [(event, entry) for event, entry in record['entries'].items()]
471
+ for item in record.get('stale', []):
472
+ if isinstance(item, list) and len(item) == 2 and isinstance(item[0], str):
473
+ pairs.append((item[0], item[1]))
474
+ return pairs
475
+
476
+
477
+ def _wire_hooks() -> None:
478
+ """Add (or refresh) the two owned entries. The record is written first and
479
+ names the previous entries as stale, so an interrupted run never leaves an
480
+ entry that a later uninstall cannot identify."""
481
+ path = devin_config()
482
+ previous = _hook_record()
483
+ config, raw, mode = _read_devin_config(path)
484
+ entries = _hook_entries()
485
+ stale = [[event, entry] for event, entry in (_recorded_pairs(previous) if previous else [])
486
+ if entries.get(event) != entry]
487
+ merged = config
488
+ for event, entry in stale:
489
+ merged, _ = hooks.remove_hooks(merged, {event: entry})
490
+ merged = hooks.merge_hooks(merged, entries)
491
+ record = {'owner': MARKER, 'config': str(path), 'entries': entries, 'stale': stale,
492
+ 'org_policy': hooks.ATTESTATION}
493
+ target = state.private_path(state.data_dir() / hooks.RECORD)
494
+ _atomic(target, json.dumps(record, sort_keys=True).encode())
495
+ if merged != config or raw is None:
496
+ _write_devin_config(path, merged, raw, mode)
497
+ if stale:
498
+ record['stale'] = []
499
+ _atomic(target, json.dumps(record, sort_keys=True).encode())
500
+
501
+
502
+ def _unwire_hooks(*, tolerant=False) -> bool:
503
+ """Remove only the recorded, byte-equal entries, then the record. True when
504
+ a record existed. Edited entries stay, and are named."""
505
+ record = _hook_record(tolerant=tolerant)
506
+ if record is None:
507
+ return False
508
+ path = devin_config()
509
+ config, raw, mode = _read_devin_config(path)
510
+ if raw is not None:
511
+ result = config
512
+ for event, entry in _recorded_pairs(record):
513
+ result, _ = hooks.remove_hooks(result, {event: entry})
514
+ preserved = [event for event, found in hooks.installed_state(result, record['entries']).items()
515
+ if found == 'edited']
516
+ if result != config:
517
+ _write_devin_config(path, result, raw, mode)
518
+ if preserved:
519
+ print('Kept edited Token Optimizer hook entries in ' + str(path) + ' (' + ', '.join(preserved) +
520
+ '); they no longer match what was installed. Remove them by hand if unwanted.')
521
+ (state.data_dir() / hooks.RECORD).unlink(missing_ok=True)
522
+ # The backup is a full copy of the user's config: never outlive the wiring.
523
+ (state.data_dir() / 'devin-config-backup.json').unlink(missing_ok=True)
524
+ return True
525
+
526
+
527
+ def _recover_pending() -> None:
528
+ """Resume only a fingerprinted fresh-install transaction, never foreign files."""
529
+ pending=state.private_path(state.data_dir()/'pending-install.json')
530
+ if not pending.exists():return
531
+ if pending.stat().st_nlink!=1:raise OSError('pending ownership hardlink refused: ' + str(pending))
532
+ try:
533
+ value=json.loads(_private_bytes(pending))
534
+ except (ValueError,RecursionError):
535
+ value=None
536
+ expected={str(state.data_dir()/'plugin'/name) for name in PAYLOAD}|{str(skill_dir()/'SKILL.md')}
537
+ previous=expected - {str(state.data_dir()/'plugin'/'devin_hooks.py')}
538
+ legacy=previous - {str(state.data_dir()/'plugin'/name) for name in ('plugin_env.py','refetch_fingerprint.py')}
539
+ files=value.get('files') if isinstance(value,dict) else None
540
+ try:
541
+ keys=_resolved_keys(files) if isinstance(files,dict) else None
542
+ except (OSError,ValueError,TypeError,RuntimeError):
543
+ keys=None
544
+ if (not isinstance(value,dict) or value.get('owner')!=MARKER
545
+ or keys not in (sorted(expected),sorted(previous),sorted(legacy))):
546
+ raise OSError('invalid pending install record: ' + str(pending) + '; preserved; run uninstall --purge (which also removes stored captures) to discard adapter state')
547
+ # Reconcile published new bytes first: stale pending must not undo a completed update.
548
+ if manifest_path().exists():
549
+ try:
550
+ published=_ownership()
551
+ except OSError:
552
+ published=None
553
+ if published and _resolved_files(published['files'])==_resolved_files(value['files']):
554
+ _clear_pending(pending);return
555
+ source=SCRIPTS.parents[2]/'devin/SKILL.md'
556
+ if not source.is_file():raise OSError('pending repair requires original checkout')
557
+ rendered=source.read_text().replace('@PYTHON@',shlex.quote(os.path.realpath(sys.executable))).replace('@FILTER@',shlex.quote(str(state.data_dir()/'plugin/devin_compress.py')))
558
+ current={str(state.data_dir()/'plugin'/name):hashlib.sha256(_render_payload(name)).hexdigest() for name in PAYLOAD}
559
+ current[str(skill_dir()/'SKILL.md')]=hashlib.sha256(rendered.encode()).hexdigest()
560
+ # A previous-version record cannot match this tree's rendered digests; it
561
+ # reconciles against the digests it committed, per file, in the loop below.
562
+ if keys==sorted(expected) and _resolved_files(value['files'])!=current:
563
+ raise OSError('pending version/content ambiguous: ' + str(pending) + '; preserved; run uninstall --purge (which also removes stored captures) to discard adapter state, or follow the documented manual repair')
564
+ old=value.get('previous')
565
+ if old is not None:
566
+ if not isinstance(old,dict) or _resolved_keys(old) not in (sorted(expected),sorted(legacy)):raise OSError('invalid refresh recovery record')
567
+ if any(not isinstance(content,str) for content in old.values()) or not isinstance(value.get('previous_manifest'),str):
568
+ raise OSError('invalid refresh recovery encoding')
569
+ previous={name:base64.b64decode(content,validate=True) for name,content in old.items()}
570
+ previous_manifest=base64.b64decode(value['previous_manifest'],validate=True)
571
+ previous_record=json.loads(previous_manifest)
572
+ if (not isinstance(previous_record,dict) or previous_record.get('owner')!=MARKER
573
+ or not isinstance(previous_record.get('files'),dict)
574
+ or set(previous_record['files'])!=set(previous)
575
+ or any(not isinstance(digest,str) or len(digest)!=64
576
+ or any(ch not in '0123456789abcdef' for ch in digest)
577
+ for digest in previous_record['files'].values())):
578
+ raise OSError('invalid previous ownership commitments; preserved')
579
+ if _private_bytes(manifest_path())!=previous_manifest:
580
+ raise OSError('previous ownership differs from preserved manifest; preserved')
581
+ if any(hashlib.sha256(content).hexdigest()!=previous_record['files'][name]
582
+ for name,content in previous.items()):
583
+ raise OSError('previous rollback source differs from ownership commitments; preserved')
584
+ for name,content in previous.items():
585
+ path=Path(name);state.no_symlinks(path)
586
+ if path.exists() and _hash(path) not in (hashlib.sha256(content).hexdigest(),value['files'][name]):
587
+ raise OSError('edited interrupted refresh; preserved')
588
+ temporary=path.with_name(path.name+'.install-tmp')
589
+ if temporary.exists():
590
+ raise OSError('pre-existing refresh temporary ownership ambiguous; preserved; use manual repair')
591
+ added=set(value['files']) - set(previous)
592
+ for name in added:
593
+ path=Path(name);state.no_symlinks(path)
594
+ if path.exists() and _hash(path)!=value['files'][name]:
595
+ raise OSError('edited newly added refresh leaf; preserved')
596
+ for name in added:
597
+ Path(name).unlink(missing_ok=True)
598
+ for name,content in previous.items():
599
+ path=Path(name)
600
+ _atomic(path,content)
601
+ _atomic(manifest_path(),previous_manifest)
602
+ _clear_pending(pending);return
603
+ # If the fresh install completed publication, validate before clearing pending.
604
+ if manifest_path().exists():
605
+ _ownership();_clear_pending(pending);return
606
+ removable=[]
607
+ recorded=_resolved_files(value['files'])
608
+ for folder in (skill_dir(),state.data_dir()/'plugin'):
609
+ state.no_symlinks(folder)
610
+ if not folder.exists():continue
611
+ for item in folder.iterdir():
612
+ key=str(item)
613
+ original=key.removesuffix('.install-tmp')
614
+ if key.endswith('.install-tmp'):
615
+ raise OSError('pre-existing temporary ownership ambiguous; preserved; use manual repair')
616
+ if original not in expected or not item.is_file() or item.is_symlink():
617
+ raise OSError('foreign content in interrupted install; preserved')
618
+ # Partial/foreign temps are never erased: exact intended bytes must match.
619
+ info=item.stat()
620
+ if info.st_uid!=os.geteuid() or info.st_mode&0o077 or info.st_nlink!=1:
621
+ raise OSError('unsafe interrupted install content; preserved')
622
+ if _hash(item)!=recorded.get(original,''):
623
+ raise OSError('edited interrupted install content; preserved')
624
+ removable.append(item)
625
+ for item in removable:item.unlink()
626
+ for folder in (skill_dir(),state.data_dir()/'plugin'):
627
+ try:folder.rmdir()
628
+ except FileNotFoundError:pass
629
+ _clear_pending(pending)
630
+
631
+
632
+ def _preflight_state_files(root):
633
+ for leaf in ('install.lock', 'consent.json', 'pending-install.json'):
634
+ state.private_path(root / leaf)
635
+
636
+
637
+ def _numeric_state_warnings(root) -> list:
638
+ """Numeric estimates are optional: the filter works without them, so an
639
+ unsafe metrics leaf is reported, never a reason to refuse the skill."""
640
+ found = []
641
+ for leaf in state.NUMERIC_STATE_LEAVES:
642
+ try:
643
+ state.private_path(root / leaf)
644
+ except OSError as exc:
645
+ found.append('Warning: numeric estimates will not be recorded: ' + str(exc))
646
+ return found
647
+
648
+
649
+ def _preflight_ancestors(root, skill):
650
+ for destination in (root, skill):
651
+ for ancestor in reversed(destination.parents):
652
+ if not ancestor.exists():
653
+ continue
654
+ info = ancestor.lstat()
655
+ if not stat.S_ISDIR(info.st_mode):
656
+ raise OSError('install ancestor is not a directory: ' + str(ancestor))
657
+ if info.st_mode & 0o022 and not info.st_mode & stat.S_ISVTX:
658
+ raise OSError('group/other-writable ancestor directory refused: ' + str(ancestor) + ' (chmod go-w it, or set its sticky bit)')
659
+
660
+
661
+
662
+ def _preflight_write_access(root, skill):
663
+ """Check effective access without creating leaves; ACL inheritance may differ."""
664
+ for destination in (root, root / 'plugin', skill):
665
+ cursor = destination
666
+ while not cursor.exists():
667
+ cursor = cursor.parent
668
+ mode = os.W_OK | os.X_OK
669
+ if cursor == destination:
670
+ mode |= os.R_OK
671
+ if not os.access(cursor, mode, effective_ids=True):
672
+ raise OSError('install destination is not readable/writable/searchable: ' + str(cursor))
673
+ for ancestor in cursor.parents:
674
+ if not os.access(ancestor, os.X_OK, effective_ids=True):
675
+ raise OSError('install ancestor is not searchable: ' + str(ancestor))
676
+ lock = root / 'install.lock'
677
+ if lock.exists() and not os.access(lock, os.R_OK | os.W_OK, effective_ids=True):
678
+ raise OSError('install lock is not readable/writable: ' + str(lock))
679
+
680
+
681
+ def _preflight_file_flags(names) -> None:
682
+ """An immutable or append-only file cannot be replaced or removed. Only
683
+ platforms that expose file flags (macOS, BSD) are checked here."""
684
+ blocked = getattr(stat, 'UF_IMMUTABLE', 0) | getattr(stat, 'SF_IMMUTABLE', 0) | \
685
+ getattr(stat, 'UF_APPEND', 0) | getattr(stat, 'SF_APPEND', 0)
686
+ for name in names:
687
+ try:
688
+ flags = getattr(os.lstat(name), 'st_flags', 0)
689
+ except OSError:
690
+ continue
691
+ if flags & blocked:
692
+ raise OSError('owned file is immutable and cannot be replaced or removed: ' + str(name) +
693
+ '; clear its flag (chflags nouchg) and retry')
694
+
695
+
696
+ def _preflight_removal_access(root, skill, owned, *, purge=False):
697
+ # Without an ownership record nothing in plugin/ or the skill folder is
698
+ # removed by name: the purge sweep skips what it cannot change and reports
699
+ # it as preserved, so foreign folders are never a reason to refuse.
700
+ destinations = [root]
701
+ if owned:
702
+ destinations.extend(Path(name).parent for name in owned['files'])
703
+ # The emptied skill folder is removed from its parent.
704
+ if skill.exists():
705
+ destinations.append(skill.parent)
706
+ for folder in set(destinations):
707
+ if folder.exists() and not os.access(folder, os.W_OK | os.X_OK, effective_ids=True):
708
+ raise OSError('removal directory is not writable/searchable: ' + str(folder) + '; make it writable (chmod u+wx) and retry removal')
709
+ if owned:
710
+ _preflight_file_flags(owned['files'])
711
+ cache = root / 'plugin' / '__pycache__'
712
+ if not owned and (purge and (root / 'plugin').is_symlink()
713
+ or not os.access(root / 'plugin', os.W_OK | os.X_OK, effective_ids=True)):
714
+ cache = None # Foreign symlink targets and folders are never inspected or removed.
715
+ if cache is not None:
716
+ state.no_symlinks(cache)
717
+ if cache is not None and cache.exists():
718
+ if not cache.is_dir():
719
+ raise OSError('removal cache is not a directory; preserved: ' + str(cache))
720
+ if not os.access(cache, os.R_OK | os.W_OK | os.X_OK, effective_ids=True):
721
+ raise OSError('removal cache is not readable/writable/searchable: ' + str(cache))
722
+ lock = root / 'install.lock'
723
+ if lock.exists() and not os.access(lock, os.R_OK | os.W_OK, effective_ids=True):
724
+ raise OSError('install lock is not readable/writable: ' + str(lock))
725
+
726
+
727
+ def _has_content(folder) -> bool:
728
+ """An empty directory left by an earlier removal is not foreign content."""
729
+ if not folder.exists() and not folder.is_symlink():
730
+ return False
731
+ if folder.is_symlink() or not folder.is_dir():
732
+ return True
733
+ return any(entry.name != '.DS_Store' for entry in folder.iterdir())
734
+
735
+
736
+ def _preflight_destination(root, skill):
737
+ _preflight_ancestors(root, skill)
738
+ _preflight_state_files(root)
739
+ state.private_path(root, directory=True)
740
+ state.private_path(root / 'plugin', directory=True)
741
+ owned = _ownership()
742
+ existing = [] if owned else [str(folder) for folder in (skill, root / 'plugin') if _has_content(folder)]
743
+ if existing:
744
+ raise OSError('foreign install destination already exists: ' + ', '.join(existing) + '; move aside or remove and retry')
745
+ state.private_path(skill, directory=True)
746
+ if owned:
747
+ _preflight_file_flags(owned['files'])
748
+ actual = {str(p) for folder in (skill, root / 'plugin') for p in folder.rglob('*')
749
+ if p.is_file() and '__pycache__' not in p.parts and p.name != '.DS_Store'}
750
+ recorded = set(_resolved_files(owned['files']))
751
+ if actual != recorded:
752
+ strays, missing = sorted(actual - recorded), sorted(recorded - actual)
753
+ if strays:
754
+ raise OSError('unowned files in install destination: ' + ', '.join(strays) + '; move aside or remove and retry')
755
+ raise OSError('owned files are missing from the install destination: ' + ', '.join(missing) + '; run uninstall, then install')
756
+ return owned
757
+
758
+
759
+ def install(*, dry_run=False, mode=None) -> None:
760
+ """mode: 'auto' wires the hooks, 'manual' unwires them, None keeps the current mode."""
761
+ if os.name != 'posix':
762
+ raise OSError('native Windows unsupported; use a POSIX environment')
763
+ root, skill = state.data_dir(), skill_dir()
764
+ state.no_symlinks(root); state.no_symlinks(skill)
765
+ # Stable trusted interpreter, never a bare PATH command in an installed skill.
766
+ if not py_path_is_trusted(sys.executable):
767
+ raise OSError('no trusted Python interpreter')
768
+ source = SCRIPTS.parents[2] / 'devin' / 'SKILL.md'
769
+ if not source.is_file():
770
+ raise OSError('run install from a Token Optimizer checkout')
771
+ for name in PAYLOAD:
772
+ if not (SCRIPTS / name).is_file():
773
+ raise OSError('missing payload: ' + name)
774
+ if state.loader_path_info()['status'] != 'documented_default':
775
+ print('Warning: nondefault Devin home; Desktop discovery is unverified. Check the loaded skill in Desktop Customizations; this installer does not configure its loader.')
776
+ _preflight_ancestors(root, skill)
777
+ _preflight_state_files(root)
778
+ for warning in _numeric_state_warnings(root):
779
+ print(warning)
780
+ if dry_run:
781
+ if (root / 'pending-install.json').exists():
782
+ raise OSError('dry-run cannot predict recovery and refuses while recovery is pending: ' + str(root / 'pending-install.json') + '; run a real install or uninstall to attempt recovery. If that refuses, uninstall --purge discards adapter state and stored captures')
783
+ _preflight_destination(root, skill)
784
+ _preflight_write_access(root, skill)
785
+ print('Would install explicit Devin output skill at ' + str(skill))
786
+ recorded = _hook_record()
787
+ if mode == 'auto' or (mode is None and recorded):
788
+ _read_devin_config(devin_config())
789
+ print('Would wire automatic compression hooks into ' + str(devin_config()))
790
+ elif mode == 'manual' and recorded:
791
+ _read_devin_config(devin_config())
792
+ print('Would remove automatic compression hooks from ' + str(devin_config()))
793
+ return
794
+ with _lock():
795
+ _recover_pending()
796
+ owned = _preflight_destination(root, skill)
797
+ # Fresh installs roll back only leaves/directories created by this attempt.
798
+ # Refresh retains old bytes and manifest until a complete update succeeds.
799
+ old_bytes={name:Path(name).read_bytes() for name in owned['files']} if owned else {}
800
+ old_manifest=manifest_path().read_bytes() if owned else None
801
+ new_leaves=[]
802
+ pending=state.data_dir()/'pending-install.json'
803
+ intended={str(root/'plugin'/name):hashlib.sha256(_render_payload(name)).hexdigest() for name in PAYLOAD}
804
+ rendered=source.read_text().replace('@PYTHON@',shlex.quote(os.path.realpath(sys.executable))).replace('@FILTER@',shlex.quote(str(root/'plugin/devin_compress.py')))
805
+ intended[str(skill/'SKILL.md')]=hashlib.sha256(rendered.encode()).hexdigest()
806
+ transaction={'owner':MARKER,'files':intended}
807
+ if owned:
808
+ transaction['previous']={name:base64.b64encode(content).decode('ascii') for name,content in old_bytes.items()}
809
+ transaction['previous_manifest']=base64.b64encode(old_manifest).decode('ascii')
810
+ _atomic(pending,json.dumps(transaction,sort_keys=True).encode())
811
+ try:
812
+ state.private_path(root / 'plugin', directory=True, create=True)
813
+ state.private_dir(skill)
814
+ files = {}
815
+ for name in PAYLOAD:
816
+ target = root / 'plugin' / name
817
+ new_leaves.append(str(target))
818
+ _atomic(target, _render_payload(name))
819
+ files[str(target)] = _hash(target)
820
+ text = source.read_text().replace('@PYTHON@', shlex.quote(os.path.realpath(sys.executable)))
821
+ text = text.replace('@FILTER@', shlex.quote(str(root / 'plugin' / 'devin_compress.py')))
822
+ target = skill / 'SKILL.md'
823
+ new_leaves.append(str(target))
824
+ _atomic(target, text.encode())
825
+ files[str(target)] = _hash(target)
826
+ _atomic(manifest_path(), json.dumps({'owner': MARKER, 'files': files}, sort_keys=True).encode())
827
+ state.enable_consent()
828
+ _clear_pending(pending)
829
+ except Exception:
830
+ if owned:
831
+ for name in set(new_leaves) - set(old_bytes):
832
+ Path(name).unlink(missing_ok=True)
833
+ for name,content in old_bytes.items():
834
+ _atomic(Path(name),content)
835
+ _atomic(manifest_path(),old_manifest)
836
+ else:
837
+ for name in new_leaves:
838
+ Path(name).unlink(missing_ok=True)
839
+ manifest_path().unlink(missing_ok=True)
840
+ for folder in (skill,root/'plugin'):
841
+ try:folder.rmdir()
842
+ except OSError:pass
843
+ _clear_pending(pending)
844
+ raise
845
+ hook_error = None
846
+ try:
847
+ recorded = _hook_record()
848
+ if mode == 'auto' or (mode is None and recorded):
849
+ if mode == 'auto':
850
+ print(ATTESTATION_NOTICE)
851
+ _wire_hooks()
852
+ wired = True
853
+ else:
854
+ if mode == 'manual':
855
+ _unwire_hooks()
856
+ wired = False
857
+ except (OSError, ValueError) as exc:
858
+ hook_error, wired = str(exc), False
859
+ print('Installed Devin output skill: /token-optimizer-output works in every session.')
860
+ if wired:
861
+ print('Automatic mode ON: hooks wired into ' + str(devin_config()) + '. Large output from commands your Devin '
862
+ 'rules already allow (test runs, grep, git status, long logs...) is compressed with no extra prompts; commands Devin '
863
+ 'asks about still ask. Restart running Devin sessions to load the hooks.')
864
+ elif mode == 'manual':
865
+ print('Manual mode: no hooks in the Devin config.')
866
+ else:
867
+ print('Manual mode. For automatic compression run: install.sh --devin --auto')
868
+ print('Consent: private captures may contain confidential/personal data; the adapter makes no extra copies beyond the captures you create.')
869
+ print('A raw passthrough removes its capture after delivery; a compressed result keeps its capture for recovery until you delete it or uninstall --purge. A failed delivery keeps the capture.')
870
+ print('Failures, stderr, binary and credential-matching output pass through RAW to Devin/model context.')
871
+ print('Numeric local estimates retain 30 days, at most 10000 rows.')
872
+ if hook_error:
873
+ raise OSError('the skill is installed, but automatic hooks were NOT wired: ' + hook_error)
874
+
875
+
876
+ def _preflight_purge(root):
877
+ # Purge removes state leaves by name, even unsafe modes/links. It cannot
878
+ # unlink directories: detect those before removing any owned payload.
879
+ for name in ('metrics.db', 'metrics.db-journal', 'metrics.db-wal', 'metrics.db-shm',
880
+ 'consent.json', 'session-salt', 'install.json', 'pending-install.json', *HOOK_STATE_LEAVES):
881
+ leaf = root / name
882
+ if leaf.is_dir() and not leaf.is_symlink():
883
+ raise OSError('purge state leaf is a directory; preserved: ' + str(leaf))
884
+
885
+ captures = root / 'captures'
886
+ state.no_symlinks(captures)
887
+ if captures.exists():
888
+ if not captures.is_dir():
889
+ raise OSError('purge captures root is not a directory: ' + str(captures))
890
+ if not os.access(captures, os.R_OK | os.W_OK | os.X_OK, effective_ids=True):
891
+ raise OSError('captures root is not readable/writable/searchable: ' + str(captures))
892
+ # delete_capture opens every absolute component O_RDONLY|O_DIRECTORY.
893
+ # Verify that descriptor walk before any state/payload removal.
894
+ folders = list(captures.iterdir())
895
+ if any(folder.is_dir() and not folder.is_symlink() and re.fullmatch(r'capture-[0-9a-f]{32}', folder.name) for folder in folders):
896
+ try:
897
+ fd = state.directory_fd(captures)
898
+ os.close(fd)
899
+ except OSError as exc:
900
+ raise OSError('capture descriptor path refused: ' + str(captures) + '; inspect ancestors and move state aside if needed: ' + str(exc)) from exc
901
+ for folder in folders:
902
+ if not folder.is_dir() or folder.is_symlink() or not re.fullmatch(r'capture-[0-9a-f]{32}', folder.name):
903
+ continue
904
+ state.private_path(folder, directory=True)
905
+ if not os.access(folder, os.R_OK | os.W_OK | os.X_OK, effective_ids=True):
906
+ raise OSError('capture directory is not writable/searchable: ' + str(folder))
907
+ for name in ('stdout', 'stderr', '.prepared', 'complete.json'):
908
+ state.no_symlinks(folder / name)
909
+ leaf = folder / name
910
+ if leaf.exists() and not stat.S_ISREG(leaf.lstat().st_mode):
911
+ raise OSError('purge capture leaf must be regular: ' + str(leaf))
912
+
913
+
914
+ def uninstall(*, dry_run=False, purge=False) -> None:
915
+ if os.name != 'posix':
916
+ raise OSError('native Windows unsupported')
917
+ root = state.data_dir()
918
+ if (not root.exists() and not root.is_symlink()
919
+ and not skill_dir().exists() and not skill_dir().is_symlink()):
920
+ print('No owned Devin install found.')
921
+ return
922
+ # The removal lock refuses a group/other-writable ancestor; say so here so
923
+ # a dry-run predicts it.
924
+ _preflight_ancestors(root, skill_dir())
925
+ state.private_path(root, directory=True)
926
+ state.private_path(root / 'install.lock')
927
+ if purge:
928
+ _preflight_purge(root)
929
+ pending = root / 'pending-install.json'
930
+ if dry_run and not purge and (pending.exists() or pending.is_symlink()):
931
+ state.private_path(pending)
932
+ raise OSError('dry-run refuses while recovery is pending: ' + str(pending) + '; run a real install or uninstall to attempt recovery. If that refuses, uninstall --purge discards adapter state and stored captures')
933
+ # Purge is independent of an install manifest: plain uninstall may precede it.
934
+ # Under purge a stale or foreign-version pending record is deleted, not
935
+ # reconciled, so it must never block the purge path.
936
+ if not dry_run and not purge and root.exists():
937
+ with _lock():_recover_pending()
938
+ owned = _ownership_for_removal(purge=purge)
939
+ if not owned and not purge:
940
+ print('No owned Devin install found.')
941
+ return
942
+ _preflight_removal_access(root, skill_dir(), owned, purge=purge)
943
+ if dry_run:
944
+ if purge and not owned:
945
+ _preflight_sweep_access(_purge_recorded(), _known_payload_digests())
946
+ if _hook_record(tolerant=purge):
947
+ _read_devin_config(devin_config())
948
+ print('Would remove automatic compression hooks from ' + str(devin_config()) + '; other hooks stay.')
949
+ if purge:
950
+ print('Would remove unchanged owned files, numeric state and fixed stored-capture leaves; foreign capture content is preserved.')
951
+ else:
952
+ print('Would remove owned skill/payload; numeric state and captures remain unchanged.')
953
+ return
954
+ with _lock():
955
+ if purge:
956
+ # Recheck after taking the lock: preflight paths may have changed.
957
+ _preflight_purge(root)
958
+ owned = _ownership_for_removal(purge=purge)
959
+ _preflight_removal_access(root, skill_dir(), owned, purge=purge)
960
+ # Unwire before any payload is removed. A plain uninstall stops when the
961
+ # config cannot be edited; purge carries on (a stale entry is inert:
962
+ # its command ends in '|| true' and never blocks a tool call).
963
+ try:
964
+ if _unwire_hooks(tolerant=purge):
965
+ print('Removed automatic compression hooks from ' + str(devin_config()) + '; other hooks unchanged.')
966
+ except (OSError, ValueError) as exc:
967
+ if not purge:
968
+ raise OSError('automatic hooks could not be removed, nothing was uninstalled: ' + str(exc)) from None
969
+ print('Warning: automatic hooks could not be removed from ' + str(devin_config()) + ': ' + str(exc) +
970
+ '. Delete the Token Optimizer entries under "hooks" by hand; until then they do nothing.')
971
+ removed_payload = bool(owned)
972
+ if purge:
973
+ recorded = _purge_recorded()
974
+ known = _known_payload_digests()
975
+ if not owned:
976
+ _preflight_sweep_access(recorded, known)
977
+ if owned:
978
+ # Directory access was checked above; file flags and ACLs can still
979
+ # refuse one unlink. Finish the rest, keep the ownership record so a
980
+ # rerun completes, and stop before any other state is removed.
981
+ stuck = []
982
+ for name in owned['files']:
983
+ try:
984
+ Path(name).unlink(missing_ok=True)
985
+ except OSError as exc:
986
+ stuck.append(name + ' (' + (exc.strerror or str(exc)) + ')')
987
+ if stuck:
988
+ raise OSError('could not remove owned files: ' + ', '.join(stuck) +
989
+ '; other owned files were removed and the ownership record was kept.'
990
+ ' Clear the file flags or permissions, then rerun the same uninstall')
991
+ manifest_path().unlink(missing_ok=True)
992
+ cache = state.data_dir() / 'plugin' / '__pycache__'
993
+ try:
994
+ cache_present = cache.exists() and not (purge and not owned and (state.data_dir() / 'plugin').is_symlink())
995
+ except OSError:
996
+ cache_present = False # Inaccessible foreign folder: never inspected.
997
+ if cache_present:
998
+ state.no_symlinks(cache)
999
+ try:
1000
+ for item in cache.iterdir():
1001
+ if item.name.endswith('.pyc') and item.is_file() and not item.is_symlink():
1002
+ item.unlink()
1003
+ cache.rmdir()
1004
+ except OSError:
1005
+ print('Cache content was preserved under ' + str(cache) + '; inspect it before retrying removal.')
1006
+ for folder in (skill_dir(), state.data_dir() / 'plugin'):
1007
+ try: folder.rmdir()
1008
+ except OSError: pass
1009
+ if purge:
1010
+ # Identify unchanged adapter files while the records still exist.
1011
+ swept = _sweep_candidates(recorded, known)
1012
+ for name in ('metrics.db', 'metrics.db-journal', 'metrics.db-wal', 'metrics.db-shm',
1013
+ 'consent.json', 'session-salt', 'install.json', 'pending-install.json', *HOOK_STATE_LEAVES):
1014
+ # Purge removes the state leaf by name even when its mode,
1015
+ # link count or spelling would fail the privacy gate.
1016
+ (state.data_dir() / name).unlink(missing_ok=True)
1017
+ # The sweep removes only files whose digest the manifest recorded
1018
+ # or a known shipped version produced: unchanged adapter files.
1019
+ # Edited files and foreign content are preserved.
1020
+ for item in swept:
1021
+ try:
1022
+ item.unlink()
1023
+ removed_payload = True
1024
+ except OSError:
1025
+ pass
1026
+ for folder in (state.data_dir() / 'plugin', skill_dir()):
1027
+ try:
1028
+ if folder.is_symlink() or not folder.is_dir():
1029
+ continue
1030
+ state.no_symlinks(folder)
1031
+ except OSError:
1032
+ continue
1033
+ try: folder.rmdir()
1034
+ except OSError: pass
1035
+ captures = state.data_dir() / 'captures'
1036
+ if captures.exists():
1037
+ state.no_symlinks(captures)
1038
+ for folder in captures.iterdir():
1039
+ if not folder.is_dir() or folder.is_symlink() or not re.fullmatch(r'capture-[0-9a-f]{32}', folder.name):
1040
+ continue
1041
+ # Stored captures may hold credentials; purge removes them.
1042
+ # Foreign-named content keeps its directory (and itself).
1043
+ state.delete_capture(folder)
1044
+ try: captures.rmdir()
1045
+ except OSError: pass
1046
+ remaining = [str(folder) for folder in (state.data_dir() / 'plugin', skill_dir(), captures) if folder.exists()]
1047
+ if remaining:
1048
+ print('Unowned or edited files were preserved under ' + ' and '.join(remaining) +
1049
+ '; inspect them and move the folders aside to finish removing the adapter.')
1050
+ print('Purged numeric metrics, SQLite sidecars, consent and HMAC key.' +
1051
+ (' Some capture content was preserved; inspect the reported captures directory.' if captures.exists() else ' Stored captures removed.'))
1052
+ if not purge:
1053
+ print('Original captures unchanged.')
1054
+ print('Removed owned Devin skill/payload.' if removed_payload else 'No owned Devin skill/payload was installed.')
1055
+
1056
+
1057
+ def main(argv=None) -> int:
1058
+ parser = argparse.ArgumentParser(description=__doc__)
1059
+ parser.add_argument('action', choices=('install', 'uninstall'))
1060
+ parser.add_argument('--dry-run', action='store_true')
1061
+ parser.add_argument('--purge', action='store_true')
1062
+ modes = parser.add_mutually_exclusive_group()
1063
+ modes.add_argument('--auto', action='store_true',
1064
+ help='also wire automatic compression hooks; ' + ATTESTATION_NOTICE)
1065
+ modes.add_argument('--manual', action='store_true', help='remove automatic hooks, keep the skill')
1066
+ args = parser.parse_args(argv)
1067
+ if args.action == 'install' and args.purge:
1068
+ parser.error('--purge is uninstall-only')
1069
+ if args.action == 'uninstall' and (args.auto or args.manual):
1070
+ parser.error('--auto and --manual are install-only')
1071
+ try:
1072
+ if args.action == 'install':
1073
+ install(dry_run=args.dry_run, mode='auto' if args.auto else 'manual' if args.manual else None)
1074
+ else:
1075
+ uninstall(dry_run=args.dry_run, purge=args.purge)
1076
+ return 0
1077
+ except RecursionError as exc:
1078
+ print('Devin install refused: ' + str(exc), file=sys.stderr)
1079
+ return 2
1080
+ except (OSError, ValueError) as exc:
1081
+ print('Devin install refused: ' + str(exc), file=sys.stderr)
1082
+ return 1
1083
+
1084
+
1085
+ if __name__ == '__main__':
1086
+ raise SystemExit(main())