ctx-harness 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (246) hide show
  1. ctx/__init__.py +5 -0
  2. ctx/__main__.py +4 -0
  3. ctx/_proc.py +259 -0
  4. ctx/_retrieval/__init__.py +10 -0
  5. ctx/_retrieval/common.py +212 -0
  6. ctx/_retrieval/get.py +933 -0
  7. ctx/_retrieval/rg_engine.py +161 -0
  8. ctx/_retrieval/search.py +975 -0
  9. ctx/_retrieval/spans.py +375 -0
  10. ctx/_retrieval/stats.py +215 -0
  11. ctx/_retrieval/targets.py +180 -0
  12. ctx/_retrieval/telemetry.py +98 -0
  13. ctx/_vendor/__init__.py +7 -0
  14. ctx/_vendor/scip.proto +962 -0
  15. ctx/_vendor/scip_pb2.py +87 -0
  16. ctx/accounting.py +9 -0
  17. ctx/acp.py +411 -0
  18. ctx/agent.py +422 -0
  19. ctx/agyperm.py +281 -0
  20. ctx/agysdk.py +172 -0
  21. ctx/anchors.py +234 -0
  22. ctx/ask.py +381 -0
  23. ctx/astgrep.py +602 -0
  24. ctx/binfmt.py +513 -0
  25. ctx/bounds.py +109 -0
  26. ctx/callgraph.py +1231 -0
  27. ctx/capsule.py +529 -0
  28. ctx/capture.py +450 -0
  29. ctx/catalog.py +183 -0
  30. ctx/ccperm.py +687 -0
  31. ctx/checkpoint.py +114 -0
  32. ctx/cli.py +1344 -0
  33. ctx/cliux.py +255 -0
  34. ctx/codeindex.py +711 -0
  35. ctx/codeverbs.py +745 -0
  36. ctx/collab.py +507 -0
  37. ctx/collab_sessions.py +281 -0
  38. ctx/command_spans.py +212 -0
  39. ctx/commands/__init__.py +16 -0
  40. ctx/commands/_errors.py +53 -0
  41. ctx/commands/admin.py +429 -0
  42. ctx/commands/binary.py +76 -0
  43. ctx/commands/collab.py +226 -0
  44. ctx/commands/compress.py +28 -0
  45. ctx/commands/coverage.py +16 -0
  46. ctx/commands/edit.py +126 -0
  47. ctx/commands/emit.py +173 -0
  48. ctx/commands/execute.py +450 -0
  49. ctx/commands/history.py +101 -0
  50. ctx/commands/hosts.py +504 -0
  51. ctx/commands/intake.py +93 -0
  52. ctx/commands/plans.py +294 -0
  53. ctx/commands/retrieve.py +460 -0
  54. ctx/commands/rewrite.py +70 -0
  55. ctx/commands/semantic.py +64 -0
  56. ctx/commands/surfaces.py +136 -0
  57. ctx/commands/tasks.py +63 -0
  58. ctx/commands/view.py +683 -0
  59. ctx/config.py +848 -0
  60. ctx/config_edit.py +475 -0
  61. ctx/containers.py +2039 -0
  62. ctx/context_archive_policy.py +49 -0
  63. ctx/context_compression.py +70 -0
  64. ctx/contracts/generic.toml +22 -0
  65. ctx/contracts/investigate.toml +46 -0
  66. ctx/contracts/lint.toml +45 -0
  67. ctx/contracts/pytest.toml +42 -0
  68. ctx/contracts.py +325 -0
  69. ctx/controllers/__init__.py +1 -0
  70. ctx/controllers/investigation.py +414 -0
  71. ctx/controllers/investigation_contract.py +180 -0
  72. ctx/coverage.py +453 -0
  73. ctx/data/antigravity/agents/ctx-explorer.md +64 -0
  74. ctx/data/antigravity/hooks.json +43 -0
  75. ctx/data/antigravity/mcp_config.json +9 -0
  76. ctx/data/antigravity/plugin.json +5 -0
  77. ctx/data/antigravity/skills/ctx-harness/SKILL.md +185 -0
  78. ctx/data/antigravity/skills/ctx-harness/references/evidence-plans.md +104 -0
  79. ctx/data/antigravity/skills/ctx-harness/references/harness-collaboration.md +81 -0
  80. ctx/data/antigravity/skills/ctx-harness/references/model-catalog.md +87 -0
  81. ctx/data/antigravity/skills/ctx-harness/references/repository-addressing.md +9 -0
  82. ctx/data/antigravity/skills/ctx-harness/references/routing-policy.md +21 -0
  83. ctx/data/antigravity/skills/ctx-harness/references/verbs.md +142 -0
  84. ctx/data/codex/AGENTS.md +36 -0
  85. ctx/data/codex/config.toml +20 -0
  86. ctx/data/codex/hooks.json +51 -0
  87. ctx/data/ctx_agy.py +241 -0
  88. ctx/data/model-catalog.json +114 -0
  89. ctx/data/model-prices.json +39 -0
  90. ctx/data/native-hooks/bridge.mjs +28 -0
  91. ctx/data/native-hooks/dsh.mjs +27 -0
  92. ctx/data/native-hooks/hermes.py +47 -0
  93. ctx/data/native-hooks/omp.mjs +19 -0
  94. ctx/data/native-hooks/opencode.mjs +22 -0
  95. ctx/debt.py +99 -0
  96. ctx/deliverables.py +2507 -0
  97. ctx/digest/__init__.py +594 -0
  98. ctx/digest/base.py +360 -0
  99. ctx/digest/binprof.py +69 -0
  100. ctx/digest/block_selection.py +99 -0
  101. ctx/digest/capped.py +137 -0
  102. ctx/digest/cfgprof.py +451 -0
  103. ctx/digest/chunkmap.py +411 -0
  104. ctx/digest/commprof.py +372 -0
  105. ctx/digest/containerprof.py +93 -0
  106. ctx/digest/decision_client.py +188 -0
  107. ctx/digest/delimprof.py +905 -0
  108. ctx/digest/evidence_map.py +955 -0
  109. ctx/digest/evidence_render.py +512 -0
  110. ctx/digest/intakeprof.py +456 -0
  111. ctx/digest/jsonprof.py +195 -0
  112. ctx/digest/lintprof.py +201 -0
  113. ctx/digest/logprof.py +236 -0
  114. ctx/digest/markupprof.py +548 -0
  115. ctx/digest/mdprof.py +452 -0
  116. ctx/digest/moreprofs.py +662 -0
  117. ctx/digest/nbprof.py +562 -0
  118. ctx/digest/picker.py +342 -0
  119. ctx/digest/pytestprof.py +650 -0
  120. ctx/digest/searchprof.py +151 -0
  121. ctx/digest/shapeutil.py +392 -0
  122. ctx/digest/tableprof.py +156 -0
  123. ctx/digest/text.py +390 -0
  124. ctx/digest/traceprof.py +855 -0
  125. ctx/digest/udiffprof.py +457 -0
  126. ctx/edit_expansion.py +116 -0
  127. ctx/edit_outcomes.py +495 -0
  128. ctx/edit_policy.py +122 -0
  129. ctx/edit_transactions.py +602 -0
  130. ctx/edit_verification.py +161 -0
  131. ctx/engagement.py +347 -0
  132. ctx/evidence.py +313 -0
  133. ctx/evidence_access.py +74 -0
  134. ctx/evidence_ops.py +102 -0
  135. ctx/evidence_outcomes.py +544 -0
  136. ctx/execution.py +511 -0
  137. ctx/facts.py +1397 -0
  138. ctx/filesets.py +170 -0
  139. ctx/gitstatus.py +209 -0
  140. ctx/governance.py +530 -0
  141. ctx/guard_policy.py +29 -0
  142. ctx/handoff_policy.py +19 -0
  143. ctx/hook.py +7924 -0
  144. ctx/host_config.py +535 -0
  145. ctx/hosts.py +680 -0
  146. ctx/installer.py +1512 -0
  147. ctx/intake.py +655 -0
  148. ctx/jobs.py +706 -0
  149. ctx/ladders.py +616 -0
  150. ctx/launchform.py +511 -0
  151. ctx/lsp.py +595 -0
  152. ctx/lsp_edits.py +149 -0
  153. ctx/lsp_service.py +253 -0
  154. ctx/mcp.py +567 -0
  155. ctx/mcp_edits.py +86 -0
  156. ctx/mcp_hosts.py +301 -0
  157. ctx/media.py +2475 -0
  158. ctx/mediaread.py +746 -0
  159. ctx/mutation_policy.py +23 -0
  160. ctx/native_hooks.py +193 -0
  161. ctx/native_prewalk.py +131 -0
  162. ctx/orchestrator.py +2469 -0
  163. ctx/pack.py +524 -0
  164. ctx/pathglob.py +364 -0
  165. ctx/plan_exec.py +902 -0
  166. ctx/plan_ir.py +575 -0
  167. ctx/plan_ops.py +932 -0
  168. ctx/plan_value.py +332 -0
  169. ctx/policy.py +438 -0
  170. ctx/post_edit_diagnostics.py +424 -0
  171. ctx/prefix-manifest.json +11 -0
  172. ctx/prefixassets.py +204 -0
  173. ctx/prewalk.py +83 -0
  174. ctx/pricing.py +186 -0
  175. ctx/promptgate.py +638 -0
  176. ctx/proxy.py +615 -0
  177. ctx/proxywindow.py +71 -0
  178. ctx/prune.py +393 -0
  179. ctx/pyeval.py +93 -0
  180. ctx/query.py +1440 -0
  181. ctx/recovery_policy.py +67 -0
  182. ctx/refgrammar.py +31 -0
  183. ctx/reflex.py +1729 -0
  184. ctx/refs.py +83 -0
  185. ctx/relay.py +807 -0
  186. ctx/replay.py +549 -0
  187. ctx/repomap.py +528 -0
  188. ctx/rescue.py +241 -0
  189. ctx/residence.py +975 -0
  190. ctx/resolver.py +637 -0
  191. ctx/retrieval.py +84 -0
  192. ctx/route_telemetry.py +225 -0
  193. ctx/rundiff.py +326 -0
  194. ctx/scip_index.py +195 -0
  195. ctx/scip_ingest.py +492 -0
  196. ctx/scorecard.py +811 -0
  197. ctx/sdk.py +455 -0
  198. ctx/searchq.py +321 -0
  199. ctx/secretpaths.py +58 -0
  200. ctx/selfcmd.py +196 -0
  201. ctx/semantic/__init__.py +12 -0
  202. ctx/semantic/contract.py +181 -0
  203. ctx/semantic/engine.py +231 -0
  204. ctx/semantic/evidence.py +192 -0
  205. ctx/semantic/hosts.py +44 -0
  206. ctx/semantic/worker.py +104 -0
  207. ctx/semgrep_engine.py +174 -0
  208. ctx/seq.py +142 -0
  209. ctx/session_economics.py +173 -0
  210. ctx/sessiondir.py +194 -0
  211. ctx/setup_policy.py +27 -0
  212. ctx/setup_telemetry.py +163 -0
  213. ctx/shsplit.py +345 -0
  214. ctx/skeleton.py +1055 -0
  215. ctx/snapcompact.py +383 -0
  216. ctx/statusline.py +328 -0
  217. ctx/steward.py +298 -0
  218. ctx/store.py +787 -0
  219. ctx/stream_rules.py +164 -0
  220. ctx/substitute.py +287 -0
  221. ctx/surface.py +1796 -0
  222. ctx/surface_gateway.py +663 -0
  223. ctx/surface_launch.py +609 -0
  224. ctx/surface_profiles.py +452 -0
  225. ctx/surface_reconcile.py +298 -0
  226. ctx/task_context.py +121 -0
  227. ctx/task_runtime.py +377 -0
  228. ctx/taskledger.py +592 -0
  229. ctx/textutil.py +1069 -0
  230. ctx/toolrepair.py +84 -0
  231. ctx/toolresult.py +626 -0
  232. ctx/tooltelemetry.py +64 -0
  233. ctx/toolviews.py +114 -0
  234. ctx/trajectory.py +715 -0
  235. ctx/usage.py +338 -0
  236. ctx/verification_policy.py +18 -0
  237. ctx/wave_policy.py +24 -0
  238. ctx/worker_yield.py +109 -0
  239. ctx/workspace.py +471 -0
  240. ctx/worktree_isolation.py +283 -0
  241. ctx/wrap.py +1282 -0
  242. ctx_harness-0.5.0.dist-info/METADATA +437 -0
  243. ctx_harness-0.5.0.dist-info/RECORD +246 -0
  244. ctx_harness-0.5.0.dist-info/WHEEL +4 -0
  245. ctx_harness-0.5.0.dist-info/entry_points.txt +2 -0
  246. ctx_harness-0.5.0.dist-info/licenses/LICENSE +201 -0
ctx/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """straitjacket / ctx-harness: local context containment for coding agents."""
2
+
3
+ __version__ = "0.5.0"
4
+
5
+ POLICY_VERSION = "default/v1"
ctx/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from ctx.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
ctx/_proc.py ADDED
@@ -0,0 +1,259 @@
1
+ """The subprocess mechanism the foreground and background runners share (R7).
2
+
3
+ :mod:`ctx.execution` runs a command synchronously and returns its manifest;
4
+ :mod:`ctx.jobs` runs one under a detached supervisor that outlives the caller.
5
+ They are genuinely different things and this module does not pretend
6
+ otherwise — it holds only the two steps whose *implementation* was identical
7
+ in both, character for character:
8
+
9
+ * :func:`wait_or_kill` — bound a child's runtime and, on expiry, take down
10
+ the whole process group rather than the leader (both runners spawn with
11
+ ``start_new_session``, so a shell that forked children leaves orphans if you
12
+ only kill the pid you know).
13
+ * :func:`exit_status` — turn a ``Popen.returncode`` into the manifest's
14
+ ``(exitCode, signal)`` pair. Signal death is NOT an exit code: the manifest
15
+ reports ``exitCode: null`` plus a signal name, and a run killed by a signal
16
+ must never read as "exited 0" or "exited 137".
17
+
18
+ Deliberately stdlib-only and dependency-free. ``ctx.jobs.supervise_main`` is
19
+ a detached process that reads everything it needs from ``meta.json`` and
20
+ never resolves a workspace or opens the store; importing these two helpers
21
+ out of :mod:`ctx.execution` would have dragged the store, the workspace
22
+ resolver and git parsing into it. That property is the reason this is its own
23
+ module rather than two more functions in ``execution.py``.
24
+
25
+ What is NOT here, because the similarity is superficial rather than shared
26
+ logic — see ``tests/test_proc_mechanism.py``, which records the reasoning:
27
+
28
+ * Argv validation. The messages match but the exception classes differ
29
+ (``ExecutionError`` / ``JobError``), and a shared validator parameterized
30
+ by exception class is more machinery than the two lines it saves.
31
+ * The ``Popen`` call itself. One feeds a spooled stdin file and raises on
32
+ ``FileNotFoundError``; the other feeds ``DEVNULL`` and records a ``failed``
33
+ state transition into ``meta.json``. Same API, different contracts.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import os
39
+ import signal as signal_mod
40
+ import subprocess
41
+ import time
42
+
43
+ __all__ = ["exit_status", "native_exit_status", "kill_and_reap", "wait_or_kill",
44
+ "shell_popen_args", "capture_shell", "capture_shell_choice", "SH_FALLBACK_NOTE"]
45
+
46
+ #: Where a shell may be installed besides $PATH (Claude Code's own search).
47
+ _STANDARD_DIRS = ("/bin", "/usr/bin", "/usr/local/bin", "/opt/homebrew/bin")
48
+ _VERIFIED: dict[str, bool] = {}
49
+ _CHOICE: dict[tuple, tuple[str, str | None]] = {}
50
+
51
+ #: The one line said when no bash or zsh could be found.
52
+ SH_FALLBACK_NOTE = ("[ctx: no working bash or zsh found; the command ran under /bin/sh, "
53
+ "which may not accept bash syntax]")
54
+
55
+
56
+ def _known_shells() -> frozenset[str]:
57
+ """Resolved paths of the system's own shells: every entry of
58
+ /etc/shells, and the bash/zsh installed beside the system's /bin/sh."""
59
+ out = set()
60
+ try:
61
+ with open("/etc/shells", encoding="utf-8") as fh:
62
+ for line in fh:
63
+ line = line.strip()
64
+ if line.startswith("/"):
65
+ out.add(os.path.realpath(line))
66
+ except OSError:
67
+ pass
68
+ for d in ("/bin", "/usr/bin", os.path.dirname(os.path.realpath("/bin/sh"))):
69
+ for name in ("bash", "zsh"):
70
+ p = os.path.join(d, name)
71
+ if os.path.exists(p):
72
+ out.add(os.path.realpath(p))
73
+ return frozenset(out)
74
+
75
+
76
+ def _working_shell(path: str | None) -> bool:
77
+ """Is ``path`` a bash or zsh that runs? Asked of the binary itself (it
78
+ must report BASH_VERSION or ZSH_VERSION), never read off its name: a
79
+ file named ``bash`` can be anything."""
80
+ if not path or not os.path.isabs(path) or os.path.isdir(path) or not os.access(path, os.X_OK):
81
+ return False
82
+ if os.path.realpath(path) not in _known_shells():
83
+ return False
84
+ hit = _VERIFIED.get(path)
85
+ if hit is not None:
86
+ return hit
87
+ env = {k: v for k, v in os.environ.items() if k not in ("BASH_ENV", "ENV")}
88
+ try:
89
+ out = subprocess.run(
90
+ [path, "-c", 'printf %s "${BASH_VERSION:-}${ZSH_VERSION:-}"'],
91
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=5, env=env)
92
+ ok = out.returncode == 0 and bool(out.stdout.strip())
93
+ except (OSError, subprocess.SubprocessError):
94
+ ok = False
95
+ _VERIFIED[path] = ok
96
+ return ok
97
+
98
+
99
+ def _search(names: tuple[str, ...]) -> str | None:
100
+ import shutil
101
+
102
+ for name in names:
103
+ found = shutil.which(name)
104
+ cands = ([found] if found else []) + [os.path.join(d, name) for d in _STANDARD_DIRS]
105
+ for cand in cands:
106
+ if _working_shell(cand):
107
+ return cand
108
+ return None
109
+
110
+
111
+ def capture_shell_choice() -> tuple[str, str | None]:
112
+ """``(shell, note)``: the shell that runs a ``--shell`` command string,
113
+ and the one line to say when it is not a shell the host would use.
114
+
115
+ The shell the agent's own shell tool uses, so a string written for it --
116
+ brace expansion, ``[[ ]]``, arrays, here-strings, ``set -o pipefail`` --
117
+ runs the same. Claude Code documents its choice (env-vars,
118
+ ``CLAUDE_CODE_SHELL``): that variable when it names a working bash or
119
+ zsh, else ``$SHELL`` when that is bash or zsh, else the first working
120
+ zsh, then bash, on PATH and the standard locations; never another shell.
121
+ Under Claude Code (``CLAUDECODE=1`` in its Bash tool's environment) ctx
122
+ follows exactly that. Elsewhere the same, but preferring bash when
123
+ ``$SHELL`` is not bash or zsh (fish, unset, a wrapper). ``CTX_SHELL``
124
+ overrides when it is a working bash or zsh. Only when no bash or zsh
125
+ exists at all does the string go to /bin/sh, and ``note`` says so.
126
+ """
127
+ key = tuple(os.environ.get(k) for k in
128
+ ("CTX_SHELL", "CLAUDECODE", "CLAUDE_CODE_SHELL", "SHELL", "PATH"))
129
+ hit = _CHOICE.get(key)
130
+ if hit is not None:
131
+ return hit
132
+ in_claude = os.environ.get("CLAUDECODE") == "1"
133
+ explicit = [os.environ.get("CTX_SHELL")]
134
+ if in_claude:
135
+ explicit.append(os.environ.get("CLAUDE_CODE_SHELL"))
136
+ explicit.append(os.environ.get("SHELL"))
137
+ choice: tuple[str, str | None] | None = None
138
+ for cand in explicit:
139
+ if _working_shell(cand):
140
+ choice = (str(cand), None)
141
+ break
142
+ if choice is None:
143
+ found = _search(("zsh", "bash") if in_claude else ("bash", "zsh"))
144
+ choice = (found, None) if found else ("/bin/sh", SH_FALLBACK_NOTE)
145
+ _CHOICE[key] = choice
146
+ return choice
147
+
148
+
149
+ def capture_shell() -> str:
150
+ """The shell :func:`capture_shell_choice` picks."""
151
+ return capture_shell_choice()[0]
152
+
153
+
154
+ def shell_popen_args(command: str) -> tuple[object, bool]:
155
+ """``(popen_args, shell)`` that run ``command`` VERBATIM in that shell."""
156
+ if os.name == "nt": # pragma: no cover - POSIX shells only
157
+ return command, True
158
+ return [capture_shell(), "-c", command], False
159
+
160
+
161
+ def kill_and_reap(proc: subprocess.Popen) -> None:
162
+ """Stop an owned process group and reap its leader, even if it exited.
163
+
164
+ Call only for children started with ``start_new_session=True``. A dead
165
+ leader can still have live descendants, so do not gate the group signal
166
+ on ``poll()``. This is process cleanup, not containment of descendants
167
+ that deliberately escape the group with ``setsid()``.
168
+ """
169
+ try:
170
+ os.killpg(proc.pid, signal_mod.SIGKILL)
171
+ except (ProcessLookupError, PermissionError):
172
+ proc.kill()
173
+ proc.wait()
174
+
175
+
176
+ def wait_or_kill(proc: subprocess.Popen, timeout: float | None, *, cancelled=None) -> bool:
177
+ """Wait for ``proc``; on timeout SIGKILL its process group and reap it.
178
+
179
+ Returns True iff the timeout expired. ``timeout=None`` waits forever.
180
+ Interruption or another wait failure also stops the group, then propagates
181
+ the original exception. It must never be reported as a successful run.
182
+
183
+ The group kill is the point: both callers spawn with
184
+ ``start_new_session=True``, so the child leads its own process group and
185
+ ``killpg`` reaches anything it forked. ``ProcessLookupError`` (already
186
+ gone) and ``PermissionError`` (unsignalable group) fall back to killing
187
+ the leader, exactly as both copies did. The second ``wait()`` is not
188
+ optional — without it the killed child stays a zombie.
189
+ """
190
+ try:
191
+ if cancelled is None:
192
+ proc.wait(timeout=timeout)
193
+ else:
194
+ deadline = None if timeout is None else time.monotonic() + timeout
195
+ while True:
196
+ if cancelled():
197
+ kill_and_reap(proc)
198
+ return False
199
+ remaining = None if deadline is None else deadline - time.monotonic()
200
+ if remaining is not None and remaining <= 0:
201
+ kill_and_reap(proc)
202
+ return True
203
+ try:
204
+ proc.wait(timeout=min(0.05, remaining) if remaining is not None else 0.05)
205
+ break
206
+ except subprocess.TimeoutExpired:
207
+ continue
208
+ except subprocess.TimeoutExpired:
209
+ kill_and_reap(proc)
210
+ return True
211
+ except BaseException:
212
+ kill_and_reap(proc)
213
+ raise
214
+ if timeout == 0:
215
+ # timeout=0 means the caller already detected the timeout elsewhere
216
+ # (orchestrator._run_bounded: communicate() timed out) and is forcing
217
+ # cleanup now. The leader may have exited already while an orphaned
218
+ # grandchild keeps the process group alive, so wait() did not raise
219
+ # and killpg still has to run. Improvement route, first live run.
220
+ kill_and_reap(proc)
221
+ return False
222
+
223
+
224
+ def exit_status(returncode: int | None) -> tuple[int | None, str | None]:
225
+ """``Popen.returncode`` → the manifest's ``(exitCode, signal)`` pair.
226
+
227
+ A negative ``returncode`` means death by signal N. That is reported as
228
+ ``exitCode: null`` with the signal's name, never as a number — a run
229
+ killed by SIGKILL is not a run that exited. An unrecognized signal number
230
+ still gets a name (``SIG9``) rather than falling through as an exit code.
231
+ """
232
+ if returncode is not None and returncode < 0:
233
+ try:
234
+ return None, signal_mod.Signals(-returncode).name
235
+ except ValueError: # pragma: no cover - exotic signal number
236
+ return None, f"SIG{-returncode}"
237
+ return returncode, None
238
+
239
+
240
+ def native_exit_status(result: dict) -> int:
241
+ """Shell-facing status, distinct from the command's typed termination.
242
+
243
+ A timeout is 124. A signal is 128+N, while the manifest continues to
244
+ carry exitCode=null and signal=SIGNAME. Unknown status must fail.
245
+ """
246
+ if result.get("timedOut"):
247
+ return 124
248
+ name = result.get("signal")
249
+ if name:
250
+ try:
251
+ number = int(signal_mod.Signals[str(name)])
252
+ except (KeyError, ValueError):
253
+ try:
254
+ number = int(str(name).removeprefix("SIG"))
255
+ except ValueError:
256
+ return 1
257
+ return 128 + number if 0 < number < 128 else 1
258
+ code = result.get("exitCode")
259
+ return code if type(code) is int and 0 <= code <= 255 else 1
@@ -0,0 +1,10 @@
1
+ """Private implementation package backing ``ctx.retrieval`` (SPEC §6.3-6.5).
2
+
3
+ Nothing here is a stable import path — everything importable is re-exported
4
+ by ``ctx.retrieval``, which is the byte-compatible facade every other module
5
+ (``cli``, ``mcp``, ``codeverbs``, ``rundiff``, ``digest``, tests, evals)
6
+ imports from. Submodules exist purely to keep each concern (targets, the
7
+ optional ripgrep engine, search, get, spans, stats, telemetry) small enough
8
+ to read in one sitting; import from ``ctx.retrieval`` instead of reaching
9
+ into these directly.
10
+ """
@@ -0,0 +1,212 @@
1
+ """Shared errors, ref parsing, and emission helpers for the retrieval package.
2
+
3
+ Internal — nothing outside ``ctx.retrieval`` (the public facade) and its
4
+ sibling ``ctx._retrieval.*`` modules should import from here directly.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from ctx.refs import Ref, parse_ref
10
+ from ctx.store import Store
11
+ from ctx.textutil import _redaction_of, bounded, redact, sanitize_for_model
12
+ from ctx.workspace import Workspace
13
+
14
+
15
+ class RetrievalError(Exception):
16
+ pass
17
+
18
+
19
+ def _emit(
20
+ ws: Workspace,
21
+ text: str,
22
+ budget_tokens: int,
23
+ continuation: str | None = None,
24
+ *,
25
+ handle: str | None = None,
26
+ exact: bool = False,
27
+ ) -> str:
28
+ """Bound a retrieval result, keeping a way back to the rest of it.
29
+
30
+ ``continuation`` is set when the *caller* decided to cut (a line span it
31
+ clipped itself). ``handle`` covers the other cut: ``bounded`` trimming on
32
+ the token budget, which the caller cannot predict. Without it a
33
+ budget-truncated result ends at the bare truncation note, with no address
34
+ — the same defect fixed on the digest side, and it lives here too.
35
+
36
+ ``exact`` marks an EXACT-BYTES answer (``ctx get --bytes``). Control
37
+ stripping is a display nicety everywhere else and the thing that makes
38
+ this answer wrong: it silently deletes every byte below 0x20 from a slice
39
+ the caller asked for verbatim. Redaction still runs -- it is a security
40
+ control, not a presentation one, and it announces itself when it fires,
41
+ so the one case where an exact answer is not byte-exact says so.
42
+ """
43
+ if exact:
44
+ # The exact path skips control STRIPPING, not redaction -- but it goes
45
+ # through the same switch, so `[redaction] enabled = false` means the
46
+ # same thing here as everywhere else.
47
+ enabled, patterns = _redaction_of(ws.config.redaction)
48
+ text, redactions = redact(text, patterns) if enabled else (text, [])
49
+ else:
50
+ text, redactions = sanitize_for_model(text, ws.config.redaction)
51
+ if redactions:
52
+ text += "\nredaction: applied [" + ", ".join(redactions) + "]"
53
+ fallback = f"ctx get {handle}" if handle else None
54
+ return bounded(text, budget_tokens, continuation, truncation_continuation=fallback)
55
+
56
+
57
+ #: Bytes read either side of a returned range so a secret crossing its edge
58
+ #: is judged whole: the regex context (as bytes, 4 per char at most) after,
59
+ #: and the private-key look-behind before.
60
+ def _edge_context_bytes() -> tuple[int, int]:
61
+ from ctx.textutil import PEM_LOOKBEHIND_CHARS, REDACTION_CONTEXT_CHARS, TOKEN_RUN_SCAN_CHARS
62
+
63
+ before = 4 * max(REDACTION_CONTEXT_CHARS, PEM_LOOKBEHIND_CHARS, TOKEN_RUN_SCAN_CHARS)
64
+ after = 4 * max(REDACTION_CONTEXT_CHARS, TOKEN_RUN_SCAN_CHARS)
65
+ return before, after
66
+
67
+
68
+ def edge_masked_bytes(read, start: int, end: int, total: int, policy, *, exact: bool = False) -> str:
69
+ """Bytes ``[start, end)`` (0-based) of an artifact, decoded, with every
70
+ secret that CROSSES the range's edges blanked at the same width.
71
+
72
+ Every range ctx returns -- ``--bytes``, ``--lines``, ``--records``,
73
+ ``--span``, and the continuation windows ctx prints for them -- has
74
+ edges somebody chose, often ctx itself, and a secret cut by an edge is
75
+ recognized by the emission pass on neither side: the head of a token in
76
+ one answer and its tail in the next reassemble it. So the range is
77
+ judged with a bounded amount of the artifact around it
78
+ (:func:`_edge_context_bytes`) and the crossing part is blanked with
79
+ ``*`` -- one per byte, newlines kept -- so the answer's declared width,
80
+ byte count and line count do not move and continuations still tile the
81
+ artifact. Secrets wholly inside are left to the emission pass.
82
+
83
+ ``read(a, b)`` returns bytes ``[a, b)``; ``exact`` decodes with the
84
+ byte-exact error handler (``--bytes``), else with replacement.
85
+ """
86
+ from ctx.textutil import decode_exact, edge_masked
87
+
88
+ before, after = _edge_context_bytes()
89
+ lo, hi = max(0, start - before), min(total, end + after)
90
+ raw = read(lo, hi)
91
+ dec = decode_exact if exact else (lambda b: b.decode("utf-8", "replace"))
92
+ pre, mid, post = dec(raw[: start - lo]), dec(raw[start - lo: end - lo]), dec(raw[end - lo:])
93
+ return edge_masked(pre, mid, post, policy)
94
+
95
+
96
+ def blob_reader(store: Store, blob_hash: str):
97
+ """``read(a, b)`` over a stored blob by seek (bounded memory)."""
98
+ def read(a: int, b: int) -> bytes:
99
+ return _read_bytes_range(store, blob_hash, a + 1, b)
100
+ return read
101
+
102
+
103
+ def _parse(ref_text: str) -> Ref:
104
+ return parse_ref(ref_text)
105
+
106
+
107
+ def _peek_blob(store: Store, blob_hash: str, n: int = 8192) -> bytes:
108
+ """Read only the first ``n`` bytes of a blob (default: the same 8 KiB
109
+ binary-sniff window used everywhere else in this package).
110
+
111
+ Perf/memory (task 3, "bounded memory on huge blobs"): a blob that turns
112
+ out to be binary must not be fully materialized into a Python ``bytes``
113
+ object just to be rejected. Callers that need the binary verdict before
114
+ deciding whether to do a full ``store.get_blob`` read use this instead.
115
+ """
116
+ from ctx.store import MIN_ID_DISPLAY, UnknownIdError
117
+
118
+ resolved = store.resolve_id(blob_hash, kinds=("blob",))
119
+ try:
120
+ with store.blob_path(resolved).open("rb") as fh:
121
+ return fh.read(n)
122
+ except FileNotFoundError:
123
+ # Parity with Store.get_blob's own not-found translation.
124
+ raise UnknownIdError(f"blob:{resolved[:MIN_ID_DISPLAY]} not found") from None
125
+
126
+
127
+ def _read_bytes_range(store: Store, blob_hash: str, a: int, b: int) -> bytes:
128
+ """Byte range [a, b] (1-indexed, inclusive) without loading the whole
129
+ blob into memory — mirrors ``data[a - 1 : b]`` slicing semantics
130
+ exactly (short reads near EOF silently return fewer bytes, never an
131
+ error), just backed by a seek instead of a full read.
132
+
133
+ Perf/memory (task 3): the ``--bytes`` selector is, by construction, a
134
+ request for a small bounded slice; loading a 50 MiB blob to return 40
135
+ requested bytes was the unbounded-memory gap this closes.
136
+ """
137
+ resolved = store.resolve_id(blob_hash, kinds=("blob",))
138
+ path = store.blob_path(resolved)
139
+ start = max(0, a - 1)
140
+ length = b - start
141
+ if length <= 0:
142
+ return b""
143
+ with path.open("rb") as fh:
144
+ fh.seek(start)
145
+ return fh.read(length)
146
+
147
+
148
+ def _route_workspace(store: Store, ws: Workspace, ref: Ref) -> tuple[Store, Workspace]:
149
+ """Resolve a ws:<alias>/ reference to its target workspace and store.
150
+
151
+ A reference carrying an alias must never silently execute against the
152
+ current workspace (wrong-repository evidence). Unknown aliases are
153
+ rejected with the fix, not guessed (SPEC §5.1, §15).
154
+ """
155
+ if ref.workspace_alias is None:
156
+ return store, ws
157
+ from pathlib import Path as _Path
158
+
159
+ from ctx.workspace import resolve_workspace
160
+
161
+ path = ws.config.aliases.get(ref.workspace_alias)
162
+ if path is None:
163
+ known = ", ".join(sorted(ws.config.aliases)) or "none configured"
164
+ raise RetrievalError(
165
+ f"unknown workspace alias {ref.workspace_alias!r} (known: {known}); "
166
+ "define it under [aliases] in ctx.toml or pass --workspace"
167
+ )
168
+ target_path = _Path(path)
169
+ if not target_path.is_absolute():
170
+ target_path = ws.root / target_path
171
+ target = resolve_workspace(str(target_path))
172
+ return Store(target.workspace_id), target
173
+
174
+
175
+ # The span grammar itself lives in ``ctx.anchors`` — pure, with no retrieval
176
+ # imports — so an emission site can mint and parse an anchored address without
177
+ # pulling this package onto the hook's hot import path. It keeps the hoisted
178
+ # module-level compile the perf pass put here: ``re.match`` on a repeated
179
+ # literal is memoized by the stdlib's internal cache, but that cache is shared
180
+ # and gets evicted by the arbitrary user-supplied search patterns compiled
181
+ # elsewhere in this package (``ctx.retrieval.search``), so only an explicit
182
+ # module-level compile never pays for that churn.
183
+ def _span_anchored(spec: str) -> tuple[int, int, str | None]:
184
+ """``A:B`` or ``A:B@anchor`` — the grammar for a *line* selector.
185
+
186
+ The anchor is the content the caller believes is at those lines (see
187
+ ``ctx.anchors``). Only line selectors carry one, because only they address
188
+ a moving target: ``--bytes`` and ``--records`` are offsets into an
189
+ immutable stream, and an anchor there would be a promise about nothing.
190
+ """
191
+ from ctx.anchors import parse_span
192
+
193
+ try:
194
+ return parse_span(spec)
195
+ except ValueError as e:
196
+ raise RetrievalError(str(e)) from None
197
+
198
+
199
+ def _span(spec: str) -> tuple[int, int]:
200
+ """``A:B`` for the selectors that cannot be anchored.
201
+
202
+ Rejects the anchored form rather than dropping the anchor: silently
203
+ ignoring it would accept an address that *looks* verified and is not,
204
+ which is the exact failure anchors exist to remove.
205
+ """
206
+ a, b, span_anchor = _span_anchored(spec)
207
+ if span_anchor is not None:
208
+ raise RetrievalError(
209
+ f"invalid span {spec!r}: only --lines takes a content anchor "
210
+ "(--bytes/--records address an immutable stream)"
211
+ )
212
+ return a, b