@alexgreensh/token-optimizer 5.13.63 → 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 +5 -0
- package/package.json +1 -1
- package/skills/fleet-auditor/SKILL.md +1 -1
- 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 +180 -44
- 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/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_session.py +149 -1
- package/skills/token-optimizer/scripts/devin_source.py +2 -2
- package/skills/token-optimizer/scripts/measure.py +3498 -1111
- package/skills/token-optimizer/scripts/read_cache.py +20 -7
- package/skills/token-optimizer/scripts/recovery_output.py +67 -18
- package/skills/token-optimizer/scripts/session_activity.py +169 -0
- package/skills/token-optimizer/scripts/session_store.py +63 -9
- package/skills/token-optimizer/scripts/statusline.js +4 -6
|
@@ -180,7 +180,7 @@ Estimated savings: ~X tokens
|
|
|
180
180
|
Handled in Phase 0 setup. If the user skipped it there, offer again here:
|
|
181
181
|
|
|
182
182
|
```bash
|
|
183
|
-
|
|
183
|
+
"$PY" "$MEASURE_PY" check-hook
|
|
184
184
|
```
|
|
185
185
|
|
|
186
186
|
If not installed, run `setup-hook --dry-run` to show the proposed change, then `setup-hook` after confirmation. The hook runs `measure.py collect --quiet` once per session close (~1 second, zero background processes).
|
|
@@ -324,7 +324,7 @@ Add or improve model routing instructions in CLAUDE.md.
|
|
|
324
324
|
- opus: architecture decisions, novel debugging, cross-cutting synthesis
|
|
325
325
|
```
|
|
326
326
|
3. If routing instructions exist, compare against actual model_mix usage:
|
|
327
|
-
- Run `
|
|
327
|
+
- Run `"$PY" "$MEASURE_PY" trends --json --days 30` if trends DB exists
|
|
328
328
|
- Are subagents actually following the routing? (check model_mix percentages)
|
|
329
329
|
- Is the instruction specific enough? ("default to haiku" vs detailed task-to-model table)
|
|
330
330
|
- If >70% of tokens go to Opus despite routing instructions, the instructions may be too vague
|
|
@@ -348,7 +348,7 @@ Check the user's Claude Code version (`claude --version`) and apply version-spec
|
|
|
348
348
|
**v2.1.86+: Read tool native deduplication**
|
|
349
349
|
- Claude Code deduplicates unchanged re-reads natively (compact line-number format)
|
|
350
350
|
- If Token Optimizer's `read_cache.py` PreToolUse hook is installed, it is redundant on v2.1.86+
|
|
351
|
-
- Check: run `
|
|
351
|
+
- Check: run `"$PY" "$MEASURE_PY" read-cache-stats --session current`. If "blocks: 0" for recent sessions, native dedup is handling it.
|
|
352
352
|
- Action: Disable the read-cache hook (`TOKEN_OPTIMIZER_READ_CACHE=0` in settings.json env block) to eliminate hook process overhead
|
|
353
353
|
|
|
354
354
|
**v2.1.86+: @ file mentions no longer JSON-escaped**
|
|
@@ -413,4 +413,4 @@ Check the user's Claude Code version (`claude --version`) and apply version-spec
|
|
|
413
413
|
| User says 'skip verification' | "Noted. Skipping verification. Recommend running /cost before and after to measure actual savings." |
|
|
414
414
|
| Backup is empty/missing | "Backup directory appears empty. This could mean a fresh setup or a write failure. Proceeding without backup, but will not modify any files without explicit user confirmation for each change." |
|
|
415
415
|
| File write fails mid-implementation | "Write failed for [file]. Restoring from backup. Check disk space and permissions." Present the restore command from the Restoring Backups section. |
|
|
416
|
-
| Synthesis output missing | "Synthesis agent did not produce output. Showing raw audit findings instead." Present the individual audit files from
|
|
416
|
+
| Synthesis output missing | "Synthesis agent did not produce output. Showing raw audit findings instead." Present the individual audit files from {COORD_PATH}/audit/ for user review. |
|
|
@@ -5,7 +5,7 @@ Keep-Warm pings the prompt cache before it expires so a paused session resumes w
|
|
|
5
5
|
## 1. Check whether to ask
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
-
|
|
8
|
+
"$PY" "$MEASURE_PY" keepwarm-consent-status # JSON: {billing_mode, consent, should_ask}
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
`should_ask` false: say nothing. True (API-billed, not yet asked): continue.
|
|
@@ -13,7 +13,7 @@ python3 "$MEASURE_PY" keepwarm-consent-status # JSON: {billing_mode, consent,
|
|
|
13
13
|
## 2. Compute the user's own projection
|
|
14
14
|
|
|
15
15
|
```bash
|
|
16
|
-
|
|
16
|
+
"$PY" "$MEASURE_PY" keepwarm-backfill --json --no-fence # read modes."probe-only".net_usd
|
|
17
17
|
```
|
|
18
18
|
|
|
19
19
|
## 3. Pitch
|
|
@@ -28,21 +28,21 @@ When a session pauses past its cache window and resumes, the whole prefix is wri
|
|
|
28
28
|
Recording the answer before anything else means an interrupted run never leaves an "asked" marker with no answer.
|
|
29
29
|
|
|
30
30
|
```bash
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
"$PY" "$MEASURE_PY" keepwarm-enable # yes: records consent and installs the scheduler (macOS)
|
|
32
|
+
"$PY" "$MEASURE_PY" keepwarm-disable # no
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
Both are final, so the user is not asked again. Only when the user neither accepts nor declines:
|
|
36
36
|
|
|
37
37
|
```bash
|
|
38
|
-
|
|
38
|
+
"$PY" "$MEASURE_PY" keepwarm-consent-asked # marks the question as shown
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
## 5. Confirm it is armed (after a yes)
|
|
42
42
|
|
|
43
43
|
```bash
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
"$PY" "$MEASURE_PY" keepwarm-scheduler status # installed and loaded state (macOS)
|
|
45
|
+
"$PY" "$MEASURE_PY" keepwarm-tick --dry-run # what the next tick would decide
|
|
46
46
|
```
|
|
47
47
|
|
|
48
48
|
On Linux and Windows the scheduler is not shipped yet: Keep-Warm runs watchdog-only until the user wires `keepwarm-tick` to their own cron or timer. Tell them that plainly.
|
|
@@ -45,8 +45,10 @@ Or drop a local build into `~/.config/opencode/plugins/` (OpenCode auto-loads it
|
|
|
45
45
|
If the user genuinely wants to audit a Claude Code setup *from* OpenCode (rare),
|
|
46
46
|
they can force the runtime:
|
|
47
47
|
|
|
48
|
+
Resolve `$MEASURE_PY` and `$PY` first with the SKILL.md Step 0b snippet (this file is followed instead of the audit phases, so they are not set yet).
|
|
49
|
+
|
|
48
50
|
```bash
|
|
49
|
-
TOKEN_OPTIMIZER_RUNTIME=claude
|
|
51
|
+
TOKEN_OPTIMIZER_RUNTIME=claude "$PY" "$MEASURE_PY" report
|
|
50
52
|
```
|
|
51
53
|
|
|
52
54
|
This is opt-in and explicit. The default under OpenCode is to never touch
|
|
@@ -64,7 +66,7 @@ hooks into `~/.claude/settings.json` (via `measure.py setup-all-hooks`).
|
|
|
64
66
|
- If you use **OpenCode only**: the Claude hooks are unnecessary. After
|
|
65
67
|
running `install.sh`, remove them with:
|
|
66
68
|
```bash
|
|
67
|
-
|
|
69
|
+
"$PY" ~/.claude/token-optimizer/skills/token-optimizer/scripts/measure.py cleanup-duplicate-hooks
|
|
68
70
|
```
|
|
69
71
|
Or simply re-create the symlink manually:
|
|
70
72
|
```bash
|
|
@@ -468,9 +468,9 @@ See `examples/hooks-starter.json` for a ready-to-use template.
|
|
|
468
468
|
**What it does**: Captures structured session state before compaction fires, then restores the critical pieces after compaction completes. Decisions, error-fix sequences, agent state, and modified files survive the lossy compaction process.
|
|
469
469
|
|
|
470
470
|
**Actions**:
|
|
471
|
-
- [ ] Install Smart Compaction hooks: `
|
|
472
|
-
- [ ] Run `
|
|
473
|
-
- [ ] Generate project-specific Compact Instructions: `
|
|
471
|
+
- [ ] Install Smart Compaction hooks: `"$PY" "$MEASURE_PY" setup-smart-compact --dry-run` (preview first)
|
|
472
|
+
- [ ] Run `"$PY" "$MEASURE_PY" setup-smart-compact` to install
|
|
473
|
+
- [ ] Generate project-specific Compact Instructions: `"$PY" "$MEASURE_PY" compact-instructions`
|
|
474
474
|
- [ ] Add the generated instructions to `.claude/settings.json` under `compactInstructions`
|
|
475
475
|
|
|
476
476
|
**What the hooks do**:
|
|
@@ -490,7 +490,7 @@ See `examples/hooks-starter.json` for a ready-to-use template.
|
|
|
490
490
|
**What it does**: Analyzes your session JSONL and scores how useful your context content is. A session at 60% with clean, relevant content performs differently from 60% stuffed with stale reads and duplicate injections.
|
|
491
491
|
|
|
492
492
|
**Actions**:
|
|
493
|
-
- [ ] Run `
|
|
493
|
+
- [ ] Run `"$PY" "$MEASURE_PY" quality` on your current or recent session
|
|
494
494
|
- [ ] Check your score: 85+ is excellent, 70-84 good, 50-69 degraded, <50 critical
|
|
495
495
|
- [ ] Act on specific issues: stale reads, bloated results, duplicate reminders
|
|
496
496
|
|
|
@@ -498,7 +498,7 @@ See `examples/hooks-starter.json` for a ready-to-use template.
|
|
|
498
498
|
- Stale read ratio (files read then later edited, making the read content outdated)
|
|
499
499
|
- Tool result bloat (large results never referenced again)
|
|
500
500
|
- Duplicate content (repeated system reminders)
|
|
501
|
-
- Compaction
|
|
501
|
+
- Compaction count (descriptive only; measured post-boundary recovery signals are reported separately)
|
|
502
502
|
- Decision density (ratio of substantive to overhead exchanges)
|
|
503
503
|
- Agent efficiency (dispatch cost vs useful result size)
|
|
504
504
|
|
|
@@ -512,16 +512,16 @@ See `examples/hooks-starter.json` for a ready-to-use template.
|
|
|
512
512
|
|
|
513
513
|
```bash
|
|
514
514
|
# Measure current state
|
|
515
|
-
|
|
515
|
+
"$PY" "$MEASURE_PY" report
|
|
516
516
|
|
|
517
517
|
# Save snapshot before optimizing
|
|
518
|
-
|
|
518
|
+
"$PY" "$MEASURE_PY" snapshot before
|
|
519
519
|
|
|
520
520
|
# After optimization
|
|
521
|
-
|
|
521
|
+
"$PY" "$MEASURE_PY" snapshot after
|
|
522
522
|
|
|
523
523
|
# Compare
|
|
524
|
-
|
|
524
|
+
"$PY" "$MEASURE_PY" compare
|
|
525
525
|
```
|
|
526
526
|
|
|
527
527
|
Also track with `/cost` at end of each session and `measure.py trends` for historical data. The SessionEnd hook auto-collects usage into a local SQLite database.
|
|
@@ -21,7 +21,7 @@ Keep this quick, one question max.
|
|
|
21
21
|
|
|
22
22
|
## Quick Pre-Check
|
|
23
23
|
|
|
24
|
-
Run `
|
|
24
|
+
Run `"$PY" "$MEASURE_PY" report`.
|
|
25
25
|
If estimated controllable tokens < 1,000 and no CLAUDE.md exists, short-circuit:
|
|
26
26
|
```
|
|
27
27
|
[Token Optimizer] Your setup is already minimal (~X tokens overhead).
|
|
@@ -63,7 +63,7 @@ mkdir -p "$COORD_PATH"/{audit,analysis,plan,verification}
|
|
|
63
63
|
## SessionEnd Hook Check
|
|
64
64
|
|
|
65
65
|
```bash
|
|
66
|
-
|
|
66
|
+
"$PY" "$MEASURE_PY" check-hook
|
|
67
67
|
```
|
|
68
68
|
- Exit 0: already installed, skip to Phase 1.
|
|
69
69
|
- Exit 1 (manual/script install users only): explain and offer to install:
|
|
@@ -81,7 +81,7 @@ What this does:
|
|
|
81
81
|
- All data stays on your machine (stored in ~/.claude/_backups/token-optimizer/)
|
|
82
82
|
- Powers the Trends and Health tabs in your dashboard
|
|
83
83
|
|
|
84
|
-
Remove anytime:
|
|
84
|
+
Remove anytime: "$PY" "$MEASURE_PY" setup-hook --uninstall
|
|
85
85
|
```
|
|
86
86
|
|
|
87
87
|
Ask user: 1) Install (dry-run first), 2) Show JSON first, 3) Skip
|
|
@@ -90,8 +90,8 @@ Ask user: 1) Install (dry-run first), 2) Show JSON first, 3) Skip
|
|
|
90
90
|
|
|
91
91
|
Run BOTH probes in one pass:
|
|
92
92
|
```bash
|
|
93
|
-
|
|
94
|
-
|
|
93
|
+
"$PY" "$MEASURE_PY" daemon-status
|
|
94
|
+
"$PY" "$MEASURE_PY" daemon-consent --get
|
|
95
95
|
```
|
|
96
96
|
|
|
97
97
|
`daemon-status` prints `DAEMON_RUNNING`, `DAEMON_FOREIGN`, or `DAEMON_NOT_RUNNING`.
|
|
@@ -116,7 +116,7 @@ What installing the URL does:
|
|
|
116
116
|
- Starts automatically at login, restarts if it ever stops
|
|
117
117
|
- Only reachable from this machine (localhost)
|
|
118
118
|
|
|
119
|
-
Remove anytime:
|
|
119
|
+
Remove anytime: "$PY" "$MEASURE_PY" setup-daemon --uninstall
|
|
120
120
|
```
|
|
121
121
|
|
|
122
122
|
Ask user: 1) Install (write consent first, then install), 2) Skip (set consent no)
|
|
@@ -125,7 +125,7 @@ On Linux/BSD: skip silently, mention `file://` URL works.
|
|
|
125
125
|
## Smart Compaction Check
|
|
126
126
|
|
|
127
127
|
```bash
|
|
128
|
-
|
|
128
|
+
"$PY" "$MEASURE_PY" setup-smart-compact --status
|
|
129
129
|
```
|
|
130
130
|
- All 4 hooks installed: skip entirely.
|
|
131
131
|
- Partially or not installed: explain and offer:
|
|
@@ -134,9 +134,9 @@ python3 $MEASURE_PY setup-smart-compact --status
|
|
|
134
134
|
[Token Optimizer] Smart Compaction captures session state BEFORE compaction fires,
|
|
135
135
|
then restores it afterward. Decisions, modified files, errors, agent state.
|
|
136
136
|
|
|
137
|
-
Remove anytime:
|
|
137
|
+
Remove anytime: "$PY" "$MEASURE_PY" setup-smart-compact --uninstall
|
|
138
138
|
```
|
|
139
139
|
|
|
140
140
|
Ask user: 1) Install (dry-run first), 2) Show JSON first, 3) Skip
|
|
141
141
|
|
|
142
|
-
Output: `[Token Optimizer Initialized] Backup:
|
|
142
|
+
Output: `[Token Optimizer Initialized] Backup: {BACKUP_DIR} | Coordination: {COORD_PATH}`
|
|
@@ -39,7 +39,7 @@ What should we tackle first?
|
|
|
39
39
|
## Dashboard Generation
|
|
40
40
|
|
|
41
41
|
```bash
|
|
42
|
-
|
|
42
|
+
"$PY" "$MEASURE_PY" dashboard --coord-path "$COORD_PATH"
|
|
43
43
|
```
|
|
44
44
|
|
|
45
45
|
Tell the user: "Dashboard opened in your browser. Browse findings by category, check the optimizations you want, click Copy Prompt and paste back here. Or just tell me directly what to tackle."
|
|
@@ -48,7 +48,7 @@ Tell the user: "Dashboard opened in your browser. Browse findings by category, c
|
|
|
48
48
|
|
|
49
49
|
Check daemon status first:
|
|
50
50
|
```bash
|
|
51
|
-
|
|
51
|
+
"$PY" "$MEASURE_PY" daemon-status 2>/dev/null || echo "DAEMON_NOT_RUNNING"
|
|
52
52
|
```
|
|
53
53
|
|
|
54
54
|
If DAEMON_RUNNING:
|
|
@@ -64,7 +64,7 @@ Your persistent dashboard (auto-updated every session):
|
|
|
64
64
|
File: <read from `measure.py dashboard` output, line beginning ` Dashboard: `>
|
|
65
65
|
```
|
|
66
66
|
Never hardcode the file path. It is install-dependent, so cite the path the command actually printed.
|
|
67
|
-
On macOS only, suggest: "Want a bookmarkable URL? Run: `
|
|
67
|
+
On macOS only, suggest: "Want a bookmarkable URL? Run: `"$PY" "$MEASURE_PY" setup-daemon`"
|
|
68
68
|
Do NOT mention `localhost:24842` if daemon is not running.
|
|
69
69
|
|
|
70
70
|
For headless/remote: user can run `dashboard --serve` separately. Never use `--serve` from within the orchestrator (it blocks with `serve_forever`).
|
|
@@ -13,7 +13,7 @@ work, check what we discussed last session"), the continuity hook reconstructs a
|
|
|
13
13
|
- **Savings** are credited as a realized `resume_lean` event (avoided cold-resume
|
|
14
14
|
cache-rewrite minus the lean block), idempotent per target session, shown in the
|
|
15
15
|
Savings view. Realized tier, same as `checkpoint_restore`.
|
|
16
|
-
- **Manual fallback**: `
|
|
16
|
+
- **Manual fallback**: `"$PY" "$MEASURE_PY" resume-lean` lists cold sessions;
|
|
17
17
|
`resume-lean <#|session_id> --print` emits the block for `claude "$(...)"`.
|
|
18
18
|
- Ported across Claude Code, Codex, OpenClaw, opencode (checkpoint richness varies
|
|
19
19
|
by platform; the lean block adapts to available fields).
|
|
@@ -367,7 +367,8 @@ Most Claude Code users are on Max subscriptions ($100-200/month), not per-token
|
|
|
367
367
|
35K overhead = 18% of 200K (3.5% of 1M). Compaction arrives that much sooner.
|
|
368
368
|
|
|
369
369
|
2. MORE COMPACTION CYCLES
|
|
370
|
-
Each compaction
|
|
370
|
+
Each compaction rewrites context to a summary; recovery quality is measured
|
|
371
|
+
per boundary, not assumed. More compactions still means more summary passes.
|
|
371
372
|
A session with 35K overhead compacts ~2x more often than 20K.
|
|
372
373
|
|
|
373
374
|
3. QUALITY DEGRADATION
|
|
@@ -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)
|