@alexgreensh/token-optimizer 5.13.62 → 5.13.64
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/sessionstart_runner.py +25 -4
- package/package.json +1 -1
- package/skills/fleet-auditor/SKILL.md +1 -1
- package/skills/fleet-auditor/scripts/fleet.py +4 -1
- package/skills/fleet-auditor/scripts/shared.py +31 -14
- package/skills/token-coach/SKILL.md +49 -40
- package/skills/token-coach/references/deterministic-stages.md +1 -1
- package/skills/token-coach/references/keepwarm-consent.md +7 -7
- package/skills/token-dashboard/SKILL.md +30 -6
- package/skills/token-optimizer/SKILL.md +42 -44
- package/skills/token-optimizer/assets/dashboard.html +571 -106
- package/skills/token-optimizer/references/agent-prompts.md +4 -1
- package/skills/token-optimizer/references/codex-workflow.md +30 -12
- package/skills/token-optimizer/references/cursor-workflow.md +9 -7
- package/skills/token-optimizer/references/implementation-playbook.md +4 -4
- package/skills/token-optimizer/references/keepwarm-consent.md +7 -7
- package/skills/token-optimizer/references/opencode-workflow.md +4 -2
- package/skills/token-optimizer/references/optimization-checklist.md +9 -9
- package/skills/token-optimizer/references/phase0-setup.md +9 -9
- package/skills/token-optimizer/references/presentation-workflow.md +3 -3
- package/skills/token-optimizer/references/session-continuity.md +1 -1
- package/skills/token-optimizer/references/token-flow-architecture.md +2 -1
- package/skills/token-optimizer/scripts/adapter_hook_command.py +94 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +12 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +4 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +9 -18
- package/skills/token-optimizer/scripts/antigravity_session.py +31 -6
- package/skills/token-optimizer/scripts/archive_result.py +6 -1
- package/skills/token-optimizer/scripts/archive_window.py +274 -0
- package/skills/token-optimizer/scripts/checkpoint_state.py +385 -0
- package/skills/token-optimizer/scripts/codex_install.py +5 -3
- package/skills/token-optimizer/scripts/codex_session.py +149 -1
- package/skills/token-optimizer/scripts/cursor_doctor.py +12 -27
- package/skills/token-optimizer/scripts/cursor_install.py +11 -19
- package/skills/token-optimizer/scripts/devin_source.py +3 -3
- package/skills/token-optimizer/scripts/grok_doctor.py +12 -24
- package/skills/token-optimizer/scripts/grok_install.py +9 -16
- package/skills/token-optimizer/scripts/measure.py +7300 -1642
- package/skills/token-optimizer/scripts/read_cache.py +52 -27
- package/skills/token-optimizer/scripts/recovery_output.py +67 -18
- package/skills/token-optimizer/scripts/refetch_guard.py +9 -3
- package/skills/token-optimizer/scripts/session_activity.py +169 -0
- package/skills/token-optimizer/scripts/session_store.py +127 -9
- package/skills/token-optimizer/scripts/statusline.js +4 -6
|
@@ -53,6 +53,8 @@ _GEMINI_CARD_IDS = (
|
|
|
53
53
|
"gemini-2.5-flash-lite",
|
|
54
54
|
)
|
|
55
55
|
|
|
56
|
+
_GEMINI_SNAPSHOT_SUFFIX = re.compile(r"\d{3}|\d{8}|\d{4}-\d{2}-\d{2}")
|
|
57
|
+
|
|
56
58
|
|
|
57
59
|
def _safe_int(value: Any, default: int = 0) -> int:
|
|
58
60
|
try:
|
|
@@ -82,8 +84,12 @@ def model_id_for_display_name(name: str) -> Optional[str]:
|
|
|
82
84
|
if not s:
|
|
83
85
|
return None
|
|
84
86
|
if s.startswith("gemini-"):
|
|
87
|
+
# A card id, optionally followed by a numeric snapshot suffix (-001,
|
|
88
|
+
# -20260101, -2026-01-01). Any other variant (an unlisted -lite, -image
|
|
89
|
+
# or -live model) has no card of its own and is left unpriced.
|
|
85
90
|
for card_id in _GEMINI_CARD_IDS:
|
|
86
|
-
if s == card_id or s.startswith(card_id + "-")
|
|
91
|
+
if s == card_id or (s.startswith(card_id + "-")
|
|
92
|
+
and _GEMINI_SNAPSHOT_SUFFIX.fullmatch(s[len(card_id) + 1:])):
|
|
87
93
|
return card_id
|
|
88
94
|
return None
|
|
89
95
|
if "claude" in s or "sonnet" in s or "opus" in s or "haiku" in s:
|
|
@@ -292,18 +298,36 @@ def normalize_session(raw: dict) -> Optional[dict]:
|
|
|
292
298
|
not_fully_idle = bool(raw.get("not_fully_idle"))
|
|
293
299
|
end_reason = "killed" if killed else ("not_fully_idle" if not_fully_idle else "")
|
|
294
300
|
|
|
295
|
-
# Per-model usage: single model id for the whole conversation (highest
|
|
296
|
-
# volume was resolved upstream in antigravity_state.model_display_name).
|
|
297
|
-
billable = total_input + total_output
|
|
298
|
-
model_usage = {model: billable} if model not in ("", _UNKNOWN_MODEL) else {}
|
|
299
301
|
model_usage_breakdown = {}
|
|
300
|
-
|
|
302
|
+
complete_generations = all(isinstance(g, dict) and all(k in g for k in (
|
|
303
|
+
"input_tokens", "output_tokens", "cache_read_tokens", "model_display_name")) for g in generations)
|
|
304
|
+
complete_generations = bool(generations) and complete_generations and not _safe_int(raw.get("undecodable_rows")) and all(
|
|
305
|
+
sum(max(0, _safe_int(g.get(k))) for g in generations) == total
|
|
306
|
+
for k, total in (("input_tokens", input_tokens), ("output_tokens", output_tokens),
|
|
307
|
+
("cache_read_tokens", cache_read))
|
|
308
|
+
)
|
|
309
|
+
if complete_generations:
|
|
310
|
+
for g in generations:
|
|
311
|
+
name = str(g.get("model_display_name") or _UNKNOWN_MODEL)
|
|
312
|
+
key = model_id_for_display_name(name) or name
|
|
313
|
+
parts = model_usage_breakdown.setdefault(key, {"fresh_input": 0, "cache_read": 0, "cache_create": 0, "output": 0, "requests": []})
|
|
314
|
+
request = {"fresh_input": max(0, _safe_int(g.get("input_tokens"))),
|
|
315
|
+
"cache_read": max(0, _safe_int(g.get("cache_read_tokens"))),
|
|
316
|
+
"output": max(0, _safe_int(g.get("output_tokens")))}
|
|
317
|
+
for field, value in request.items():
|
|
318
|
+
parts[field] += value
|
|
319
|
+
parts["requests"].append(request)
|
|
320
|
+
elif model not in ("", _UNKNOWN_MODEL):
|
|
301
321
|
model_usage_breakdown[model] = {
|
|
302
322
|
"fresh_input": total_input - total_cache_read,
|
|
303
323
|
"cache_read": total_cache_read,
|
|
304
324
|
"cache_create": 0,
|
|
305
325
|
"output": total_output,
|
|
306
326
|
}
|
|
327
|
+
model_usage = {name: parts["fresh_input"] + parts["cache_create"] + parts["output"]
|
|
328
|
+
for name, parts in model_usage_breakdown.items()}
|
|
329
|
+
if credits is None and any(model_id_for_display_name(name) for name in model_usage):
|
|
330
|
+
cost_source = "antigravity_list_price_estimate"
|
|
307
331
|
|
|
308
332
|
session = _base_canonical(str(conversation_id))
|
|
309
333
|
session.update(
|
|
@@ -326,6 +350,7 @@ def normalize_session(raw: dict) -> Optional[dict]:
|
|
|
326
350
|
"model_id": model_id,
|
|
327
351
|
"model_usage": model_usage,
|
|
328
352
|
"model_usage_breakdown": model_usage_breakdown,
|
|
353
|
+
"generation_details_complete": complete_generations,
|
|
329
354
|
"message_count": user_inputs,
|
|
330
355
|
"api_calls": len(generations),
|
|
331
356
|
"tool_calls": {"total": tool_calls},
|
|
@@ -1658,7 +1658,12 @@ def archive_result(quiet: bool = False) -> None:
|
|
|
1658
1658
|
source_file_path=lineage_source_file[:500] if lineage_source_file else None,
|
|
1659
1659
|
language=lineage_language,
|
|
1660
1660
|
archived_from="PostToolUse",
|
|
1661
|
-
|
|
1661
|
+
# Hand the whole stored response to SessionStore: it bounds
|
|
1662
|
+
# output_text to a head+tail search index (index_truncated=1) so a
|
|
1663
|
+
# few 5MB archives cannot fill the 50MB session DB, while the
|
|
1664
|
+
# sidecar keeps the full redacted body for `expand`.
|
|
1665
|
+
output_text=safe_response,
|
|
1666
|
+
truncated=1 if truncated else 0,
|
|
1662
1667
|
)
|
|
1663
1668
|
except Exception:
|
|
1664
1669
|
pass
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Bounded reads over an archived tool result.
|
|
2
|
+
|
|
3
|
+
``measure.py expand`` returns a whole archived response by default. These
|
|
4
|
+
helpers slice the stored text into a line range, a char range, or
|
|
5
|
+
match-context windows so a caller can pull back only the part it needs —
|
|
6
|
+
the same progressive-disclosure move the archive pointer already makes for
|
|
7
|
+
the preview. Shared by ``expand`` and reusable by other adapters that hold
|
|
8
|
+
archived text.
|
|
9
|
+
|
|
10
|
+
All offsets are 0-based char offsets into the stored response; line numbers
|
|
11
|
+
are 1-based. Nothing here writes or mutates — callers own I/O and accounting.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import bisect
|
|
16
|
+
import re
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
# A bare ``--start``/``--chars`` read defaults to a ~6k-char window (the paper's
|
|
20
|
+
# doc-read default); match windows are hard-capped so one hot line cannot pull
|
|
21
|
+
# a whole minified file back into context.
|
|
22
|
+
DEFAULT_WINDOW_CHARS = 6000
|
|
23
|
+
MAX_MATCH_WINDOW_CHARS = 8000
|
|
24
|
+
DEFAULT_MATCH_CONTEXT = 3
|
|
25
|
+
MAX_MATCH_CONTEXT = 50
|
|
26
|
+
MAX_MATCH_WINDOWS = 10
|
|
27
|
+
_INT_MAX = 1 << 62
|
|
28
|
+
|
|
29
|
+
_VALUE_FLAGS = frozenset({"lines", "start", "chars", "match", "context", "skip"})
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SpecError(ValueError):
|
|
33
|
+
"""A bounded-read request that cannot be satisfied (bad flag, bad range)."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class ReadSpec:
|
|
38
|
+
"""One bounded-read request, normalized from raw CLI flag values."""
|
|
39
|
+
|
|
40
|
+
kind: str # "chars" | "lines" | "match"
|
|
41
|
+
start: int = 0
|
|
42
|
+
chars: int = DEFAULT_WINDOW_CHARS
|
|
43
|
+
lines: str = ""
|
|
44
|
+
pattern: str = ""
|
|
45
|
+
context: int = DEFAULT_MATCH_CONTEXT
|
|
46
|
+
skip: int = 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Window:
|
|
51
|
+
"""A slice of the stored response plus the coordinates to cite it."""
|
|
52
|
+
|
|
53
|
+
text: str
|
|
54
|
+
start: int # char offset, 0-based inclusive
|
|
55
|
+
end: int # char offset, exclusive
|
|
56
|
+
line_start: int # 1-based first line the slice touches
|
|
57
|
+
line_end: int # 1-based last line the slice touches
|
|
58
|
+
total_chars: int
|
|
59
|
+
total_lines: int
|
|
60
|
+
has_prev: bool
|
|
61
|
+
has_next: bool
|
|
62
|
+
clipped: bool = False # match window trimmed to MAX_MATCH_WINDOW_CHARS
|
|
63
|
+
matched_lines: tuple = () # 1-based line numbers that matched (match mode)
|
|
64
|
+
group_index: int = 0 # 1-based match group number (match mode)
|
|
65
|
+
group_total: int = 0 # total match groups before --skip (match mode)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _bounded_int(value, flag, lo, hi):
|
|
69
|
+
try:
|
|
70
|
+
n = int(str(value).strip(), 10)
|
|
71
|
+
except (TypeError, ValueError):
|
|
72
|
+
raise SpecError(f"--{flag} wants an integer, got {value!r}")
|
|
73
|
+
if n < lo or n > hi:
|
|
74
|
+
raise SpecError(f"--{flag} must be between {lo} and {hi}, got {n}")
|
|
75
|
+
return n
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def spec_from_flags(flags):
|
|
79
|
+
"""Build a ReadSpec from raw ``expand`` flag values, or None when empty.
|
|
80
|
+
|
|
81
|
+
``flags`` maps the bare flag name ("lines", "start", ...) to its string
|
|
82
|
+
value. Conflicting or orphaned flags raise SpecError so the CLI can print
|
|
83
|
+
a usage error instead of silently picking one.
|
|
84
|
+
"""
|
|
85
|
+
if not flags:
|
|
86
|
+
return None
|
|
87
|
+
unknown = sorted(set(flags) - _VALUE_FLAGS)
|
|
88
|
+
if unknown:
|
|
89
|
+
raise SpecError(f"unknown expand option(s): {', '.join('--' + u for u in unknown)}")
|
|
90
|
+
has_lines = "lines" in flags
|
|
91
|
+
has_chars = "chars" in flags or "start" in flags
|
|
92
|
+
has_match = "match" in flags
|
|
93
|
+
if sum(1 for x in (has_lines, has_chars, has_match) if x) > 1:
|
|
94
|
+
raise SpecError("--lines, --start/--chars and --match are mutually exclusive")
|
|
95
|
+
for flag in ("context", "skip"):
|
|
96
|
+
if flag in flags and not has_match:
|
|
97
|
+
raise SpecError(f"--{flag} requires --match")
|
|
98
|
+
if has_match and not str(flags["match"]).strip():
|
|
99
|
+
raise SpecError("--match needs a non-empty pattern")
|
|
100
|
+
if has_lines:
|
|
101
|
+
return ReadSpec(kind="lines", lines=str(flags["lines"]))
|
|
102
|
+
if has_match:
|
|
103
|
+
return ReadSpec(
|
|
104
|
+
kind="match",
|
|
105
|
+
pattern=str(flags["match"]),
|
|
106
|
+
context=_bounded_int(flags.get("context", DEFAULT_MATCH_CONTEXT),
|
|
107
|
+
"context", 0, MAX_MATCH_CONTEXT),
|
|
108
|
+
skip=_bounded_int(flags.get("skip", 0), "skip", 0, _INT_MAX),
|
|
109
|
+
)
|
|
110
|
+
return ReadSpec(
|
|
111
|
+
kind="chars",
|
|
112
|
+
start=_bounded_int(flags.get("start", 0), "start", 0, _INT_MAX),
|
|
113
|
+
chars=_bounded_int(flags.get("chars", DEFAULT_WINDOW_CHARS), "chars", 1, _INT_MAX),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def line_count(text):
|
|
118
|
+
"""Number of LF-terminated lines ``_split_lines`` sees (0 for empty text)."""
|
|
119
|
+
return len(_split_lines(text)[0])
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _split_lines(text):
|
|
123
|
+
"""(line parts with keepends, start offsets). offsets[i] starts line i;
|
|
124
|
+
offsets[len(parts)] == len(text) is the end sentinel.
|
|
125
|
+
|
|
126
|
+
Lines split on ``\\n`` only so line numbers agree with ``grep -n``/``sed -n``;
|
|
127
|
+
``str.splitlines`` would also break on \\x0b, \\x0c, \\x1c-\\x1e, \\x85 and
|
|
128
|
+
U+2028/U+2029, which are not line boundaries for the archived tools.
|
|
129
|
+
"""
|
|
130
|
+
raw = text.split("\n")
|
|
131
|
+
parts = [seg + "\n" for seg in raw[:-1]]
|
|
132
|
+
if raw[-1]:
|
|
133
|
+
parts.append(raw[-1])
|
|
134
|
+
offsets = [0]
|
|
135
|
+
for part in parts:
|
|
136
|
+
offsets.append(offsets[-1] + len(part))
|
|
137
|
+
return parts, offsets
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _line_of(offsets, n_lines, pos):
|
|
141
|
+
"""0-based index of the line containing char ``pos`` (clamped)."""
|
|
142
|
+
i = bisect.bisect_right(offsets, pos) - 1
|
|
143
|
+
return max(0, min(i, n_lines - 1))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _window(text, offsets, n_lines, start, end, has_prev, has_next, **kw):
|
|
147
|
+
return Window(
|
|
148
|
+
text=text[start:end], start=start, end=end,
|
|
149
|
+
line_start=_line_of(offsets, n_lines, start) + 1,
|
|
150
|
+
line_end=_line_of(offsets, n_lines, max(start, end - 1)) + 1,
|
|
151
|
+
total_chars=len(text), total_lines=n_lines,
|
|
152
|
+
has_prev=has_prev, has_next=has_next, **kw)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def char_window(text, start, length):
|
|
156
|
+
"""``length`` chars beginning at 0-based ``start`` (clamped at EOF)."""
|
|
157
|
+
total = len(text)
|
|
158
|
+
if start < 0:
|
|
159
|
+
raise SpecError("--start must be >= 0")
|
|
160
|
+
if length < 1:
|
|
161
|
+
raise SpecError("--chars must be >= 1")
|
|
162
|
+
if start >= total:
|
|
163
|
+
raise SpecError(f"--start {start} is past the end ({total} chars)")
|
|
164
|
+
end = min(total, start + length)
|
|
165
|
+
parts, offsets = _split_lines(text)
|
|
166
|
+
return _window(text, offsets, len(parts), start, end,
|
|
167
|
+
has_prev=start > 0, has_next=end < total)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
_LINE_SPEC = re.compile(r"(\d+)(?::(\d*)|-(\d*))?\Z")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def line_window(text, spec):
|
|
174
|
+
"""Lines ``spec`` of ``text``. Accepts ``A``, ``A:B``, ``A-B``; a bare
|
|
175
|
+
separator (``A:`` / ``A-``) reads to EOF. Lines are 1-based."""
|
|
176
|
+
m = _LINE_SPEC.fullmatch(str(spec).strip())
|
|
177
|
+
if not m:
|
|
178
|
+
raise SpecError("--lines wants A, A:B or A-B (1-based; trailing B optional = to EOF)")
|
|
179
|
+
first = int(m.group(1))
|
|
180
|
+
parts, offsets = _split_lines(text)
|
|
181
|
+
n_lines = len(parts)
|
|
182
|
+
if first < 1:
|
|
183
|
+
raise SpecError("--lines are 1-based; the first line must be >= 1")
|
|
184
|
+
if n_lines == 0 or first > n_lines:
|
|
185
|
+
raise SpecError(f"--lines {first}: is past the end ({n_lines} lines)")
|
|
186
|
+
if m.group(2) is None and m.group(3) is None:
|
|
187
|
+
last = first # bare "A" = that one line
|
|
188
|
+
else:
|
|
189
|
+
tail = m.group(2) if m.group(2) is not None else m.group(3)
|
|
190
|
+
last = n_lines if tail == "" else int(tail)
|
|
191
|
+
if last < first:
|
|
192
|
+
raise SpecError(f"--lines end {last} is before start {first}")
|
|
193
|
+
last = min(last, n_lines)
|
|
194
|
+
start, end = offsets[first - 1], offsets[last]
|
|
195
|
+
return _window(text, offsets, n_lines, start, end,
|
|
196
|
+
has_prev=first > 1, has_next=last < n_lines)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _match_span(line, rx, needle):
|
|
200
|
+
"""(start, end) of the first match in ``line``, or None."""
|
|
201
|
+
if rx is not None:
|
|
202
|
+
m = rx.search(line)
|
|
203
|
+
return (m.start(), m.end()) if m else None
|
|
204
|
+
i = line.find(needle)
|
|
205
|
+
return (i, i + len(needle)) if i >= 0 else None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _match_last_end(line, rx, needle):
|
|
209
|
+
"""End offset of the LAST match in ``line``."""
|
|
210
|
+
if rx is not None:
|
|
211
|
+
end = 0
|
|
212
|
+
for m in rx.finditer(line):
|
|
213
|
+
end = m.end()
|
|
214
|
+
return end or len(line)
|
|
215
|
+
i = line.rfind(needle)
|
|
216
|
+
return (i + len(needle)) if i >= 0 else len(line)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _clip_to_matches(text, parts, offsets, group, rx, needle):
|
|
220
|
+
"""A <=MAX_MATCH_WINDOW_CHARS char range centered on the group's matches."""
|
|
221
|
+
total = len(text)
|
|
222
|
+
span_s = offsets[group[0]] + (_match_span(parts[group[0]], rx, needle) or (0, 0))[0]
|
|
223
|
+
span_e = offsets[group[-1]] + _match_last_end(parts[group[-1]], rx, needle)
|
|
224
|
+
span_len = max(1, span_e - span_s)
|
|
225
|
+
if span_len >= MAX_MATCH_WINDOW_CHARS:
|
|
226
|
+
ws, we = span_s, min(total, span_s + MAX_MATCH_WINDOW_CHARS)
|
|
227
|
+
else:
|
|
228
|
+
pad = (MAX_MATCH_WINDOW_CHARS - span_len) // 2
|
|
229
|
+
ws = max(0, span_s - pad)
|
|
230
|
+
we = min(total, ws + MAX_MATCH_WINDOW_CHARS)
|
|
231
|
+
ws = max(0, we - MAX_MATCH_WINDOW_CHARS)
|
|
232
|
+
return ws, we
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def match_windows(text, pattern, context=DEFAULT_MATCH_CONTEXT, skip=0,
|
|
236
|
+
limit=MAX_MATCH_WINDOWS):
|
|
237
|
+
"""``limit`` context windows around literal substring matches, after ``skip``
|
|
238
|
+
groups. Returns ``(windows, group_total)``; ``group_total`` counts every
|
|
239
|
+
match group so the caller can say how many remain.
|
|
240
|
+
|
|
241
|
+
The pattern is always a literal substring (``grep -F`` semantics), never a
|
|
242
|
+
regex: an agent-supplied pattern cannot backtrack over a multi-MB archive.
|
|
243
|
+
"""
|
|
244
|
+
parts, offsets = _split_lines(text)
|
|
245
|
+
n_lines = len(parts)
|
|
246
|
+
needle = str(pattern)
|
|
247
|
+
if n_lines == 0 or not needle:
|
|
248
|
+
return [], 0
|
|
249
|
+
matched = [i for i, line in enumerate(parts)
|
|
250
|
+
if _match_span(line, None, needle) is not None]
|
|
251
|
+
if not matched:
|
|
252
|
+
return [], 0
|
|
253
|
+
# Cluster matched lines into groups: two matches share a window when their
|
|
254
|
+
# ±context ranges touch, i.e. the gap is at most 2*context+1 lines.
|
|
255
|
+
groups = [[matched[0]]]
|
|
256
|
+
for idx in matched[1:]:
|
|
257
|
+
if idx - groups[-1][-1] <= 2 * context + 1:
|
|
258
|
+
groups[-1].append(idx)
|
|
259
|
+
else:
|
|
260
|
+
groups.append([idx])
|
|
261
|
+
windows = []
|
|
262
|
+
for gpos, group in enumerate(groups[skip:skip + limit]):
|
|
263
|
+
lo = max(0, group[0] - context)
|
|
264
|
+
hi = min(n_lines - 1, group[-1] + context)
|
|
265
|
+
ws, we = offsets[lo], offsets[hi + 1]
|
|
266
|
+
clipped = we - ws > MAX_MATCH_WINDOW_CHARS
|
|
267
|
+
if clipped:
|
|
268
|
+
ws, we = _clip_to_matches(text, parts, offsets, group, None, needle)
|
|
269
|
+
windows.append(_window(
|
|
270
|
+
text, offsets, n_lines, ws, we,
|
|
271
|
+
has_prev=False, has_next=False, clipped=clipped,
|
|
272
|
+
matched_lines=tuple(i + 1 for i in group),
|
|
273
|
+
group_index=skip + gpos + 1, group_total=len(groups)))
|
|
274
|
+
return windows, len(groups)
|