ccstats 0.4.0

Fast token and cost usage statistics CLI for Claude Code, OpenAI Codex, Cursor, Grok, and Kimi Code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
"""Shared deterministic helpers for SpecRail checks.

This module intentionally avoids third-party dependencies so the default pack
can validate in a fresh repository checkout.
"""

from __future__ import annotations

import json
import re
import hashlib
from dataclasses import dataclass
from pathlib import Path
from typing import Any


DECISIONS = {"allowed", "warn", "needs_human", "blocked"}
TERMINAL_BLOCKING_STATES = {
    "abandoned",
    "duplicate",
    "reserved_internal",
    "security_private",
}


class SpecRailError(ValueError):
    """Raised when SpecRail configuration or evidence is malformed."""


@dataclass(frozen=True)
class PackConfig:
    repo: Path
    workflow: dict[str, Any]
    states: dict[str, Any]
    labels: dict[str, Any]


def read_text(path: Path) -> str:
    try:
        return path.read_text(encoding="utf-8")
    except OSError as exc:
        raise SpecRailError(f"cannot read {path}: {exc}") from exc


def parse_scalar(value: str) -> Any:
    value = value.strip()
    if value in {"true", "True"}:
        return True
    if value in {"false", "False"}:
        return False
    if value in {"null", "None", "~"}:
        return None
    if value == "[]":
        return []
    if value.startswith("[") and value.endswith("]"):
        inner = value[1:-1].strip()
        if not inner:
            return []
        return [parse_scalar(item.strip()) for item in inner.split(",")]
    if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
        return value[1:-1]
    if re.fullmatch(r"-?[0-9]+", value):
        return int(value)
    return value


def _significant_lines(text: str) -> list[tuple[int, str]]:
    lines: list[tuple[int, str]] = []
    for raw in text.splitlines():
        if not raw.strip() or raw.lstrip().startswith("#"):
            continue
        indent = len(raw) - len(raw.lstrip(" "))
        lines.append((indent, raw.strip()))
    return lines


def parse_yaml_subset(text: str) -> Any:
    """Parse the small YAML subset used by SpecRail config files.

    Supported constructs: nested mappings, lists of scalars, booleans, nulls,
    and integers. This is not a general YAML parser.
    """

    lines = _significant_lines(text)

    def parse_block(index: int, indent: int) -> tuple[Any, int]:
        if index >= len(lines):
            return {}, index
        container: Any = [] if lines[index][1].startswith("- ") else {}

        while index < len(lines):
            line_indent, content = lines[index]
            if line_indent < indent:
                break
            if line_indent > indent:
                raise SpecRailError(f"unexpected indent near: {content}")

            if isinstance(container, list):
                if not content.startswith("- "):
                    break
                item = content[2:].strip()
                if not item:
                    child, index = parse_block(index + 1, indent + 2)
                    container.append(child)
                else:
                    container.append(parse_scalar(item))
                    index += 1
                continue

            if content.startswith("- "):
                break
            key, sep, value = content.partition(":")
            if not sep:
                raise SpecRailError(f"expected key/value near: {content}")
            key = key.strip()
            value = value.strip()
            if value:
                container[key] = parse_scalar(value)
                index += 1
                continue
            if index + 1 < len(lines) and lines[index + 1][0] > line_indent:
                child, index = parse_block(index + 1, lines[index + 1][0])
                container[key] = child
            else:
                container[key] = {}
                index += 1
        return container, index

    parsed, end = parse_block(0, lines[0][0] if lines else 0)
    if end != len(lines):
        raise SpecRailError(f"could not parse YAML near: {lines[end][1]}")
    return parsed


def load_yaml_file(path: Path) -> Any:
    return parse_yaml_subset(read_text(path))


def load_pack(repo: Path) -> PackConfig:
    repo = repo.resolve()
    return PackConfig(
        repo=repo,
        workflow=load_yaml_file(repo / "workflow.yaml"),
        states=load_yaml_file(repo / "states.yaml"),
        labels=load_yaml_file(repo / "labels.yaml"),
    )


def state_map(config: PackConfig) -> dict[str, Any]:
    states = config.states.get("states")
    if not isinstance(states, dict):
        raise SpecRailError("states.yaml must contain a states mapping")
    return states


def label_groups(config: PackConfig) -> dict[str, list[str]]:
    labels = config.labels.get("labels")
    if not isinstance(labels, dict):
        raise SpecRailError("labels.yaml must contain a labels mapping")
    groups: dict[str, list[str]] = {}
    for group, values in labels.items():
        groups[group] = [str(value) for value in values] if isinstance(values, list) else []
    return groups


def action_policy(config: PackConfig) -> dict[str, Any]:
    policy = config.workflow.get("action_policy", {})
    actions = policy.get("actions", {}) if isinstance(policy, dict) else {}
    if not isinstance(actions, dict):
        raise SpecRailError("workflow.yaml action_policy.actions must be a mapping")
    return actions


def artifact_templates(config: PackConfig) -> dict[str, str]:
    artifacts = config.workflow.get("artifacts", {})
    if not isinstance(artifacts, dict):
        raise SpecRailError("workflow.yaml artifacts must be a mapping")
    return {str(key): str(value) for key, value in artifacts.items()}


def work_id_for_issue(issue: int | None) -> str | None:
    if issue is None:
        return None
    return f"GH{issue}"


def render_artifact_path(config: PackConfig, artifact: str, issue: int | None) -> str | None:
    template = artifact_templates(config).get(artifact)
    if not template:
        return None
    if issue is None:
        return template
    return (
        template.replace("{issue_number}", str(issue))
        .replace("{work_id}", work_id_for_issue(issue) or "")
    )


def infer_state(config: PackConfig, state: str | None, labels: list[str]) -> tuple[str | None, list[str]]:
    if state:
        return state, [f"state provided explicitly: {state}"]

    known_states = set(state_map(config))
    label_set = {label.strip() for label in labels if label.strip()}
    matches = sorted(label_set & known_states)
    if len(matches) == 1:
        return matches[0], [f"state inferred from label: {matches[0]}"]
    if len(matches) > 1:
        raise SpecRailError(f"conflicting state labels: {', '.join(matches)}")
    return None, []


def validate_state_graph(config: PackConfig) -> list[str]:
    errors: list[str] = []
    states = state_map(config)
    for name, body in states.items():
        if not isinstance(body, dict):
            errors.append(f"states.yaml: state {name} must be a mapping")
            continue
        if "owner" not in body:
            errors.append(f"states.yaml: state {name} missing owner")
        next_states = body.get("next", [])
        if body.get("terminal") is True and next_states:
            errors.append(f"states.yaml: terminal state {name} must not define next")
        if next_states and not isinstance(next_states, list):
            errors.append(f"states.yaml: state {name} next must be a list")
            continue
        for next_state in next_states:
            if str(next_state) not in states:
                errors.append(f"states.yaml: state {name} references unknown next state {next_state}")
    return errors


def validate_labels(config: PackConfig) -> list[str]:
    errors: list[str] = []
    states = set(state_map(config))
    groups = label_groups(config)
    for required_group in ["readiness", "outcome", "review"]:
        if required_group not in groups:
            errors.append(f"labels.yaml: missing label group {required_group}")
    for state in ["needs_info", "triaged", "ready_to_spec", "ready_to_implement"]:
        if state not in groups.get("readiness", []):
            errors.append(f"labels.yaml: readiness labels missing {state}")
    for label in groups.get("readiness", []) + groups.get("outcome", []):
        if label not in states and label not in {"merged"}:
            errors.append(f"labels.yaml: label {label} is not a known state or allowed outcome")
    return errors


def validate_action_policy(config: PackConfig) -> list[str]:
    errors: list[str] = []
    states = set(state_map(config))
    actions = action_policy(config)
    for route in ["triage_issue", "write_spec", "implement", "review_pr", "fix_ci", "draft_release_note"]:
        if route not in actions:
            errors.append(f"workflow.yaml: action_policy missing route {route}")
    for route, body in actions.items():
        if not isinstance(body, dict):
            errors.append(f"workflow.yaml: action {route} must be a mapping")
            continue
        allowed_from = body.get("allowed_from", [])
        if not isinstance(allowed_from, list):
            errors.append(f"workflow.yaml: action {route} allowed_from must be a list")
            continue
        for state in allowed_from:
            if str(state) not in states:
                errors.append(f"workflow.yaml: action {route} references unknown state {state}")
    return errors


def validate_template_parity(repo: Path) -> list[str]:
    errors: list[str] = []
    root = repo / "templates"
    zh = root / "zh-CN"
    base_files = sorted(path.name for path in root.glob("*.md"))
    zh_files = sorted(path.name for path in zh.glob("*.md")) if zh.is_dir() else []
    for name in base_files:
        if name not in zh_files:
            errors.append(f"templates/zh-CN: missing localized template {name}")
    for name in zh_files:
        if name not in base_files:
            errors.append(f"templates/zh-CN/{name}: no matching base template")
    stable_tokens = ["GH-", "ready_to_spec", "ready_to_implement"]
    for name in ["issue_feature.md", "product_spec.md", "tech_spec.md", "pull_request.md"]:
        for rel in [Path("templates") / name, Path("templates/zh-CN") / name]:
            path = repo / rel
            if not path.is_file():
                continue
            text = read_text(path)
            for token in stable_tokens:
                if token in read_text(repo / "templates" / name) and token not in text:
                    errors.append(f"{rel}: missing stable token {token}")
    return errors


def validate_json_schemas(repo: Path) -> list[str]:
    errors: list[str] = []
    schema_dir = repo / "schemas"
    if not schema_dir.is_dir():
        return ["missing schemas/ directory"]
    for path in sorted(schema_dir.glob("*.schema.json")):
        try:
            data = json.loads(read_text(path))
        except json.JSONDecodeError as exc:
            errors.append(f"{path.relative_to(repo)}: invalid JSON: {exc.msg}")
            continue
        if "$schema" not in data:
            errors.append(f"{path.relative_to(repo)}: missing $schema")
        if "title" not in data:
            errors.append(f"{path.relative_to(repo)}: missing title")
        if data.get("type") != "object":
            errors.append(f"{path.relative_to(repo)}: top-level type must be object")
    return errors


def _frontmatter(text: str) -> dict[str, str] | None:
    if not text.startswith("---\n"):
        return None
    end = text.find("\n---\n", 4)
    if end < 0:
        return None
    raw = text[4:end]
    metadata: dict[str, str] = {}
    for line in raw.splitlines():
        key, sep, value = line.partition(":")
        if not sep:
            return None
        metadata[key.strip()] = value.strip()
    return metadata


def _sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def validate_skills_lock(repo: Path) -> list[str]:
    """Validate repo-distributed SpecRail skills and their lockfile."""

    errors: list[str] = []
    lock_path = repo / "skills-lock.json"
    if not lock_path.is_file():
        return ["missing required file: skills-lock.json"]
    try:
        lock = json.loads(read_text(lock_path))
    except json.JSONDecodeError as exc:
        return [f"skills-lock.json: invalid JSON: {exc.msg}"]
    if not isinstance(lock, dict):
        return ["skills-lock.json: top-level value must be an object"]

    if lock.get("version") != 1:
        errors.append("skills-lock.json: version must be 1")
    if lock.get("algorithm") != "sha256":
        errors.append("skills-lock.json: algorithm must be sha256")

    skills = lock.get("skills")
    if not isinstance(skills, list) or not skills:
        errors.append("skills-lock.json: skills must be a non-empty list")
        return errors

    seen_names: set[str] = set()
    seen_paths: set[str] = set()
    paths: list[str] = []
    for index, item in enumerate(skills, start=1):
        if not isinstance(item, dict):
            errors.append(f"skills-lock.json: skill #{index} must be an object")
            continue
        name = item.get("name")
        rel_path = item.get("path")
        digest = item.get("computedHash")
        if not isinstance(name, str) or not name.strip():
            errors.append(f"skills-lock.json: skill #{index} missing name")
            continue
        if not isinstance(rel_path, str) or not rel_path.strip():
            errors.append(f"skills-lock.json: skill {name} missing path")
            continue
        if name in seen_names:
            errors.append(f"skills-lock.json: duplicate skill name {name}")
        if rel_path in seen_paths:
            errors.append(f"skills-lock.json: duplicate skill path {rel_path}")
        seen_names.add(name)
        seen_paths.add(rel_path)
        paths.append(rel_path)

        path = Path(rel_path)
        if path.is_absolute() or ".." in path.parts:
            errors.append(f"skills-lock.json: skill {name} path must be repo-relative")
            continue
        if path.parts[:1] != ("skills",) or path.name != "SKILL.md":
            errors.append(f"skills-lock.json: skill {name} path must be skills/<name>/SKILL.md")
            continue
        if len(path.parts) != 3 or path.parts[1] != name:
            errors.append(f"skills-lock.json: skill {name} path must match its name")

        skill_path = repo / path
        if not skill_path.is_file():
            errors.append(f"skills-lock.json: skill file does not exist: {rel_path}")
            continue
        text = read_text(skill_path)
        metadata = _frontmatter(text)
        if metadata is None:
            errors.append(f"{rel_path}: missing YAML frontmatter")
        else:
            if set(metadata) != {"name", "description"}:
                errors.append(f"{rel_path}: frontmatter must contain only name and description")
            if metadata.get("name") != name:
                errors.append(f"{rel_path}: frontmatter name must be {name}")
            if not metadata.get("description"):
                errors.append(f"{rel_path}: description must not be empty")
        if not isinstance(digest, str) or not digest.startswith("sha256:"):
            errors.append(f"skills-lock.json: skill {name} computedHash must start with sha256:")
        elif digest.removeprefix("sha256:") != _sha256_file(skill_path):
            errors.append(f"skills-lock.json: skill {name} computedHash mismatch")

    if paths != sorted(paths):
        errors.append("skills-lock.json: skills must be sorted by path")

    skill_files = {
        str(path.relative_to(repo))
        for path in sorted((repo / "skills").glob("specrail-*/SKILL.md"))
    }
    missing_from_lock = sorted(skill_files - seen_paths)
    extra_in_lock = sorted(
        path for path in seen_paths if path.startswith("skills/specrail-") and path not in skill_files
    )
    for rel_path in missing_from_lock:
        errors.append(f"skills-lock.json: missing skill file {rel_path}")
    for rel_path in extra_in_lock:
        errors.append(f"skills-lock.json: locked skill file missing from repo {rel_path}")
    return errors