agent-manifesto-kit 1.3.0 → 1.5.0

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/README.md CHANGED
@@ -23,6 +23,31 @@ Or run directly with `npx`:
23
23
  npx agent-manifesto-kit list
24
24
  ```
25
25
 
26
+ ## Update
27
+
28
+ Update the global CLI and its bundled catalog to the latest published npm version:
29
+
30
+ ```bash
31
+ agentkit update
32
+ agentkit --version
33
+ ```
34
+
35
+ The command runs `npm install --global agent-manifesto-kit@latest`, using your active npm
36
+ configuration and installation prefix. It takes no arguments, streams npm output and returns
37
+ nonzero if npm cannot start, fails or is interrupted. npm must be on `PATH`, with network
38
+ access and permission to write its global installation directory.
39
+
40
+ `update` always targets the global npm installation, including when invoked from a source
41
+ checkout or through `npx`. To use the latest version without a global installation, run
42
+ `npx agent-manifesto-kit@latest <command>`. Versions without `update` can use the npm install
43
+ command above. See [npm install](https://docs.npmjs.com/cli/v11/commands/npm-install/).
44
+
45
+ Refresh previously synced project capabilities separately, from each project:
46
+
47
+ ```bash
48
+ agentkit sync
49
+ ```
50
+
26
51
  ## Quick Start
27
52
 
28
53
  List available capabilities:
@@ -57,12 +82,26 @@ Keep skills and agents synced into both Claude and Codex locations of a project:
57
82
  agentkit sync blender-3d brainstorm --provider claude,codex
58
83
  ```
59
84
 
85
+ The [Blender bundle](collection/bundles/blender-3d/README.md) includes Quick, Standard and
86
+ Production workflows, compact create/fix handoffs and per-phase usage records. Start with
87
+ `blender-asset`; animation and export checks are optional additions to the selected profile.
88
+
89
+ Get retro suggestions after significant sessions (optional Stop-hook nudge for both tools):
90
+
91
+ ```bash
92
+ agentkit sync session-retro --provider claude,codex
93
+ python3 .claude/skills/session-retro/scripts/install_hooks.py
94
+ ```
95
+
60
96
  Adopt a single skill for Codex:
61
97
 
62
98
  ```bash
63
99
  agentkit adopt brainstorm --provider codex
64
100
  ```
65
101
 
102
+ `--provider=codex` is equivalent. Bare `provider=codex`, missing option values and unknown
103
+ adoption options are rejected before any files are copied.
104
+
66
105
  Adopt into a specific project directory:
67
106
 
68
107
  ```bash
@@ -89,6 +128,7 @@ such as templates, under `.claude/<bundle-name>/`.
89
128
  ## Commands
90
129
 
91
130
  ```bash
131
+ agentkit update
92
132
  agentkit list [skills|agents|bundles]
93
133
  agentkit lint [name]
94
134
  agentkit adopt <name> [--provider claude|codex|agnostic] [--dest <dir>] [--force] [--cli <cli>]
@@ -100,6 +140,7 @@ Command summary:
100
140
 
101
141
  | Command | Description |
102
142
  | --- | --- |
143
+ | `agentkit update` | Install the latest published CLI and catalog globally through npm |
103
144
  | `agentkit list [skills|agents|bundles]` | Show the full catalog or one selected view; bundle views include item summaries |
104
145
  | `agentkit lint [name]` | Check all capabilities, or one named capability, for provider-specific tokens |
105
146
  | `agentkit adopt <name>` | Copy a capability or bundle into your project |
@@ -1,41 +1,138 @@
1
1
  # Blender 3D
2
2
 
3
- Build low-poly game models in Blender that match a reference sheet, then retarget library motion
4
- onto them and export clips a game engine plays correctly, using measured comparisons and an
5
- independent visual review instead of guesswork.
3
+ A portable Blender asset workflow with effort matched to the task. Use the same bundle for a
4
+ small prop, a reference-matched game asset, or a complex model with animation and engine checks.
6
5
 
7
- ## Contents
6
+ ## Profiles
8
7
 
9
- | Item | Type | Purpose | Depends on |
10
- | --- | --- | --- | --- |
11
- | `blender-reference-model` | skill | Scripted modeling against a reference: measure, render at the reference scale, compare, zoom, calibrate colours, check meshes | `visual-reviewer` |
12
- | `blender-mocap-retarget` | skill | Rig, skin and retarget a source clip onto an existing character; motion QA; single-clip glTF export; re-import and Godot checks | `blender-reference-model` scripts, `visual-reviewer` |
13
- | `visual-reviewer` | agent | Fresh-context review of comparison sheets and motion contact sheets; at most five ranked findings | — |
8
+ | Profile | Typical work | Sequence | Independent review | Repair ceiling |
9
+ | --- | --- | --- | --- | --- |
10
+ | Quick | Simple prop, prototype, material/origin edit, isolated repair | Build → relevant technical checks → affected views → delivery | When requested or materially uncertain | 1 |
11
+ | Standard | Reference matching, modular asset, ordinary game-ready delivery | Proportions → build → comparison if applicable → technical checks → delivery | Required when requested or identity/acceptance remains uncertain | 2 |
12
+ | Production | Strict fidelity, complex assembly, critical deformation, dependent deliverables | Acceptance/blockout checkpoint → refine → technical gates → review → delivery | One fresh-context reviewer required | 3 |
14
13
 
15
- ## Requirements
14
+ Each row permits focused fixes within its ceiling, followed by affected checks. Missing required
15
+ checks or review blocks acceptance. Optional taste changes do not force more rounds. Animation,
16
+ retargeting and engine export add their own criteria to any profile; they do not restart modeling.
17
+ The calling agent chooses the smallest suitable profile and records why. Project budgets may
18
+ set an explicit initial ceiling; later increases require a user decision.
16
19
 
17
- - Blender run headless: `blender -b model.blend --python script.py -- args` (tested on 5.2; 4.2+ expected)
18
- - System Python 3 with Pillow and numpy for the image scripts
19
- - Optional: Godot 4 on `PATH` (or `GODOT=/path/to/godot`) for `godot_verify.py`
20
- - For Codex, the reviewer agent needs image viewing available in its session; if it is not,
21
- the skills report that the independent review could not run
20
+ ## Contents
22
21
 
23
- Record your Blender and engine executable paths in your project's instruction file, so agents
24
- don't have to search for them.
22
+ | Item | Purpose |
23
+ | --- | --- |
24
+ | `blender-asset` skill | Entry capability for a build or focused revision, with or without a reference |
25
+ | `blender-asset/workflows/asset.yml` | Declarative profile selection, stage sequencing, review and completion rules |
26
+ | `blender-asset/scripts/task_state.py` | Compact task handoff, file-dependent evidence and repair reservations |
27
+ | `blender-asset/scripts/record_run.py` | Per-phase usage journal with parent/child identities and unknown-value coverage |
28
+ | `blender-reference-model` skill and scripts | Measurements, matched renders, identity details and mesh diagnostics |
29
+ | `blender-mocap-retarget` skill and scripts | Appearance preservation, source-motion comparison, motion and export checks |
30
+ | `visual-reviewer` agent | Read-only image review with at most five ranked findings |
25
31
 
26
- ## Install
32
+ The complete bundle is the supported installation unit. The YAML is read by the calling agent;
33
+ it is not an executable orchestrator. No always-on hooks, automatic teams or fixed model presets
34
+ are installed. Machine paths, model/effort preferences, task state and usage logs belong in the
35
+ consumer project, outside the synced skill directories.
27
36
 
28
- The bundle has only skills and an agent, so sync is enough and keeps both tools up to date:
37
+ ## Install and requirements
29
38
 
30
39
  ```bash
31
40
  agentkit sync blender-3d --provider claude,codex
32
41
  ```
33
42
 
34
- Use `agentkit adopt blender-3d --provider <provider>` instead for a one-off copy you intend to
35
- edit locally.
43
+ Sync copies skills, their nested workflow/scripts and the agent. It preserves local edits under
44
+ the normal sync conflict rules. Use `agentkit adopt blender-3d --provider <provider>` for a
45
+ one-off copy intended for local adaptation. No CLI changes are needed for these profiles.
46
+
47
+ - Install [Blender](https://www.blender.org/download/), verify `blender --version`.
48
+ Current fixture validation uses Blender 5.2.1 LTS; other versions need project verification.
49
+ - Install [Python 3](https://www.python.org/downloads/), verify `python3 --version`.
50
+ State and usage helpers use only its standard library. Image tools need
51
+ `python3 -m pip install Pillow numpy`; verify `python3 -c "import PIL, numpy"`.
52
+ - For a Godot target, install [Godot 4](https://godotengine.org/download/) and verify
53
+ `godot --version`; `GODOT` may hold its executable path.
54
+ - A required visual reviewer needs image viewing and independent-agent support in its session.
55
+ When unavailable, mark that gate `not_tested` and report partial delivery.
56
+
57
+ ## Start and resume
58
+
59
+ Ask the agent to use `blender-asset`, for example: “Quick: create a low-poly crate, 1 m wide,
60
+ under 400 triangles; deliver the editable blend and a front/three-quarter preview.” A strict
61
+ reference character can request Production with its views, identity priorities and export needs.
62
+
63
+ The coordinator records a task contract and required evidence before building. These examples
64
+ use Claude paths; Codex uses `.agents/skills` instead. Paths supplied to `task_state.py` resolve
65
+ relative to the state file's directory, independent of the current shell directory.
66
+
67
+ ```bash
68
+ python3 .claude/skills/blender-asset/scripts/task_state.py init \
69
+ --state work/crate/task.json --profile quick --artifact crate.blend \
70
+ --acceptance brief.json --require geometry --require preview
71
+ python3 .claude/skills/blender-asset/scripts/task_state.py evidence \
72
+ --state work/crate/task.json --name geometry --result pass \
73
+ --depends crate.blend --depends build.py --report mesh.json
74
+ python3 .claude/skills/blender-asset/scripts/task_state.py status \
75
+ --state work/crate/task.json --strict
76
+ ```
77
+
78
+ The brief and evidence files must exist when they are registered. Repeat evidence registration
79
+ for `preview` with its actual dependencies and image report; until then, strict status fails.
80
+ An evidence record is an assertion of a performed check, not an automatic visual judgment.
81
+ Hashes detect changed/missing declared files, not undeclared dependencies: include inputs,
82
+ builder, reference, render settings and export as appropriate. Unchanged independent evidence
83
+ can be reused. A coarse dependency such as the whole `.blend` conservatively invalidates all
84
+ checks registered against it when it changes.
85
+
86
+ Before a correction, reserve a round with `repair --state ... --reason "fix latch position"`.
87
+ Use `handoff --state ... --phase build --summary ... --next ... --ref ...` to leave compact
88
+ context for a new fix session; use `--phase fix` after that stage. Resume with the authoritative
89
+ asset, saved builder/edit script, criteria and unresolved findings. A lack of progress or an
90
+ exhausted ceiling ends repairs with remaining defects disclosed; do not reset state to evade it.
91
+ The state helper records reservations and evidence; the coordinator enforces the workflow.
92
+
93
+ ## Measure accepted-task cost
94
+
95
+ ```bash
96
+ python3 .claude/skills/blender-asset/scripts/record_run.py record \
97
+ --log work/crate/usage.jsonl --event-id create-1 --phase create \
98
+ --provider codex --model project-selected-model --input-tokens 1200 \
99
+ --output-tokens 400 --render-count 2 --render-seconds 4.5 --acceptance pass
100
+ python3 .claude/skills/blender-asset/scripts/record_run.py summary \
101
+ --log work/crate/usage.jsonl
102
+ ```
103
+
104
+ Record create, review and fix calls separately, with `--parent-id` for child calls. Each row
105
+ contains only that call's own usage; never record an inclusive parent total plus the same child
106
+ usage. Token categories are disjoint: `--input-tokens` excludes cache-read/write tokens;
107
+ normalize provider totals before recording them. Summed call durations are not wall-clock
108
+ duration when calls overlap. Unknown metrics remain null and summaries expose incomplete
109
+ coverage. Duplicate event
110
+ IDs cannot double count the same call. Render time, token/API usage and any supplied dollar
111
+ estimate measure different costs; `--advisory-dollars` requires `--advisory-source`.
112
+ These helpers neither read billing automatically nor enforce a live spending limit. The
113
+ coordinator writes state and usage sequentially; concurrent writers are not supported.
114
+
115
+ Compare workflows on comparable tasks that reached the same acceptance criteria, including
116
+ failed attempts, fixes and reviews. A create/fix split and lower effort are candidates to
117
+ measure, not a promised saving. Model choices remain in project configuration.
118
+
119
+ ## Technical acceptance
120
+
121
+ `check_motion.py` reports scope and coverage. Optional `--strict` requires at least one explicit
122
+ threshold: `--max-ground-penetration-mm`, `--max-planted-slide-mm-per-frame`,
123
+ `--max-extra-overlap-tris`, `--max-loop-rotation-deg`. Requested checks with no coverage fail
124
+ strict acceptance. Name relevant feet/pairs and the frame range; unrequested checks are diagnostics.
125
+ Use `blender -b asset.blend --python-exit-code 1 --python <script> -- <args>` for reliable failure propagation.
126
+
127
+ For exports, `verify_gltf.py file.glb --expect-clips Walk,Run --exact-clips --require-mesh
128
+ --require-skin --require-rig` checks original clip names including extras and re-imported structure.
129
+ Invoke it through Blender as above. For a static export, `--exact-clips` without `--expect-clips`
130
+ requires an empty clip set. Require only the structure the task actually needs.
36
131
 
37
- ## Provenance
132
+ ## Provenance and limits
38
133
 
39
- Distilled from two independent end-to-end sessions that built the same reference-matched
40
- character (0.94-0.96 silhouette IoU per view) and retargeted a Mixamo walk onto it. The scripts
41
- reproduce those sessions' measurements on the original assets.
134
+ The original modeling and retarget tools came from measured reference-character sessions.
135
+ The 1.5.0 workflow separates that demanding use case from simpler tasks, based on a two-week
136
+ Claude/Codex session audit. The audit did not establish that two medium sessions match one
137
+ large session at half the price. Silhouette scores, technical checks and sampled images each
138
+ cover different criteria; none is a universal quality certificate.
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: visual-reviewer
3
- description: Independent fresh-context visual review of a 3D asset or animation against its reference. Give it the reference image or source motion, the user's explicit requirements, and rendered comparison sheets, zoom crops, extra-angle renders or motion contact sheets. It returns at most five ranked findings. Read-only; it judges only the supplied images and does not read builder code.
3
+ description: Independently review supplied 3D asset or motion images against a brief, reference and intended display size. Use when the Blender workflow requires independent visual review or acceptance remains uncertain. Returns at most five ranked findings; read-only and does not inspect builder code.
4
+ isolation_reason: "A fresh context judges visible results without inheriting the builder's assumptions or sunk effort."
4
5
  tools: Read, Glob
5
6
  ---
6
7
 
@@ -8,44 +9,50 @@ tools: Read, Glob
8
9
 
9
10
  ## Responsibility
10
11
 
11
- Judge what the images show, independently of how the asset was built. The author's scores (IoU,
12
- QA numbers) are context, not proof. Find the differences that matter most to the user's stated
13
- priorities, which the author may no longer see.
12
+ Judge visible acceptance criteria independently of how the asset was built. Scores such as
13
+ silhouette IoU and technical QA are context, not proof of visual fidelity. Do not model, edit,
14
+ launch other agents or decide workflow routing. Review only the supplied packet and images;
15
+ do not open builder/rig code, whole transcripts or unrelated project files.
14
16
 
15
17
  ## Inputs
16
18
 
17
- - The reference: the reference image for a model, or for motion a contact sheet of the source
18
- clip when available. Also the user's requirements, including any intentional deviations from
19
- the reference (a requested deviation is not a defect).
20
- - Image paths: comparison sheets, zoom crops, renders from angles the reference does not show,
21
- and, for animation, contact sheets of frames from several angles.
22
- - Optional: known limitations the author already accepts.
19
+ - Brief, ranked priorities, acceptance criteria and intentional deviations.
20
+ - Reference images when reference fidelity is required; source-motion contact sheets when
21
+ source fidelity is required. A free-concept prop may have only a written brief.
22
+ - Current rendered images with regions/frames, intended presentation or gameplay size and
23
+ required view list. For a repair, changed regions and prior unresolved findings.
24
+ - Declared missing evidence and optional known limitations.
23
25
 
24
- Review only the images supplied, and do not open builder or rig code: independence from how the
25
- asset was made is the point. If a view needed for a judgment is missing, say which one instead
26
- of guessing.
26
+ ## Procedure
27
27
 
28
- ## What To Look For
28
+ 1. Confirm image access and required views. If unavailable, identify the missing evidence;
29
+ do not invent observations or infer appearance from filenames or scores.
30
+ 2. Compare the highest-priority visible criteria at intended display size. Inspect relevant
31
+ details at larger size where identity or construction depends on them. Requested deviations
32
+ are not defects; optional taste preferences cannot force another pass.
33
+ 3. For a repair, examine changed regions and visually affected dependencies. Reuse prior
34
+ findings only when their evidence is still current; note any unresolved required criterion.
35
+ 4. Assess applicable silhouette/proportion, identity detail, colour, attachments and construction.
36
+ For motion, inspect contacts, feet, collisions, joint deformation and sampled loop transitions.
37
+ Contact sheets alone do not prove behavior between sampled frames; state that limitation.
38
+ 5. Return at most five findings, major first. Report fewer when fewer exist. Do not fill a quota.
39
+ Escalate a missing required judgment separately from observed defects.
29
40
 
30
- - Identity: head shape, hairline and silhouette, beard boundary, facial proportions.
31
- - Proportion and silhouette: shoulder height, limb taper, torso depth, boot shape.
32
- - Details inside the outline that overlap scores cannot see: hand pose, pockets, straps,
33
- equipment placement and side, colours.
34
- - Construction: floating or unsupported parts, poke-through, hollow backs, unfinished transitions.
35
- - Motion: feet sliding or sinking, knee pops, limbs passing through the body or equipment,
36
- stiff or broken joints, loop hitches.
41
+ ## Output Contract
37
42
 
38
- ## Output
39
-
40
- At most five findings, most severe first. For each:
43
+ `Agent: visual-reviewer - output below`
41
44
 
42
45
  | Field | Content |
43
46
  | --- | --- |
44
- | Severity | major (visible at gameplay size or breaks a stated priority) or minor |
45
- | Where | image file and region or frame |
46
- | Observation | the concrete difference from the reference or the requirement |
47
- | Suggested fix | the smallest change likely to resolve it |
48
-
49
- Then one line: `Verdict: ready` or `Verdict: needs another pass`, and any views that could not be
50
- judged. Report fewer findings when fewer exist. Do not invent defects to fill the list, and label
51
- matters of taste as optional.
47
+ | Severity | major (breaks a stated criterion or is visibly wrong at intended size) / minor / optional taste |
48
+ | Where | image path and region or frame |
49
+ | Observation | visible difference tied to a criterion/reference |
50
+ | Suggested fix | smallest focused correction |
51
+
52
+ Finish with `Verdict: ready`, `Verdict: needs another pass`, or `Verdict: unverified`.
53
+ `ready` requires all required visual criteria judged with current sufficient evidence and no
54
+ major findings; disclose any minor findings. Use `needs another pass` for observed major
55
+ failures; use `unverified` when required judgments lack evidence and no major failure is yet
56
+ observed. Always list missing judgments, affected views, sampling limits and untested optional
57
+ criteria. A visual verdict does not certify topology, skin weights, exported clip sets or engine
58
+ behavior; the coordinator retains those separate technical gates.
@@ -0,0 +1,75 @@
1
+ ---
2
+ name: blender-asset
3
+ description: Build or revise a Blender asset from a brief, including simple props, prototypes and focused fixes without a reference sheet. Use as the blender-3d bundle entry capability; task complexity and optional reference, motion or export work are coordinated by its accompanying asset workflow.
4
+ ---
5
+
6
+ # Blender Asset
7
+
8
+ ## Scope
9
+
10
+ Produce one reproducible asset build or a targeted revision from a supplied task contract.
11
+ Supports a written brief without an image, an existing asset, or a measured reference.
12
+ Cross-skill sequencing, profile selection, reviews and repair limits belong to
13
+ [`workflows/asset.yml`](workflows/asset.yml), interpreted by the calling agent or manager;
14
+ it is an instruction workflow, not an executable runner. Direct invocation without a contract
15
+ returns the missing contract fields to that coordinator before modifying an asset.
16
+
17
+ ## Prerequisites
18
+
19
+ - Install the complete `blender-3d` bundle; its sibling skills and workflow are required context.
20
+ - Install [Blender](https://www.blender.org/download/); verify `blender --version`.
21
+ Store its executable path in consumer-project configuration if it is not on `PATH`.
22
+ - Install [Python 3](https://www.python.org/downloads/); verify `python3 --version`.
23
+ The state and usage helpers use only the standard library.
24
+ - Reference-image tools additionally need Pillow and numpy; see the reference skill.
25
+
26
+ ## Inputs
27
+
28
+ A task contract supplies the brief, chosen profile, authoritative input paths, output paths,
29
+ acceptance criteria, required views/checks and applicable tolerances. Include units, axes,
30
+ origin, dimensions, polygon/material constraints and target engine only when relevant.
31
+ Identify editable source versus derived outputs. A revision also names the changed region,
32
+ existing failures, allowed changes and previous evidence to reuse.
33
+
34
+ ## Procedure
35
+
36
+ Apply Stop Conditions immediately during every step; return the blocked work and evidence gaps.
37
+
38
+ 1. Inspect the named inputs and existing scene before writing. Use existing project conventions;
39
+ otherwise record reasonable units, axes and origin defaults in the task contract. Do not
40
+ impose character conventions on props or architectural assets.
41
+ 2. Make the smallest persisted Blender Python builder or edit script that produces the requested
42
+ change. Preserve user-authored geometry, materials and names outside that change. Save to
43
+ the agreed output; never overwrite an authoritative hand-edited `.blend` by rebuilding it.
44
+ Build into a new file and reconcile when script and scene disagree.
45
+ 3. For a new asset, establish scale and primary forms before details. For a narrow repair,
46
+ edit the affected region; do not restart the whole asset or regenerate unchanged views.
47
+ 4. Run the contract's relevant technical checks and render the affected views at the intended
48
+ presentation or gameplay size. Record checks as `pass`, `fail` or `not_tested`, with scope,
49
+ sample coverage and artifact paths. Missing tools or evidence cannot count as a pass.
50
+ 5. Save the editable `.blend`, its builder/edit script and requested exports. Return the
51
+ artifact paths, evidence, remaining defects and actual changes for the coordinator's next
52
+ gate. Stop this invocation after one build or repair stage.
53
+
54
+ ## State and Usage Helpers
55
+
56
+ Resolve scripts relative to this skill directory, not the shell working directory.
57
+ `python3 scripts/task_state.py --help` describes compact task state, file-dependent evidence
58
+ and bounded repair reservations. `python3 scripts/record_run.py --help` describes per-phase
59
+ usage records. Store their output in a consumer task directory outside synced skill files.
60
+ They do not launch agents, render, collect billing automatically or enforce a live money cap.
61
+
62
+ ## Stop Conditions
63
+
64
+ - An essential reference/input is missing, acceptance criteria conflict, or an edit would
65
+ overwrite authoritative work: return the concrete blocker without changing that work.
66
+ - A required check cannot run: record `not_tested` and return the missing capability.
67
+ - The coordinator has not reserved a permitted repair round: do not start another repair.
68
+
69
+ ## Output Contract
70
+
71
+ `Skill: blender-asset - output below`
72
+
73
+ Report: profile and stage; changed artifacts; checks with status and scope; evidence paths;
74
+ known defects or blockers; usage-record path (or unavailable metrics). The asset files and
75
+ persisted script are the primary output. Never claim overall acceptance from this build stage.
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env python3
2
+ """Record explicit own-call usage events and summarize known values plus coverage.
3
+
4
+ Never feed parent totals that already contain child calls into this log. Each
5
+ event owns a distinct call/work interval. Omitted metrics mean unknown, not zero.
6
+ Token categories must be disjoint: input_tokens excludes cache read/write tokens.
7
+ Advisory dollars are caller-supplied estimates with a source, never a hard cap.
8
+ No network calls, provider inference, pricing tables, or automatic collection.
9
+ """
10
+
11
+ import argparse
12
+ import json
13
+ import math
14
+ import os
15
+ from pathlib import Path
16
+ import sys
17
+
18
+
19
+ COUNTERS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens",
20
+ "api_calls", "tool_calls", "render_count")
21
+ METRICS = COUNTERS + ("elapsed_seconds", "render_seconds")
22
+ RESULTS = ("pass", "fail", "not_tested")
23
+
24
+
25
+ def nonempty(value):
26
+ if not value.strip():
27
+ raise argparse.ArgumentTypeError("value must not be empty")
28
+ return value
29
+
30
+
31
+ def natural(value):
32
+ try:
33
+ number = int(value)
34
+ except ValueError:
35
+ raise argparse.ArgumentTypeError("expected a nonnegative integer")
36
+ if number < 0 or str(number) != value:
37
+ raise argparse.ArgumentTypeError("expected a nonnegative integer")
38
+ return number
39
+
40
+
41
+ def finite(value):
42
+ try:
43
+ number = float(value)
44
+ except ValueError:
45
+ raise argparse.ArgumentTypeError("expected a finite nonnegative number")
46
+ if not math.isfinite(number) or number < 0:
47
+ raise argparse.ArgumentTypeError("expected a finite nonnegative number")
48
+ return number
49
+
50
+
51
+ def validate(event):
52
+ if (not isinstance(event, dict) or event.get("schema_version") != 1
53
+ or event.get("scope") != "own_call"
54
+ or not isinstance(event.get("event_id"), str) or not event["event_id"].strip()
55
+ or not isinstance(event.get("phase"), str) or not event["phase"].strip()
56
+ or event.get("acceptance") not in (*RESULTS, None)):
57
+ raise ValueError("invalid usage event schema")
58
+ for key in ("provider", "model", "effort", "parent_id"):
59
+ value = event.get(key)
60
+ if value is not None and (not isinstance(value, str) or not value.strip()):
61
+ raise ValueError("invalid " + key)
62
+ if event.get("parent_id") == event["event_id"]:
63
+ raise ValueError("parent_id must differ from event_id")
64
+ metrics = event.get("metrics")
65
+ if not isinstance(metrics, dict) or set(metrics) != set(METRICS):
66
+ raise ValueError("invalid usage metrics")
67
+ for key, value in metrics.items():
68
+ if value is not None and (type(value) not in (int, float) or not math.isfinite(value)
69
+ or value < 0 or (key in COUNTERS and type(value) is not int)):
70
+ raise ValueError("invalid metric: " + key)
71
+ advisory = event.get("advisory_cost")
72
+ if advisory is not None:
73
+ if not isinstance(advisory, dict) or set(advisory) != {"dollars", "source"}:
74
+ raise ValueError("invalid advisory cost")
75
+ value = advisory["dollars"]
76
+ if (type(value) not in (int, float) or not math.isfinite(value) or value < 0
77
+ or not isinstance(advisory["source"], str) or not advisory["source"].strip()):
78
+ raise ValueError("invalid advisory cost")
79
+
80
+
81
+ def read_events(path):
82
+ if not path.exists():
83
+ return [], False
84
+ content = path.read_text(encoding="utf-8")
85
+ events = {}
86
+ for line_number, line in enumerate(content.splitlines(), 1):
87
+ if not line.strip():
88
+ raise ValueError("blank usage line: " + str(line_number))
89
+ event = json.loads(line)
90
+ validate(event)
91
+ previous = events.get(event["event_id"])
92
+ if previous is not None and previous != event:
93
+ raise ValueError("conflicting duplicate event_id: " + event["event_id"])
94
+ events[event["event_id"]] = event
95
+ return list(events.values()), bool(content and not content.endswith("\n"))
96
+
97
+
98
+ def summarize(events):
99
+ totals = {}
100
+ for key in METRICS:
101
+ values = [event["metrics"][key] for event in events if event["metrics"][key] is not None]
102
+ known_sum = sum(values) if values else None
103
+ if known_sum is not None and not math.isfinite(known_sum):
104
+ raise ValueError("metric total is not finite: " + key)
105
+ totals[key] = {"known_sum": known_sum, "known_events": len(values),
106
+ "unknown_events": len(events) - len(values),
107
+ "complete": bool(events) and len(values) == len(events)}
108
+ advisory = [event["advisory_cost"] for event in events if event.get("advisory_cost") is not None]
109
+ dollars = sum(item["dollars"] for item in advisory) if advisory else None
110
+ if dollars is not None and not math.isfinite(dollars):
111
+ raise ValueError("advisory dollar total is not finite")
112
+ return {"event_count": len(events), "metrics": totals,
113
+ "acceptance": {result: sum(e["acceptance"] == result for e in events) for result in RESULTS},
114
+ "unknown_acceptance": sum(e["acceptance"] is None for e in events),
115
+ "advisory_cost": {"known_dollars": dollars, "known_events": len(advisory),
116
+ "unknown_events": len(events) - len(advisory),
117
+ "sources": sorted(set(item["source"] for item in advisory))},
118
+ "hard_money_cap_verified": False}
119
+
120
+
121
+ def main():
122
+ parser = argparse.ArgumentParser(description=__doc__)
123
+ commands = parser.add_subparsers(dest="command", required=True)
124
+ record = commands.add_parser("record", help="append one explicit own-call event, idempotently by ID")
125
+ record.add_argument("--event-id", required=True, type=nonempty)
126
+ record.add_argument("--phase", required=True, type=nonempty)
127
+ for key in ("provider", "model", "effort", "parent_id"):
128
+ record.add_argument("--" + key.replace("_", "-"), type=nonempty)
129
+ for key in METRICS:
130
+ record.add_argument("--" + key.replace("_", "-"), type=natural if key in COUNTERS else finite)
131
+ record.add_argument("--acceptance", choices=RESULTS)
132
+ record.add_argument("--advisory-dollars", type=finite)
133
+ record.add_argument("--advisory-source", type=nonempty)
134
+ summary = commands.add_parser("summary", help="sum known own-call metrics and expose unknown coverage")
135
+ for command in (record, summary):
136
+ command.add_argument("--log", type=Path, required=True)
137
+ args = parser.parse_args()
138
+ try:
139
+ events, needs_newline = read_events(args.log)
140
+ if args.command == "summary":
141
+ report = summarize(events)
142
+ report["phases"] = {phase: summarize([e for e in events if e["phase"] == phase])
143
+ for phase in sorted(set(e["phase"] for e in events))}
144
+ print(json.dumps(report, allow_nan=False))
145
+ return 0
146
+ if (args.advisory_dollars is None) != (args.advisory_source is None):
147
+ raise ValueError("--advisory-dollars and --advisory-source must be supplied together")
148
+ event = {"schema_version": 1, "scope": "own_call", "event_id": args.event_id,
149
+ "phase": args.phase, "provider": args.provider, "model": args.model,
150
+ "effort": args.effort, "parent_id": args.parent_id,
151
+ "metrics": {key: getattr(args, key) for key in METRICS}, "acceptance": args.acceptance,
152
+ "advisory_cost": None if args.advisory_dollars is None else
153
+ {"dollars": args.advisory_dollars, "source": args.advisory_source}}
154
+ validate(event)
155
+ previous = next((e for e in events if e["event_id"] == event["event_id"]), None)
156
+ if previous is not None:
157
+ if previous != event:
158
+ raise ValueError("conflicting duplicate event_id: " + event["event_id"])
159
+ print(json.dumps({"recorded": False, "event_id": event["event_id"]}))
160
+ return 0
161
+ args.log.parent.mkdir(parents=True, exist_ok=True)
162
+ payload = (("\n" if needs_newline else "") + json.dumps(event, allow_nan=False) + "\n").encode("utf-8")
163
+ with args.log.open("ab") as stream:
164
+ stream.write(payload)
165
+ stream.flush()
166
+ os.fsync(stream.fileno())
167
+ print(json.dumps({"recorded": True, "event_id": event["event_id"]}))
168
+ return 0
169
+ except (OSError, ValueError, KeyError, TypeError, OverflowError) as error:
170
+ print("record_run: " + str(error), file=sys.stderr)
171
+ return 2
172
+
173
+
174
+ if __name__ == "__main__":
175
+ sys.exit(main())