its-magic 0.1.2-35 → 0.1.2-36

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.
@@ -315,6 +315,21 @@ Manual override precedence:
315
315
  - Profile changes must not disable mandatory gate contracts
316
316
  (`/qa`, `/verify-work`, `/release`).
317
317
 
318
+ ### Token-cost evidence + comparability (US-0080 / DEC-0062)
319
+
320
+ - **Fresh context**: spawn **new** subagents per `/auto` phase; avoid carrying prior chat
321
+ reasoning as phase input.
322
+ - **`start-from`**: use **`/auto start-from=<canonical_phase_id>`** when resuming so the
323
+ schedule intersection matches materialized **`resolved_phase_plan`** (**`DEC-0052`**).
324
+ - **`TOKEN_PROFILE`**: `lean` lowers default automation breadth; does **not** remove
325
+ isolation, strict-proof, role, or release gates.
326
+ - **Metrics**: append-only **`handoffs/token_cost_runs/<orchestrator_run_id>.md`** (or
327
+ **`.jsonl`**); copy path into **`token_cost_evidence_ref`** on **`state.md`** checkpoints.
328
+ - **AC-2**: compare **`cache_read_tokens`** only when **`run_class_hash`** matches; else
329
+ **`TOKEN_COST_RUN_CLASS_MISMATCH`**.
330
+ - **CI/repo checks**: `python scripts/check_token_cost_parity.py --repo .` (manifest-listed
331
+ active/`template/` pairs); **`tests/run-tests.ps1`** / **`tests/run-tests.sh`** §26M.
332
+
318
333
  Context compaction policy:
319
334
 
320
335
  - `docs/engineering/state.md` is a compact hot surface for current execution
@@ -0,0 +1,16 @@
1
+ # Token-cost parity manifest (DEC-0062 §5 / US-0080)
2
+
3
+ - **version**: `1`
4
+ - **purpose**: Paths below MUST be **byte-identical** between repository root and
5
+ `template/` after edits (installer parity). CI: `python scripts/check_token_cost_parity.py --repo .`
6
+
7
+ ## Mirrored path pairs (`active` → `template`)
8
+
9
+ - `.cursor/commands/auto.md` → `template/.cursor/commands/auto.md`
10
+ - `.cursor/commands/execute.md` → `template/.cursor/commands/execute.md`
11
+ - `docs/engineering/auto-orchestration-reference.md` → `template/docs/engineering/auto-orchestration-reference.md`
12
+ - `docs/engineering/token-cost-parity-manifest.md` → `template/docs/engineering/token-cost-parity-manifest.md`
13
+ - `scripts/token_cost_lib.py` → `template/scripts/token_cost_lib.py`
14
+ - `scripts/token_cost_compare.py` → `template/scripts/token_cost_compare.py`
15
+ - `scripts/check_token_cost_parity.py` → `template/scripts/check_token_cost_parity.py`
16
+ - `handoffs/token_cost_runs/README.md` → `template/handoffs/token_cost_runs/README.md`
@@ -0,0 +1,26 @@
1
+ # Token-cost run evidence (`handoffs/token_cost_runs/`)
2
+
3
+ Append-only artifacts per **`orchestrator_run_id`** (**`DEC-0062`** §3, **`US-0080`**).
4
+
5
+ ## Schema (markdown table)
6
+
7
+ Each run file SHOULD include:
8
+
9
+ - `orchestrator_run_id` — stable id for the orchestrated run
10
+ - `run_class_hash` — SHA-256 hex over canonical **`DEC-0062`** §2 JSON object
11
+ - `metric_source` — how numbers were produced (for example `cursor_usage_export`,
12
+ `fixture`, `unmapped_host`)
13
+ - `recorded_at_utc` — RFC3339 UTC
14
+ - **Run totals** row: `cache_read_tokens`, `input_tokens`, `output_tokens`, and
15
+ optional `cache_creation_tokens`, `orchestrator_call_estimate`
16
+ - **Per-phase** rows: same metrics plus `phase_id`, `phase_call_count`
17
+
18
+ `docs/engineering/state.md` checkpoints SHOULD set **`token_cost_evidence_ref`**
19
+ to the primary file path when metrics exist.
20
+
21
+ ## Tooling
22
+
23
+ - `scripts/token_cost_lib.py` — `run_class_hash`, strict-proof hash helper, AC-2 compare
24
+ - `scripts/token_cost_compare.py <baseline.json> <target.json>` — exit **0** if
25
+ same `run_class_hash` and ≥ **50%** `cache_read_tokens` reduction vs baseline
26
+ - `python scripts/check_token_cost_parity.py --repo .` — active/`template/` parity
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env python3
2
+ """Verify active vs template/ bytes match for DEC-0062 token-cost parity manifest paths."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import re
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ _PAIR_RE = re.compile(r"`([^`]+)`\s*→\s*`([^`]+)`")
12
+
13
+
14
+ def load_pairs(manifest_text: str) -> list[tuple[Path, Path]]:
15
+ pairs: list[tuple[Path, Path]] = []
16
+ for line in manifest_text.splitlines():
17
+ line = line.strip()
18
+ if not line.startswith("- "):
19
+ continue
20
+ m = _PAIR_RE.search(line)
21
+ if not m:
22
+ continue
23
+ pairs.append((Path(m.group(1)), Path(m.group(2))))
24
+ return pairs
25
+
26
+
27
+ def main() -> int:
28
+ p = argparse.ArgumentParser(description=__doc__)
29
+ p.add_argument(
30
+ "--repo",
31
+ type=Path,
32
+ default=Path(__file__).resolve().parent.parent,
33
+ help="Repository root",
34
+ )
35
+ args = p.parse_args()
36
+ root: Path = args.repo
37
+ manifest = root / "docs/engineering/token-cost-parity-manifest.md"
38
+ if not manifest.is_file():
39
+ print(f"[TOKEN_COST_PARITY_ERROR] missing manifest: {manifest}")
40
+ return 2
41
+ text = manifest.read_text(encoding="utf-8")
42
+ pairs = load_pairs(text)
43
+ if not pairs:
44
+ print("[TOKEN_COST_PARITY_ERROR] no path pairs parsed from manifest")
45
+ return 2
46
+ failed = False
47
+ for rel_active, rel_tpl in pairs:
48
+ a = root / rel_active
49
+ t = root / rel_tpl
50
+ if not a.is_file() or not t.is_file():
51
+ print(f"[TOKEN_COST_PARITY_ERROR] missing file: {rel_active} or {rel_tpl}")
52
+ failed = True
53
+ continue
54
+ ba = a.read_bytes()
55
+ bt = t.read_bytes()
56
+ if ba != bt:
57
+ print(
58
+ f"[TOKEN_COST_PARITY_ERROR] mismatch: {rel_active} ({len(ba)}b) "
59
+ f"!= {rel_tpl} ({len(bt)}b)"
60
+ )
61
+ failed = True
62
+ if failed:
63
+ return 2
64
+ print("[TOKEN_COST_PARITY_OK]")
65
+ return 0
66
+
67
+
68
+ if __name__ == "__main__":
69
+ sys.exit(main())
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env python3
2
+ """Compare two token-cost run JSON records for AC-2 (same run_class_hash, 50% cache read)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ _SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
13
+ if _SCRIPT_DIR not in sys.path:
14
+ sys.path.insert(0, _SCRIPT_DIR)
15
+
16
+ import token_cost_lib # noqa: E402
17
+
18
+
19
+ def main() -> int:
20
+ p = argparse.ArgumentParser(description=__doc__)
21
+ p.add_argument("baseline", type=Path, help="JSON file with run_class_hash + totals")
22
+ p.add_argument("target", type=Path, help="JSON file with run_class_hash + totals")
23
+ p.add_argument(
24
+ "--reduction-fraction",
25
+ type=float,
26
+ default=0.5,
27
+ help="Required fractional reduction in cache_read_tokens (default 0.5)",
28
+ )
29
+ args = p.parse_args()
30
+ base = json.loads(args.baseline.read_text(encoding="utf-8"))
31
+ tgt = json.loads(args.target.read_text(encoding="utf-8"))
32
+ ok, msg = token_cost_lib.compare_cache_read_reduction(
33
+ base, tgt, reduction_fraction=args.reduction_fraction
34
+ )
35
+ print(msg)
36
+ return 0 if ok else 2
37
+
38
+
39
+ if __name__ == "__main__":
40
+ sys.exit(main())
@@ -0,0 +1,108 @@
1
+ """Token-cost run class, metrics, and AC-2 comparability helpers (US-0080 / DEC-0062)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from typing import Any, Mapping
8
+
9
+ # Canonical metric keys (DEC-0062 §1) — totals / per-phase rows
10
+ METRIC_KEYS = (
11
+ "cache_read_tokens",
12
+ "input_tokens",
13
+ "output_tokens",
14
+ "phase_call_count",
15
+ "cache_creation_tokens",
16
+ "orchestrator_call_estimate",
17
+ )
18
+
19
+ REQUIRED_TOTAL_KEYS = (
20
+ "cache_read_tokens",
21
+ "input_tokens",
22
+ "output_tokens",
23
+ )
24
+
25
+
26
+ def canonical_json_dumps(obj: Mapping[str, Any]) -> str:
27
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"))
28
+
29
+
30
+ def compute_run_class_hash(run_class: Mapping[str, Any]) -> str:
31
+ """SHA-256 hex (lowercase) of canonical JSON for DEC-0062 §2 tuple."""
32
+ payload = canonical_json_dumps(run_class)
33
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
34
+
35
+
36
+ def compute_strict_proof_hash(
37
+ orchestrator_run_id: str,
38
+ runtime_proof_id: str,
39
+ phase_id: str,
40
+ role: str,
41
+ proof_issued_at: str,
42
+ proof_ttl_seconds: int,
43
+ ) -> str:
44
+ """DEC-0038-style sorted-key JSON SHA-256 over the strict-proof tuple fields."""
45
+ obj = {
46
+ "orchestrator_run_id": orchestrator_run_id,
47
+ "runtime_proof_id": runtime_proof_id,
48
+ "phase_id": phase_id,
49
+ "role": role,
50
+ "proof_issued_at": proof_issued_at,
51
+ "proof_ttl_seconds": int(proof_ttl_seconds),
52
+ }
53
+ return hashlib.sha256(canonical_json_dumps(obj).encode("utf-8")).hexdigest()
54
+
55
+
56
+ def validate_run_totals(row: Mapping[str, Any]) -> list[str]:
57
+ """Return diagnostic strings for invalid totals; empty if OK."""
58
+ errs: list[str] = []
59
+ for k in REQUIRED_TOTAL_KEYS:
60
+ if k not in row:
61
+ errs.append(f"missing_metric:{k}")
62
+ continue
63
+ v = row[k]
64
+ if not isinstance(v, int) or v < 0:
65
+ errs.append(f"invalid_non_negative_int:{k}")
66
+ if "metric_source" not in row or not str(row.get("metric_source", "")).strip():
67
+ errs.append("missing_metric_source")
68
+ return errs
69
+
70
+
71
+ def compare_cache_read_reduction(
72
+ baseline: Mapping[str, Any],
73
+ target: Mapping[str, Any],
74
+ *,
75
+ reduction_fraction: float = 0.5,
76
+ ) -> tuple[bool, str]:
77
+ """
78
+ AC-2: target must achieve >= reduction_fraction lower cache_read_tokens
79
+ vs baseline when run_class_hash matches. Otherwise TOKEN_COST_RUN_CLASS_MISMATCH.
80
+ """
81
+ hb = baseline.get("run_class_hash")
82
+ ht = target.get("run_class_hash")
83
+ if not isinstance(hb, str) or not isinstance(ht, str) or hb != ht:
84
+ return False, "TOKEN_COST_RUN_CLASS_MISMATCH: run_class_hash differs or missing"
85
+
86
+ tb = baseline.get("totals") or {}
87
+ tt = target.get("totals") or {}
88
+ if not isinstance(tb, Mapping) or not isinstance(tt, Mapping):
89
+ return False, "TOKEN_COST_RUN_CLASS_MISMATCH: totals object missing"
90
+
91
+ br = tb.get("cache_read_tokens")
92
+ tr = tt.get("cache_read_tokens")
93
+ if not isinstance(br, int) or not isinstance(tr, int) or br < 0 or tr < 0:
94
+ return False, "TOKEN_COST_RUN_CLASS_MISMATCH: invalid cache_read_tokens"
95
+
96
+ if br == 0:
97
+ if tr == 0:
98
+ return True, "ok: baseline and target zero cache_read_tokens"
99
+ return False, "TOKEN_COST_RUN_CLASS_MISMATCH: baseline zero but target non-zero"
100
+
101
+ max_target = int(br * (1.0 - reduction_fraction))
102
+ if tr > max_target:
103
+ return (
104
+ False,
105
+ f"TOKEN_COST_RUN_CLASS_MISMATCH: cache_read_tokens {tr} exceeds "
106
+ f"50% reduction threshold (baseline {br}, max_target {max_target})",
107
+ )
108
+ return True, "ok: cache_read_tokens meets 50% reduction vs baseline"