Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions graphify/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -978,10 +978,13 @@ def _zero_node_stamped_semantic_sources(
return healed


def _record_extract_cost(graphify_out: Path, input_tokens: int, output_tokens: int, files: int) -> None:
def _record_extract_cost(graphify_out: Path, input_tokens: int, output_tokens: int, files: int,
command: str = "extract") -> bool:
"""Append this run's token usage to graphify-out/cost.json, the same ledger the
skill writes, so `graphify extract` refreshes are counted too (#1769). An
unreadable ledger is left alone rather than replaced with one run."""
skill writes, so `graphify extract` refreshes are counted too (#1769), and so
are `cluster-only`/`label` community-labeling calls (#3658). An unreadable
ledger is left alone rather than replaced with one run. Returns whether the
run was written."""
from datetime import datetime, timezone
from graphify.paths import write_json_atomic

Expand All @@ -998,8 +1001,8 @@ def _record_extract_cost(graphify_out: Path, input_tokens: int, output_tokens: i
):
raise ValueError("unexpected layout")
except (OSError, ValueError, AttributeError) as exc:
print(f"[graphify extract] warning: could not read {cost_path}, not updating it: {exc}", file=sys.stderr)
return
print(f"[graphify {command}] warning: could not read {cost_path}, not updating it: {exc}", file=sys.stderr)
return False
cost["runs"].append({
"date": datetime.now(timezone.utc).isoformat(),
"input_tokens": input_tokens,
Expand All @@ -1011,7 +1014,9 @@ def _record_extract_cost(graphify_out: Path, input_tokens: int, output_tokens: i
try:
write_json_atomic(cost_path, cost, indent=2, ensure_ascii=False)
except OSError as exc:
print(f"[graphify extract] warning: could not write {cost_path}: {exc}", file=sys.stderr)
print(f"[graphify {command}] warning: could not write {cost_path}: {exc}", file=sys.stderr)
return False
return True


def _prune_graph_json_sources(graph_path: Path, stale_sources: list[str]) -> int:
Expand Down Expand Up @@ -3391,6 +3396,15 @@ def dispatch_command(cmd: str) -> None:
from graphify.export import backup_if_protected as _backup
from graphify.exporters.html import _HTML_STALE_MARKER
_backup(out)
# Labeling calls go into the cost.json ledger now, after the snapshot and
# before the #479 guard below: the tokens are spent whether or not
# graph.json is written, and a later `graphify update` counts them too.
recorded = True
if label_token_usage["input"] or label_token_usage["output"]:
print(f"[graphify {cmd}] labeling tokens: "
f"{label_token_usage['input']:,} in / {label_token_usage['output']:,} out")
recorded = _record_extract_cost(out, label_token_usage["input"],
label_token_usage["output"], 0, command=cmd)
html_stale_marker = out / _HTML_STALE_MARKER

def _clear_html_stale_marker() -> None:
Expand Down Expand Up @@ -3422,7 +3436,14 @@ def _clear_html_stale_marker() -> None:
file=sys.stderr,
)
sys.exit(1)
tokens = label_token_usage
# The report's token cost is the cost.json ledger, as `graphify update`
# already reports it (#5154). Reporting only this run's labeling usage
# showed "0 input · 0 output" after a paid `extract` (#3658). If the
# ledger couldn't take the labeling run, this report still adds it.
from graphify.report import load_report_token_cost as _lrtc
tokens = _lrtc(out)
if not recorded:
tokens = {k: tokens[k] + label_token_usage[k] for k in ("input", "output")}
from graphify.report import load_learning_for_report as _llfr
report = generate(G, communities, cohesion, labels, gods, surprises,
{"warning": "cluster-only mode — file stats not available"},
Expand Down
3 changes: 2 additions & 1 deletion graphify/skill-aider.md
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,8 @@ G = json_graph.node_link_graph(data, edges='links')

detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
'files': {'code': [], 'document': [], 'paper': []}}
tokens = {'input': 0, 'output': 0}
from graphify.report import load_report_token_cost
tokens = load_report_token_cost(Path('graphify-out'))

communities = cluster(G)
cohesion = score_all(G, communities)
Expand Down
3 changes: 2 additions & 1 deletion graphify/skill-devin.md
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,8 @@ G = json_graph.node_link_graph(data, edges='links')

detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
'files': {'code': [], 'document': [], 'paper': []}}
tokens = {'input': 0, 'output': 0}
from graphify.report import load_report_token_cost
tokens = load_report_token_cost(Path('graphify-out'))

communities = cluster(G)
cohesion = score_all(G, communities)
Expand Down
147 changes: 147 additions & 0 deletions tests/test_labeling.py
Original file line number Diff line number Diff line change
Expand Up @@ -1060,3 +1060,150 @@ def fake_generate(G, communities, *, backend=None, model=None, gods=None,
assert labels["0"] == "Order Management" # real name survives
assert labels["5"] == "PaymentService" # sentinel echo dropped -> hub label
assert labels["7"] == "ShippingService" # bare-key echo dropped -> hub label


def _write_cost_ledger(out, input_tokens, output_tokens):
(out / "cost.json").write_text(json.dumps({
"runs": [{"date": "2026-11-21T00:00:00+00:00", "input_tokens": input_tokens,
"output_tokens": output_tokens, "files": 3}],
"total_input_tokens": input_tokens,
"total_output_tokens": output_tokens,
}), encoding="utf-8")


def test_cluster_only_reports_cost_json_totals(tmp_path, monkeypatch):
"""#3658: after a paid `extract`, cluster-only wrote "Token cost: 0 input ·
0 output" (only its own labeling usage) while `graphify update` on the same
folder reports the cost.json totals (#5154)."""
import graphify.__main__ as cli

out = tmp_path / "graphify-out"
out.mkdir()
_two_community_graph(out)
_write_cost_ledger(out, 12000, 3400)
monkeypatch.setattr(cli, "_check_skill_version", lambda _: None)
monkeypatch.setattr(
sys, "argv", ["graphify", "cluster-only", str(tmp_path), "--no-label", "--no-viz"],
)

cli.main()

report = (out / "GRAPH_REPORT.md").read_text(encoding="utf-8")
assert "Token cost: 12,000 input · 3,400 output" in report
# No labeling call was made, so nothing is added to the ledger.
ledger = json.loads((out / "cost.json").read_text(encoding="utf-8"))
assert len(ledger["runs"]) == 1
assert (ledger["total_input_tokens"], ledger["total_output_tokens"]) == (12000, 3400)


def test_label_adds_labeling_usage_to_cost_json(tmp_path, monkeypatch):
"""#3658: labeling tokens go into the ledger, so this report and a later
`graphify update` both count them."""
import graphify.__main__ as cli

out = tmp_path / "graphify-out"
out.mkdir()
_two_community_graph(out)
_write_cost_ledger(out, 12000, 3400)

def fake_generate(G, communities, *, backend=None, model=None, gods=None,
quiet=False, max_concurrency=4, batch_size=100, usage_out=None):
usage_out["input"] += 100
usage_out["output"] += 10
return {cid: f"Fresh community {cid}" for cid in communities}, "llm"

monkeypatch.setattr(cli, "_check_skill_version", lambda _: None)
monkeypatch.setattr("graphify.llm.generate_community_labels", fake_generate)
monkeypatch.setattr(
sys, "argv", ["graphify", "label", str(tmp_path), "--backend", "gemini", "--no-viz"],
)

cli.main()

ledger = json.loads((out / "cost.json").read_text(encoding="utf-8"))
assert (ledger["total_input_tokens"], ledger["total_output_tokens"]) == (12100, 3410)
assert ledger["runs"][-1]["input_tokens"] == 100
assert ledger["runs"][-1]["output_tokens"] == 10
report = (out / "GRAPH_REPORT.md").read_text(encoding="utf-8")
assert "Token cost: 12,100 input · 3,410 output" in report


def test_label_reports_its_usage_when_the_ledger_is_unreadable(tmp_path, monkeypatch):
"""#3658 review: a damaged cost.json can't take the labeling run, but this
report must still show the tokens the run spent, and the file is left alone."""
import graphify.__main__ as cli

out = tmp_path / "graphify-out"
out.mkdir()
_two_community_graph(out)
(out / "cost.json").write_text("{not json", encoding="utf-8")

def fake_generate(G, communities, *, backend=None, model=None, gods=None,
quiet=False, max_concurrency=4, batch_size=100, usage_out=None):
usage_out["input"] += 100
usage_out["output"] += 10
return {cid: f"Fresh community {cid}" for cid in communities}, "llm"

monkeypatch.setattr(cli, "_check_skill_version", lambda _: None)
monkeypatch.setattr("graphify.llm.generate_community_labels", fake_generate)
monkeypatch.setattr(
sys, "argv", ["graphify", "label", str(tmp_path), "--backend", "gemini", "--no-viz"],
)

cli.main()

report = (out / "GRAPH_REPORT.md").read_text(encoding="utf-8")
assert "Token cost: 100 input · 10 output" in report
assert (out / "cost.json").read_text(encoding="utf-8") == "{not json"


def test_label_records_its_usage_even_when_graph_json_is_refused(tmp_path, monkeypatch, capsys):
"""#3658 review: the labeling tokens are spent before the #479 guard can
refuse to write graph.json, so they reach the ledger even then."""
import graphify.__main__ as cli

out = tmp_path / "graphify-out"
out.mkdir()
_two_community_graph(out)
_write_cost_ledger(out, 12000, 3400)

def fake_generate(G, communities, *, backend=None, model=None, gods=None,
quiet=False, max_concurrency=4, batch_size=100, usage_out=None):
usage_out["input"] += 100
usage_out["output"] += 10
return {cid: f"Fresh community {cid}" for cid in communities}, "llm"

monkeypatch.setattr(cli, "_check_skill_version", lambda _: None)
monkeypatch.setattr("graphify.llm.generate_community_labels", fake_generate)
monkeypatch.setattr("graphify.export.to_json", lambda *args, **kwargs: False)
monkeypatch.setattr(
sys, "argv", ["graphify", "label", str(tmp_path), "--backend", "gemini", "--no-viz"],
)

with pytest.raises(SystemExit):
cli.main()

ledger = json.loads((out / "cost.json").read_text(encoding="utf-8"))
assert (ledger["total_input_tokens"], ledger["total_output_tokens"]) == (12100, 3410)
assert "labeling tokens: 100 in / 10 out" in capsys.readouterr().out
assert not (out / "GRAPH_REPORT.md").exists()


def test_cluster_only_without_ledger_reports_zero_and_creates_none(tmp_path, monkeypatch):
"""No cost.json and no labeling call: the report stays at zero and no ledger
is invented."""
import graphify.__main__ as cli

out = tmp_path / "graphify-out"
out.mkdir()
_two_community_graph(out)
monkeypatch.setattr(cli, "_check_skill_version", lambda _: None)
monkeypatch.setattr(
sys, "argv", ["graphify", "cluster-only", str(tmp_path), "--no-label", "--no-viz"],
)

cli.main()

report = (out / "GRAPH_REPORT.md").read_text(encoding="utf-8")
assert "Token cost: 0 input · 0 output" in report
assert not (out / "cost.json").exists()
15 changes: 15 additions & 0 deletions tests/test_skillgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,21 @@ def test_monoliths_change_only_sanctioned_lines():
assert UNIFIED_DESCRIPTION in rendered


def test_monoliths_read_the_cost_ledger_in_cluster_only():
"""#3658: the aider/devin --cluster-only script reports the cost.json totals.

The round-trip only forbids unsanctioned drift, so this asserts the fix is
actually applied: the hard-coded zero is gone and the ledger is read.
"""
platforms = gen.load_platforms()
for key in ("aider", "devin"):
rendered = gen.render(platforms[key])[0].content
section = rendered[rendered.index("## For --cluster-only"):]
section = section[:section.index("\n## ", 1)]
assert "tokens = load_report_token_cost(Path('graphify-out'))" in section
assert "tokens = {'input': 0, 'output': 0}" not in section


def test_monoliths_carry_the_1392_runbook_fixes():
"""The four #1392 data-loss/correctness fixes are present in both monoliths.

Expand Down
3 changes: 2 additions & 1 deletion tools/skillgen/expected/graphify__skill-aider.md
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,8 @@ G = json_graph.node_link_graph(data, edges='links')

detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
'files': {'code': [], 'document': [], 'paper': []}}
tokens = {'input': 0, 'output': 0}
from graphify.report import load_report_token_cost
tokens = load_report_token_cost(Path('graphify-out'))

communities = cluster(G)
cohesion = score_all(G, communities)
Expand Down
3 changes: 2 additions & 1 deletion tools/skillgen/expected/graphify__skill-devin.md
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,8 @@ G = json_graph.node_link_graph(data, edges='links')

detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
'files': {'code': [], 'document': [], 'paper': []}}
tokens = {'input': 0, 'output': 0}
from graphify.report import load_report_token_cost
tokens = load_report_token_cost(Path('graphify-out'))

communities = cluster(G)
cohesion = score_all(G, communities)
Expand Down
3 changes: 2 additions & 1 deletion tools/skillgen/fragments/core/aider.md
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,8 @@ G = json_graph.node_link_graph(data, edges='links')

detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
'files': {'code': [], 'document': [], 'paper': []}}
tokens = {'input': 0, 'output': 0}
from graphify.report import load_report_token_cost
tokens = load_report_token_cost(Path('graphify-out'))

communities = cluster(G)
cohesion = score_all(G, communities)
Expand Down
3 changes: 2 additions & 1 deletion tools/skillgen/fragments/core/devin.md
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,8 @@ G = json_graph.node_link_graph(data, edges='links')

detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
'files': {'code': [], 'document': [], 'paper': []}}
tokens = {'input': 0, 'output': 0}
from graphify.report import load_report_token_cost
tokens = load_report_token_cost(Path('graphify-out'))

communities = cluster(G)
cohesion = score_all(G, communities)
Expand Down
19 changes: 18 additions & 1 deletion tools/skillgen/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -1456,6 +1456,21 @@ def _is_cloud_cta_section_line(line: str) -> bool:
)


def _is_cluster_only_ledger_fix_line(line: str) -> bool:
"""Whether a line is the aider/devin --cluster-only token-cost fix (#3658).

The monoliths' own --cluster-only script passed a hard-coded zero to
``generate()``, so after a paid extract the report said "0 input · 0 output"
while `graphify update` reports the cost.json totals (#5154). The zero line
is removed and the ledger read is added, as the CLI's cluster-only does.
"""
return line.strip() in {
"tokens = {'input': 0, 'output': 0}",
"from graphify.report import load_report_token_cost",
"tokens = load_report_token_cost(Path('graphify-out'))",
}


_MCP_TOOLS_LINE = (
"This starts a stdio MCP server that exposes tools: {tools}. Add to Claude Desktop"
" or any MCP-compatible agent orchestrator so other agents can query the graph live."
Expand Down Expand Up @@ -1506,6 +1521,7 @@ def _is_get_section_tool_line(line: str) -> bool:
_is_when_to_build_guidance_line,
_is_hub_bypass_check_fix_line,
_is_get_section_tool_line,
_is_cluster_only_ledger_fix_line,
)


Expand All @@ -1524,7 +1540,8 @@ def monolith_roundtrip(platform: Platform) -> list[str]:
unification, the unified frontmatter description, the chunk-cleanup rewrite
(#1172), the four #1392 runbook fixes (directed propagation, content-only
semantic scope, stale-cache unlink, and the zero-node/shrink-guard ordering),
semantic-cache source scoping (#1757), and the hub bypass check (#4426).
semantic-cache source scoping (#1757), the hub bypass check (#4426), and the
--cluster-only ledger read (#3658).

The comparison is a multiset diff, not a positional zip: a line whose text is
unchanged but merely *moved* (the report-write line shifted below ``to_json``
Expand Down
Loading