@alexgreensh/token-optimizer 5.13.57 → 5.13.59

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 (29) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +16 -16
  4. package/hooks/python-launcher.sh +10 -0
  5. package/hooks/stop_runner.py +27 -4
  6. package/hooks/windows-launcher.py +57 -3
  7. package/package.json +1 -1
  8. package/skills/fleet-auditor/scripts/shared.py +29 -1
  9. package/skills/token-optimizer/pricing/prices.json +13 -1
  10. package/skills/token-optimizer/scripts/codex_doctor.py +78 -1
  11. package/skills/token-optimizer/scripts/codex_install.py +379 -41
  12. package/skills/token-optimizer/scripts/codex_session.py +38 -8
  13. package/skills/token-optimizer/scripts/copilot_doctor.py +129 -6
  14. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +62 -14
  15. package/skills/token-optimizer/scripts/copilot_install.py +56 -4
  16. package/skills/token-optimizer/scripts/detectors/cache_instability.py +18 -4
  17. package/skills/token-optimizer/scripts/deterministic_candidates.py +55 -15
  18. package/skills/token-optimizer/scripts/devin_source.py +1 -1
  19. package/skills/token-optimizer/scripts/hermes_doctor.py +177 -1
  20. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +190 -0
  21. package/skills/token-optimizer/scripts/hermes_install.py +43 -0
  22. package/skills/token-optimizer/scripts/hermes_session.py +133 -0
  23. package/skills/token-optimizer/scripts/hermes_state.py +58 -0
  24. package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
  25. package/skills/token-optimizer/scripts/measure.py +1302 -319
  26. package/skills/token-optimizer/scripts/plugin_env.py +18 -0
  27. package/skills/token-optimizer/scripts/recovery_output.py +15 -2
  28. package/skills/token-optimizer/scripts/refetch_fingerprint.py +36 -1
  29. package/skills/token-optimizer/scripts/runtime_env.py +5 -1
@@ -83,35 +83,209 @@ def _cmd_quote(token: str) -> str:
83
83
  return quoted if quoted.startswith('"') else f'"{quoted}"'
84
84
 
85
85
 
86
- def _windows_launcher_command(root: Path, script: str, args, extra_env: dict) -> str:
86
+ # Characters a Windows path may carry and still parse the same in cmd.exe,
87
+ # Windows PowerShell 5.1 and PowerShell 7 when written as a bare first token.
88
+ _SHELL_NEUTRAL_EXE_RE = re.compile(r"^[A-Za-z0-9_.:\\/+~-]+$")
89
+
90
+
91
+ def _short_path(path: str) -> str | None:
92
+ """Windows 8.3 short form of ``path``, or None when there is none."""
93
+ if sys.platform != "win32":
94
+ return None
95
+ try:
96
+ import ctypes
97
+
98
+ buf = ctypes.create_unicode_buffer(32768)
99
+ n = ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf))
100
+ if 0 < n < len(buf) and os.path.exists(buf.value):
101
+ return buf.value
102
+ except (AttributeError, ImportError, OSError, ValueError):
103
+ pass
104
+ return None
105
+
106
+
107
+ def _shell_neutral_exe(path: str) -> str | None:
108
+ """Return ``path`` as a bare token every Codex Windows hook shell parses
109
+ identically, or None when no such spelling exists.
110
+
111
+ Codex runs a command hook through the session shell: PowerShell
112
+ (``powershell -NoProfile -Command <cmd>``, preferring pwsh) or, when no
113
+ session shell is known, ``%COMSPEC% /C``. A quoted first token needs ``&``
114
+ in PowerShell and is mangled by cmd's /C quote stripping; a ``set X=Y &&``
115
+ prefix is not PowerShell 5.1 syntax at all (issue #278). A bare first token
116
+ works in both, so a path that needs quoting goes through its 8.3 short name.
117
+ """
118
+ if _SHELL_NEUTRAL_EXE_RE.match(path):
119
+ return path
120
+ short = _short_path(path)
121
+ if short and _SHELL_NEUTRAL_EXE_RE.match(short):
122
+ return short
123
+ return None
124
+
125
+
126
+ # PowerShell also treats the typographic quotes (U+2018..U+201E) as quote
127
+ # characters, so a path holding one would end the double-quoted token early.
128
+ _SHELL_UNSAFE_ARG_CHARS = '"$`%!\r\n\x00\u2018\u2019\u201a\u201b\u201c\u201d\u201e\u201f'
129
+
130
+
131
+ def _shell_neutral_arg(token: str) -> str | None:
132
+ """Double-quote ``token`` so cmd.exe and PowerShell pass it verbatim.
133
+
134
+ Returns None for a token neither shell takes literally inside double
135
+ quotes: ``$`` and the backtick expand in PowerShell, ``%`` and ``!`` can
136
+ expand in cmd, and a literal quote, newline or trailing backslash breaks
137
+ the MSVCRT argv split. PowerShell's typographic quotes are rejected too.
138
+ (A literal ``%`` was already a documented limit.)
139
+ """
140
+ if any(ch in token for ch in _SHELL_UNSAFE_ARG_CHARS) or token.endswith("\\"):
141
+ return None
142
+ return f'"{token}"'
143
+
144
+
145
+ def _neutral_child_arg(parent: str, leaf: str) -> str | None:
146
+ """``parent\\leaf`` as a shell-neutral quoted argument, going through the
147
+ 8.3 short name of ``parent`` when the long one holds a character that
148
+ expands in PowerShell or cmd (``$``, backtick, ``%``, ``!``). Only the parent
149
+ is shortened, so ``leaf`` (a version dir or the launcher file name) keeps
150
+ the exact name the launcher matches on."""
151
+ sep = "/" if "/" in parent and "\\" not in parent else "\\"
152
+ direct = _shell_neutral_arg(parent.rstrip("\\/") + sep + leaf)
153
+ if direct:
154
+ return direct
155
+ short = _short_path(parent)
156
+ if short:
157
+ return _shell_neutral_arg(short.rstrip("\\/") + "\\" + leaf)
158
+ return None
159
+
160
+
161
+ # Base folders the launcher bootstrap may start from. Windows sets the first
162
+ # three for every process; CODEX_HOME only when the user moved Codex's home.
163
+ _BOOTSTRAP_BASES = ("USERPROFILE", "LOCALAPPDATA", "APPDATA", "CODEX_HOME")
164
+ # A folder name inside the bootstrap: anything both shells keep literal inside
165
+ # double quotes that is also legal inside a Python '...' literal.
166
+ _BOOTSTRAP_UNSAFE_CHARS = _SHELL_UNSAFE_ARG_CHARS + "'\\/"
167
+
168
+
169
+ def _launcher_bootstrap(launcher: str) -> str | None:
170
+ """Readable ``python -c`` code that runs ``launcher`` from an environment
171
+ folder, for a launcher path no shell-neutral spelling exists for.
172
+
173
+ A Windows user name holding ``$`` or ``%`` puts that character in every
174
+ per-user path, its 8.3 short name included (both are legal 8.3 characters),
175
+ and PowerShell expands ``$`` inside double quotes while cmd.exe expands
176
+ ``%``. Python reads the folder from the environment instead, so the shell
177
+ never sees the character. Plain source, no encoded payload (issue #183).
178
+ Returns None when no base folder fits.
179
+ """
180
+ import ntpath
181
+
182
+ target = ntpath.normpath(launcher)
183
+ for var in _BOOTSTRAP_BASES:
184
+ base = os.environ.get(var)
185
+ if not base:
186
+ continue
187
+ base_norm = ntpath.normpath(base).rstrip("\\")
188
+ if not ntpath.normcase(target).startswith(ntpath.normcase(base_norm) + "\\"):
189
+ continue
190
+ rel = [c for c in target[len(base_norm) + 1:].split("\\") if c]
191
+ if not rel or any(c in (".", "..") or any(ch in c for ch in _BOOTSTRAP_UNSAFE_CHARS)
192
+ for c in rel):
193
+ continue
194
+ parts = ",".join(f"'{c}'" for c in rel)
195
+ return (f"import os,runpy;runpy.run_path(os.path.join(os.environ['{var}'],{parts}),"
196
+ f"run_name='__main__')")
197
+ return None
198
+
199
+
200
+ def _neutral_launcher_command(exe_path: str, launcher_path: str, baked_root: str,
201
+ env_pairs, script: str, args,
202
+ *, allow_bootstrap: bool = True) -> str | None:
203
+ """The shell-neutral launcher command (see _windows_launcher_command), or
204
+ None when no spelling runs the same in PowerShell 5.1, PowerShell 7 and
205
+ cmd.exe.
206
+
207
+ Paths are tried literally, then through the 8.3 short name of their
208
+ folder. A launcher path neither form can carry is reached through
209
+ ``_launcher_bootstrap``; its --baked-root is then written relative to the
210
+ launcher's own folder (the version dir name is always plain), which the
211
+ launcher resolves. That needs the launcher from this release, so only
212
+ install(), which copies it first, passes ``allow_bootstrap``.
213
+ """
214
+ import ntpath
215
+
216
+ exe = _shell_neutral_exe(exe_path)
217
+ if exe is None:
218
+ return None
219
+ launcher_parent, launcher_name = ntpath.split(launcher_path)
220
+ baked_parent, baked_leaf = ntpath.split(baked_root.rstrip("\\/"))
221
+ launcher = _neutral_child_arg(launcher_parent, launcher_name)
222
+ baked = _neutral_child_arg(baked_parent, baked_leaf)
223
+ head: list[str] | None = None
224
+ if launcher and baked:
225
+ head = [launcher, "--baked-root", baked]
226
+ elif allow_bootstrap and _SEMVER_DIR_RE.match(baked_leaf):
227
+ same_parent = ntpath.normcase(ntpath.normpath(launcher_parent)) == \
228
+ ntpath.normcase(ntpath.normpath(baked_parent))
229
+ code = _launcher_bootstrap(launcher_path) if same_parent else None
230
+ code_arg = _shell_neutral_arg(code) if code else None
231
+ if code_arg:
232
+ head = ["-c", code_arg, "--baked-root", f'"{baked_leaf}"']
233
+ if head is None:
234
+ return None
235
+ env_parts = [_shell_neutral_arg(pair) for pair in env_pairs]
236
+ tail = [_shell_neutral_arg(script), *(_shell_neutral_arg(a) for a in args),
237
+ _shell_neutral_arg(_LAUNCHER_MARKER)]
238
+ if not all(env_parts) or not all(tail):
239
+ return None
240
+ parts = [exe, *head]
241
+ for env_part in env_parts:
242
+ parts += ["--env", env_part]
243
+ parts += ["--", *tail]
244
+ return " ".join(parts)
245
+
246
+
247
+ def _windows_launcher_command(root: Path, script: str, args, extra_env: dict,
248
+ *, silent: bool = False) -> str:
87
249
  """Build the baked Windows hook command for a versioned marketplace root.
88
250
 
89
251
  The command invokes the readable launcher file that install() copies to
90
252
  the STABLE parent of the version dirs (.../token-optimizer/
91
253
  windows-launcher.py, which survives the marketplace swapping
92
- .../token-optimizer/<X.Y.Z>/ on upgrade) by quoted path -- issue #183:
93
- the retired base64 `python -c` exec-bootstrap tripped
94
- generic-loader antivirus signatures on the literal encoded-exec
95
- string. Every value token is force-quoted (see _cmd_quote): the runner
96
- path and --baked-root can contain cmd.exe metacharacters (& | < > ^)
97
- with no surrounding space, which list2cmdline alone leaves bare and cmd
98
- then parses as command separators -- the base64 form hid them inside the
99
- payload, so this restores that safety. Quoting keeps the /C single-parse
100
- problem (issue #180) solved with no expansion form. The launcher resolves
101
- the newest semver sibling of the baked root at runtime; --baked-root is
102
- the fail-open fallback only. The trailing marker keeps the command
103
- recognizable to ownership checks; the launcher strips it before
104
- dispatching, so the runner's sys.argv stays exactly [run.py, script,
105
- *args].
254
+ .../token-optimizer/<X.Y.Z>/ on upgrade) -- issue #183: the retired base64
255
+ `python -c` exec-bootstrap tripped generic-loader antivirus signatures on
256
+ the literal encoded-exec string.
257
+
258
+ Shell contract (issue #278): Codex hands the command to PowerShell on
259
+ native Windows (``-Command``), or to ``%COMSPEC% /C`` when it has no session
260
+ shell. The same text must run in both, so it is ``<python> "<arg>" ...``:
261
+ a bare first token, double-quoted arguments, no ``set ... &&`` prefix, no
262
+ ``>NUL`` redirect (``silent=True`` adds a TOKEN_OPTIMIZER_HOOK_SILENT env
263
+ pair; the launcher then sends stdout/stderr to the null device in-process).
264
+ The launcher sets TOKEN_OPTIMIZER_RUNTIME itself. A path holding a
265
+ character one shell expands (``$``, backtick, ``%``, ``!``) goes through
266
+ its 8.3 short name or, for the launcher, a plain ``python -c`` bootstrap
267
+ that reads the folder from the environment (see _neutral_launcher_command).
268
+ Only when even that fails (the interpreter itself sits at such a path with
269
+ no usable short name) is the cmd.exe-only form of issue #276 returned, so
270
+ the hook still works under cmd; the doctor then says what to change.
271
+ """
272
+ env = dict(extra_env)
273
+ if silent:
274
+ env["TOKEN_OPTIMIZER_HOOK_SILENT"] = "1"
275
+ command = _neutral_launcher_command(
276
+ sys.executable, str(root.parent / _LAUNCHER_FILENAME), str(root),
277
+ [f"{k}={v}" for k, v in env.items()], script, args)
278
+ if command:
279
+ return command
280
+ return _cmd_only_launcher_command(root, script, args, extra_env, silent=silent)
281
+
282
+
283
+ def _cmd_only_launcher_command(root: Path, script: str, args, extra_env: dict,
284
+ *, silent: bool = False) -> str:
285
+ """cmd.exe-only launcher command (issue #276 shape): an unquoted ``set``
286
+ builtin first so cmd's /C quote stripping keeps the quoted paths intact.
287
+ PowerShell cannot run it; used only when no shell-neutral spelling exists.
106
288
  """
107
- # The command must NOT start with a double quote. Codex hands it to
108
- # cmd.exe as a raw /C string; when that string's first character is a
109
- # quote, cmd strips the first and the LAST quote on the line (/S rules),
110
- # which unpairs every quoted path ("The filename, directory name, or
111
- # volume label syntax is incorrect", issue #276). A leading builtin keeps
112
- # the line intact whether or not the host wraps it in an outer pair of
113
- # quotes. The launcher sets this variable too; the prefix is only there
114
- # to give cmd an unquoted first token.
115
289
  parts = [
116
290
  _WIN_UNQUOTED_PREFIX,
117
291
  _cmd_quote(sys.executable),
@@ -123,7 +297,24 @@ def _windows_launcher_command(root: Path, script: str, args, extra_env: dict) ->
123
297
  parts += ["--env", _cmd_quote(f"{key}={value}")]
124
298
  parts += ["--", _cmd_quote(script), *(_cmd_quote(a) for a in args),
125
299
  _cmd_quote(_LAUNCHER_MARKER)]
126
- return " ".join(parts)
300
+ command = " ".join(parts)
301
+ return f"{command} >NUL 2>&1" if silent else command
302
+
303
+
304
+ _SET_PREFIX_RE = re.compile(r"^\s*set\s", re.IGNORECASE)
305
+
306
+
307
+ def is_shell_neutral_command(command: str) -> bool:
308
+ """True when one of our Windows launcher commands runs under both
309
+ PowerShell and cmd.exe (see _windows_launcher_command)."""
310
+ if _LAUNCHER_MARKER not in command or _LAUNCHER_B64_RE.search(command):
311
+ return False
312
+ if command.startswith(('"', "'", "&", "@")) or _SET_PREFIX_RE.match(command):
313
+ return False
314
+ # Only unquoted tokens count: a folder such as "C:\Users\Tom && Jerry"
315
+ # inside a quoted path is not a cmd.exe operator.
316
+ bare = {tok for tok in _CMD_TOKEN_RE.findall(command) if not tok.startswith('"')}
317
+ return not (bare & {"&&", ">NUL", "2>&1"})
127
318
 
128
319
 
129
320
  def decode_launcher_command(command: str) -> str | None:
@@ -174,13 +365,23 @@ def _hook_command(script: str, *args: str, redirect_quiet: bool = False,
174
365
  # already launching, which removes the nested-quoting and
175
366
  # console-codepage problems entirely. Audit by reading the file;
176
367
  # legacy base64 commands still decode via --decode-launcher.
177
- command = _windows_launcher_command(root, script, args, extra_env)
178
- else:
179
- prefix = f'set "TOKEN_OPTIMIZER_RUNTIME=codex" && {_win_env}'
180
- argv = [sys.executable, str(root / "hooks" / "run.py"), script, *args]
368
+ return _windows_launcher_command(
369
+ root, script, args, extra_env, silent=redirect_quiet)
370
+ # Development checkout (non-semver root): run the checkout's own
371
+ # launcher pinned to this root. A non-semver --baked-root is never
372
+ # swapped for a sibling, and the same shell-neutral form runs under
373
+ # PowerShell, where the old ``set ... &&`` form exited 1 (issue #278).
374
+ env = dict(extra_env)
375
+ if redirect_quiet:
376
+ env["TOKEN_OPTIMIZER_HOOK_SILENT"] = "1"
377
+ neutral = _neutral_launcher_command(
378
+ sys.executable, str(root / "hooks" / _LAUNCHER_FILENAME), str(root),
379
+ [f"{k}={v}" for k, v in env.items()], script, args, allow_bootstrap=False)
380
+ if neutral:
381
+ return neutral
382
+ prefix = f'set "TOKEN_OPTIMIZER_RUNTIME=codex" && {_win_env}'
383
+ argv = [sys.executable, str(root / "hooks" / "run.py"), script, *args]
181
384
  redirect = " >NUL 2>&1" if redirect_quiet else ""
182
- if _SEMVER_DIR_RE.match(root.name):
183
- return f"{command}{redirect}"
184
385
  return f"{prefix}{subprocess.list2cmdline(argv)}{redirect}"
185
386
 
186
387
  command_args = " ".join(shlex.quote(arg) for arg in (script, *args))
@@ -508,11 +709,13 @@ def _normalize_baked_root(match: "re.Match[str]") -> str:
508
709
  quoted = value is not None
509
710
  if not quoted:
510
711
  value = match.group("bare")
511
- leaf = re.search(r"^(.*[/\\])\d+\.\d+\.\d+$", value)
712
+ # The prefix is optional: the bootstrap form bakes just the version name.
713
+ leaf = re.search(r"^(.*[/\\])?\d+\.\d+\.\d+$", value)
512
714
  if leaf is None:
513
715
  return match.group(0)
514
- normalized = f"--baked-root {leaf.group(1)}{_SIGNATURE_VERSION}"
515
- return f'--baked-root "{leaf.group(1)}{_SIGNATURE_VERSION}"' if quoted else normalized
716
+ prefix = leaf.group(1) or ""
717
+ normalized = f"--baked-root {prefix}{_SIGNATURE_VERSION}"
718
+ return f'--baked-root "{prefix}{_SIGNATURE_VERSION}"' if quoted else normalized
516
719
 
517
720
 
518
721
  def _launcher_signature(command):
@@ -600,8 +803,12 @@ def _install_windows_launcher(root: Path) -> str:
600
803
  path. Idempotent (no rewrite when already current) and atomic
601
804
  (unique same-directory temp + replace, always cleaned up), so a
602
805
  concurrent hook run never reads a half-written launcher."""
806
+ return _copy_launcher_to(_windows_launcher_install_path(root))
807
+
808
+
809
+ def _copy_launcher_to(target: Path) -> str:
810
+ """Write this release's launcher to `target` (see _install_windows_launcher)."""
603
811
  source = _repo_root() / "hooks" / _LAUNCHER_FILENAME
604
- target = _windows_launcher_install_path(root)
605
812
  try:
606
813
  content = source.read_bytes()
607
814
  except OSError as exc:
@@ -691,14 +898,116 @@ def install(
691
898
  return path, "installed", details
692
899
 
693
900
 
901
+ _CMD_TOKEN_RE = re.compile(r'"[^"]*"|\S+')
902
+
903
+
904
+ def parse_cmd_only_launcher_command(command: str) -> dict | None:
905
+ """Split one of our cmd.exe-only launcher commands (issue #276 shape or the
906
+ older quoted-first-token shape) into its parts, or None when it does not
907
+ fit that exact generated shape.
908
+
909
+ Shape: optional ``set "TOKEN_OPTIMIZER_RUNTIME=codex" &&`` prefix, quoted
910
+ interpreter, quoted launcher, ``--baked-root`` and its value, ``--env``
911
+ pairs, ``--``, quoted script and args, marker, optional ``>NUL 2>&1``.
912
+ Anything else is left alone rather than guessed at.
913
+ """
914
+ if _LAUNCHER_MARKER not in command or _LAUNCHER_B64_RE.search(command):
915
+ return None
916
+ tokens = _CMD_TOKEN_RE.findall(command.strip())
917
+ silent = False
918
+ if tokens[-2:] == [">NUL", "2>&1"]:
919
+ silent = True
920
+ tokens = tokens[:-2]
921
+ if tokens[:2] == ['set', '"TOKEN_OPTIMIZER_RUNTIME=codex"'] and tokens[2:3] == ["&&"]:
922
+ tokens = tokens[3:]
923
+ if len(tokens) < 6 or tokens[-1] != f'"{_LAUNCHER_MARKER}"':
924
+ return None
925
+ if tokens[0].count('"') not in (0, 2):
926
+ return None
927
+
928
+ def value(tok: str) -> str | None:
929
+ if len(tok) >= 2 and tok.startswith('"') and tok.endswith('"'):
930
+ return tok[1:-1]
931
+ return None
932
+
933
+ exe = tokens[0].strip('"')
934
+ launcher = value(tokens[1])
935
+ if launcher is None or tokens[2] != "--baked-root":
936
+ return None
937
+ baked = value(tokens[3])
938
+ if baked is None:
939
+ return None
940
+ env: list[str] = []
941
+ i = 4
942
+ while i + 1 < len(tokens) and tokens[i] == "--env":
943
+ pair = value(tokens[i + 1])
944
+ if pair is None:
945
+ return None
946
+ env.append(pair)
947
+ i += 2
948
+ if i >= len(tokens) or tokens[i] != "--":
949
+ return None
950
+ rest = [value(t) for t in tokens[i + 1:-1]]
951
+ if not rest or any(v is None for v in rest):
952
+ return None
953
+ return {"exe": exe, "launcher": launcher, "baked_root": baked, "env": env,
954
+ "script": rest[0], "args": rest[1:], "silent": silent}
955
+
956
+
957
+ def neutralize_launcher_command(command: str) -> str | None:
958
+ """Rewrite one of our cmd.exe-only launcher commands into the shell-neutral
959
+ form of issue #278, or return None when it is already neutral, not ours, or
960
+ cannot be written that way (the caller then falls back to the #276 repair).
961
+
962
+ Pure text transform (see parse_cmd_only_launcher_command). It never uses
963
+ the ``python -c`` bootstrap: that form needs the launcher from this
964
+ release, which only a full codex-install puts in place.
965
+ """
966
+ if is_shell_neutral_command(command):
967
+ return None
968
+ parts = parse_cmd_only_launcher_command(command)
969
+ if parts is None:
970
+ return None
971
+ env = list(parts["env"])
972
+ if parts["silent"]:
973
+ env.append("TOKEN_OPTIMIZER_HOOK_SILENT=1")
974
+ return _neutral_launcher_command(
975
+ parts["exe"], parts["launcher"], parts["baked_root"], env,
976
+ parts["script"], parts["args"], allow_bootstrap=False)
977
+
978
+
979
+ def explain_cmd_only_command(command: str) -> str | None:
980
+ """Plain-English next step for a launcher command that could only be
981
+ written in the cmd.exe-only form, or None when it is not one of ours."""
982
+ parts = parse_cmd_only_launcher_command(command)
983
+ if parts is None:
984
+ return None
985
+ if _shell_neutral_exe(parts["exe"]) is None:
986
+ return (f"Python is installed in a folder PowerShell cannot start from a hook "
987
+ f"({parts['exe']}). Install Python in a plain folder such as C:\\Python313 "
988
+ "(no spaces and none of $ ` % !), run that Python's measure.py codex-install "
989
+ "again, then restart Codex")
990
+ allow = _neutral_launcher_command(
991
+ parts["exe"], parts["launcher"], parts["baked_root"], parts["env"],
992
+ parts["script"], parts["args"], allow_bootstrap=True)
993
+ if allow:
994
+ return "run measure.py codex-install again, then restart Codex"
995
+ return (f"the Token Optimizer plugin folder ({parts['launcher']}) has a character "
996
+ "PowerShell or cmd.exe changes ($ ` % !). Set CODEX_HOME to a plain folder such as "
997
+ "C:\\codex, reinstall the plugin there, run measure.py codex-install, then restart Codex")
998
+
999
+
694
1000
  def heal_quoted_launcher_commands(paths=None) -> int:
695
- """Repair Windows hook commands that start with a double quote.
1001
+ """Repair Windows hook commands that PowerShell or cmd.exe cannot run.
696
1002
 
697
1003
  Versions before 5.13.57 saved launcher commands that open with the quoted
698
- python.exe path. cmd.exe strips that first quote and the last one, so the
699
- hook fails before Python starts and can never repair itself (issue #276).
700
- This rewrites only our own launcher commands, only that one way, and
701
- returns how many it fixed. Never raises.
1004
+ python.exe path, which cmd.exe mangles (issue #276). 5.13.57 added a cmd-only
1005
+ ``set ... &&`` prefix, which PowerShell -- the shell Codex normally runs
1006
+ hooks in -- cannot parse (issue #278). Either way the hook fails before
1007
+ Python starts and can never repair itself, so any Token Optimizer run
1008
+ rewrites our own launcher commands into the shell-neutral form (or, if no
1009
+ such spelling exists, the cmd-only repair) and returns how many it
1010
+ fixed. Never raises.
702
1011
  """
703
1012
  if paths is None:
704
1013
  paths = []
@@ -708,6 +1017,29 @@ def heal_quoted_launcher_commands(paths=None) -> int:
708
1017
  pass
709
1018
  paths.append(Path.cwd() / ".codex" / "hooks.json")
710
1019
  fixed = 0
1020
+ refreshed: dict[str, bool] = {}
1021
+
1022
+ def launcher_ready(command: str) -> bool:
1023
+ # A rewritten command passes --env TOKEN_OPTIMIZER_HOOK_SILENT=1 where it
1024
+ # used to redirect to NUL. Launchers before 5.13.59 ignore that flag, so
1025
+ # the launcher the command names is refreshed first; if that copy fails
1026
+ # the old command stays (still quiet under cmd.exe).
1027
+ parts = parse_cmd_only_launcher_command(command)
1028
+ if parts is None:
1029
+ return False
1030
+ target = parts["launcher"]
1031
+ if target not in refreshed:
1032
+ ok = False
1033
+ try:
1034
+ path_obj = Path(target)
1035
+ if path_obj.name == _LAUNCHER_FILENAME and path_obj.parent.is_dir():
1036
+ _copy_launcher_to(path_obj)
1037
+ ok = True
1038
+ except Exception:
1039
+ ok = False
1040
+ refreshed[target] = ok
1041
+ return refreshed[target]
1042
+
711
1043
  for path in paths:
712
1044
  try:
713
1045
  if not path.is_file():
@@ -722,8 +1054,14 @@ def heal_quoted_launcher_commands(paths=None) -> int:
722
1054
  continue
723
1055
  for handler in group.get("hooks", []):
724
1056
  command = handler.get("command") if isinstance(handler, dict) else None
725
- if (isinstance(command, str) and command.startswith('"')
726
- and _LAUNCHER_MARKER in command):
1057
+ if not isinstance(command, str):
1058
+ continue
1059
+ neutral = neutralize_launcher_command(command)
1060
+ if (neutral is not None and neutral != command
1061
+ and launcher_ready(command)):
1062
+ handler["command"] = neutral
1063
+ changed += 1
1064
+ elif (command.startswith('"') and _LAUNCHER_MARKER in command):
727
1065
  handler["command"] = f"{_WIN_UNQUOTED_PREFIX} {command}"
728
1066
  changed += 1
729
1067
  if changed:
@@ -202,6 +202,28 @@ _TOPIC_PREFIXES = (
202
202
  )
203
203
 
204
204
 
205
+ # Codex writes these as role=user messages, but nobody typed them: injected
206
+ # repo instructions, environment context and turn markers. They must never
207
+ # become the session topic or the checkpoint's Active Task (#288).
208
+ _INJECTED_USER_PREFIXES = (
209
+ "# AGENTS.md instructions", "<environment_context>", "<user_instructions>",
210
+ "<turn_aborted>", "<user_action>", "<INSTRUCTIONS>",
211
+ )
212
+
213
+
214
+ def _task_user_text(text: str) -> str:
215
+ """User text a human typed, or "" for injected Codex context."""
216
+ text = str(text or "").strip()
217
+ if not text or text.startswith(_INJECTED_USER_PREFIXES):
218
+ return ""
219
+ return text
220
+
221
+
222
+ def _pick_topic(topics: dict[str, str | None]) -> str | None:
223
+ """Prefer the event_msg user_message over its response_item duplicate."""
224
+ return topics.get("user_message") or topics.get("message")
225
+
226
+
205
227
  def _extract_topic(text: str) -> str | None:
206
228
  text = " ".join(text.split())
207
229
  if not text:
@@ -423,7 +445,7 @@ def _parse_session_records(records, incomplete=False, sampled=False):
423
445
  model_usage_breakdown: dict[str, dict[str, int]] = {}
424
446
  version = None
425
447
  slug = None
426
- topic = None
448
+ topics: dict[str, str | None] = {}
427
449
  first_ts = None
428
450
  last_ts = None
429
451
  message_count = 0
@@ -534,7 +556,10 @@ def _parse_session_records(records, incomplete=False, sampled=False):
534
556
  text_chars = payload.get('_optimizer_chars', len(text))
535
557
  role = payload.get("role")
536
558
  if payload_type == "user_message" or role == "user":
537
- topic = topic or _extract_topic(text)
559
+ if not topics.get(payload_type):
560
+ task = _task_user_text(text)
561
+ if task:
562
+ topics[payload_type] = _extract_topic(task)
538
563
  input_text_chars += text_chars
539
564
  elif payload_type == "agent_message" or role == "assistant":
540
565
  output_text_chars += text_chars
@@ -610,7 +635,7 @@ def _parse_session_records(records, incomplete=False, sampled=False):
610
635
  "scan_mode": "recent_tail" if incomplete else "full",
611
636
  "version": version,
612
637
  "slug": slug,
613
- "topic": topic,
638
+ "topic": _pick_topic(topics),
614
639
  "duration_minutes": duration_minutes,
615
640
  "wall_duration_minutes": wall_duration_minutes,
616
641
  "duration_source": duration_source,
@@ -712,7 +737,7 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
712
737
  compaction_ratios: list[dict[str, Any]] = []
713
738
  last_usage: dict[str, int] | None = None
714
739
  current_model = _UNKNOWN_MODEL
715
- topic = None
740
+ topics: dict[str, str | None] = {}
716
741
  idx = 0
717
742
  prev_was_compacted = False
718
743
  last_turn_context: int | None = None
@@ -782,8 +807,10 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
782
807
  elif payload_type in {"user_message", "message", "agent_message"}:
783
808
  text = _extract_text(payload)
784
809
  role = "assistant" if payload_type == "agent_message" else str(payload.get("role") or "user")
785
- if role == "user":
786
- topic = topic or _extract_topic(text)
810
+ if role == "user" and not topics.get(payload_type):
811
+ task = _task_user_text(text)
812
+ if task:
813
+ topics[payload_type] = _extract_topic(task)
787
814
  substantive = len(text.split()) > (20 if role == "assistant" else 10)
788
815
  messages.append((idx, role, len(text), substantive))
789
816
  if re.search(r"\b(chose|decided|because|switched|going with)\b", text, re.IGNORECASE):
@@ -838,7 +865,7 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
838
865
  "context_tokens": last_turn_context or None,
839
866
  "model_context_window": last_usage["model_context_window"] if last_usage else None,
840
867
  "model": current_model if current_model != _UNKNOWN_MODEL else _DEFAULT_MODEL,
841
- "topic": topic,
868
+ "topic": _pick_topic(topics),
842
869
  }
843
870
 
844
871
 
@@ -959,7 +986,10 @@ def extract_session_state(filepath: str | Path, tail_lines: int = 500, max_files
959
986
  if not text:
960
987
  continue
961
988
  if role == "user":
962
- last_user_msg = text
989
+ if _task_user_text(text):
990
+ last_user_msg = text
991
+ else:
992
+ continue # injected context: not a task, not a question
963
993
  elif role == "assistant":
964
994
  last_assistant_msg = text
965
995
  _append_decisions(text, decisions)