okstra 0.231.1 → 0.233.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 +19 -271
- package/dist/cli-registry.mjs +14 -1
- package/dist/cli-registry.mjs.map +1 -1
- package/dist/commands/execute/render-bundle.d.mts +6 -1
- package/dist/commands/execute/render-bundle.mjs +139 -32
- package/dist/commands/execute/render-bundle.mjs.map +1 -1
- package/dist/commands/lifecycle/config.mjs +6 -74
- package/dist/commands/lifecycle/config.mjs.map +1 -1
- package/dist/commands/memory/memory.mjs +9 -55
- package/dist/commands/memory/memory.mjs.map +1 -1
- package/dist/commands/trace/capacity.d.mts +12 -0
- package/dist/commands/trace/capacity.mjs +21 -0
- package/dist/commands/trace/capacity.mjs.map +1 -0
- package/dist/commands/trace/model.d.mts +89 -0
- package/dist/commands/trace/model.mjs +251 -0
- package/dist/commands/trace/model.mjs.map +1 -0
- package/dist/commands/trace/progression.d.mts +11 -0
- package/dist/commands/trace/progression.mjs +194 -0
- package/dist/commands/trace/progression.mjs.map +1 -0
- package/dist/commands/trace/review.d.mts +7 -0
- package/dist/commands/trace/review.mjs +51 -0
- package/dist/commands/trace/review.mjs.map +1 -0
- package/dist/commands/trace/task-link.d.mts +18 -0
- package/dist/commands/trace/task-link.mjs +72 -0
- package/dist/commands/trace/task-link.mjs.map +1 -0
- package/dist/commands/trace/trace.d.mts +1 -0
- package/dist/commands/trace/trace.mjs +293 -0
- package/dist/commands/trace/trace.mjs.map +1 -0
- package/dist/lib/bounded-file.d.mts +1 -0
- package/dist/lib/bounded-file.mjs +36 -0
- package/dist/lib/bounded-file.mjs.map +1 -0
- package/dist/lib/config-store.d.mts +34 -0
- package/dist/lib/config-store.mjs +70 -0
- package/dist/lib/config-store.mjs.map +1 -0
- package/dist/lib/file-lock.mjs +4 -5
- package/dist/lib/file-lock.mjs.map +1 -1
- package/dist/lib/input-limit.d.mts +4 -0
- package/dist/lib/input-limit.mjs +8 -0
- package/dist/lib/input-limit.mjs.map +1 -0
- package/dist/lib/memory-auto-register.d.mts +1 -0
- package/dist/lib/memory-auto-register.mjs +98 -0
- package/dist/lib/memory-auto-register.mjs.map +1 -0
- package/dist/lib/memory-entry-contract.d.mts +12 -0
- package/dist/lib/memory-entry-contract.mjs +46 -0
- package/dist/lib/memory-entry-contract.mjs.map +1 -0
- package/dist/lib/python-helper.d.mts +1 -1
- package/dist/lib/python-helper.mjs +3 -2
- package/dist/lib/python-helper.mjs.map +1 -1
- package/dist/lib/record-secrets.d.mts +1 -0
- package/dist/lib/record-secrets.mjs +28 -0
- package/dist/lib/record-secrets.mjs.map +1 -0
- package/dist/lib/report-language-tag.d.mts +1 -0
- package/dist/lib/report-language-tag.mjs +4 -0
- package/dist/lib/report-language-tag.mjs.map +1 -0
- package/dist/lib/report-language.d.mts +1 -0
- package/dist/lib/report-language.mjs +50 -0
- package/dist/lib/report-language.mjs.map +1 -0
- package/dist/lib/skill-catalog.mjs +3 -0
- package/dist/lib/skill-catalog.mjs.map +1 -1
- package/dist/lib/types.d.mts +2 -1
- package/docs/architecture/storage-model.md +163 -5
- package/docs/architecture.md +17 -4
- package/docs/cli.md +511 -0
- package/docs/contributor-change-matrix.md +1 -2
- package/docs/project-structure-overview.md +33 -42
- package/package.json +1 -1
- package/runtime/BUILD.json +2 -2
- package/runtime/agents/common.json +8 -8
- package/runtime/agents/operations/trace-interface-review.json +6 -0
- package/runtime/agents/operations/trace-scope-review.json +6 -0
- package/runtime/agents/roles/verifier.json +2 -4
- package/runtime/bin/okstra-provider-exec.py +10 -4
- package/runtime/prompts/coding-preflight/architectures/hexagonal.md +23 -30
- package/runtime/prompts/coding-preflight/authoring-checks.md +17 -0
- package/runtime/prompts/coding-preflight/clean-code.md +88 -286
- package/runtime/prompts/coding-preflight/frameworks/node-server.md +2 -3
- package/runtime/prompts/coding-preflight/languages/java.md +3 -5
- package/runtime/prompts/coding-preflight/languages/javascript-typescript.md +5 -12
- package/runtime/prompts/coding-preflight/languages/kotlin.md +2 -4
- package/runtime/prompts/coding-preflight/languages/python.md +2 -7
- package/runtime/prompts/coding-preflight/languages/rust.md +2 -8
- package/runtime/prompts/coding-preflight/languages/sql.md +2 -4
- package/runtime/prompts/coding-preflight/overview.md +25 -38
- package/runtime/prompts/coding-preflight/review-rules.json +30 -0
- package/runtime/prompts/duties/code-reviewer.json +15 -18
- package/runtime/prompts/duties/implementation-verifier.json +1 -0
- package/runtime/prompts/duties/interface-reviewer.json +32 -0
- package/runtime/prompts/host-orchestration/README.md +18 -9
- package/runtime/prompts/launch.template.md +3 -2
- package/runtime/prompts/lead/context-loader.md +2 -0
- package/runtime/prompts/lead/okstra-lead-contract.md +7 -7
- package/runtime/prompts/lead/report-writer.md +6 -6
- package/runtime/prompts/profiles/_coding-conventions-preflight.md +41 -6
- package/runtime/prompts/profiles/_common-contract.md +1 -1
- package/runtime/python/okstra_ctl/agent/invocation.py +122 -36
- package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +72 -26
- package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +23 -8
- package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +58 -14
- package/runtime/python/okstra_ctl/agent/prompt_cli/results.py +8 -11
- package/runtime/python/okstra_ctl/agent/standalone.py +15 -0
- package/runtime/python/okstra_ctl/analysis_packet.py +24 -30
- package/runtime/python/okstra_ctl/attempt_evidence.py +10 -0
- package/runtime/python/okstra_ctl/code_review_census.py +162 -7
- package/runtime/python/okstra_ctl/code_review_coverage.py +4 -274
- package/runtime/python/okstra_ctl/code_review_integrity.py +154 -0
- package/runtime/python/okstra_ctl/code_review_invocation.py +212 -0
- package/runtime/python/okstra_ctl/code_review_prepare.py +381 -0
- package/runtime/python/okstra_ctl/code_review_run.py +384 -0
- package/runtime/python/okstra_ctl/code_review_scope.py +49 -9
- package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
- package/runtime/python/okstra_ctl/code_review_target.py +212 -13
- package/runtime/python/okstra_ctl/consumers.py +12 -9
- package/runtime/python/okstra_ctl/coverage_census.py +11 -2
- package/runtime/python/okstra_ctl/design_review.py +207 -0
- package/runtime/python/okstra_ctl/design_review_evidence.py +297 -0
- package/runtime/python/okstra_ctl/design_snapshot.py +16 -9
- package/runtime/python/okstra_ctl/direct_work.py +45 -3
- package/runtime/python/okstra_ctl/dispatch_core.py +31 -15
- package/runtime/python/okstra_ctl/dispatch_state.py +9 -2
- package/runtime/python/okstra_ctl/doctor.py +8 -25
- package/runtime/python/okstra_ctl/domain/role.py +1 -0
- package/runtime/python/okstra_ctl/doyouknow/__init__.py +9 -0
- package/runtime/python/okstra_ctl/doyouknow/cli.py +91 -0
- package/runtime/python/okstra_ctl/doyouknow/config.py +58 -0
- package/runtime/python/okstra_ctl/doyouknow/contracts.py +184 -0
- package/runtime/python/okstra_ctl/doyouknow/identity.py +22 -0
- package/runtime/python/okstra_ctl/doyouknow/paths.py +22 -0
- package/runtime/python/okstra_ctl/doyouknow/pending.py +72 -0
- package/runtime/python/okstra_ctl/doyouknow/registration.py +260 -0
- package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +128 -0
- package/runtime/python/okstra_ctl/doyouknow/source_store.py +172 -0
- package/runtime/python/okstra_ctl/doyouknow/sources/io.py +36 -0
- package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +300 -0
- package/runtime/python/okstra_ctl/doyouknow/sources/memory.py +179 -0
- package/runtime/python/okstra_ctl/doyouknow/sources/task.py +95 -0
- package/runtime/python/okstra_ctl/doyouknow/store.py +260 -0
- package/runtime/python/okstra_ctl/doyouknow/sync.py +58 -0
- package/runtime/python/okstra_ctl/execution_mutation_audit.py +18 -2
- package/runtime/python/okstra_ctl/file_size_cap.py +3 -4
- package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
- package/runtime/python/okstra_ctl/incremental_carry.py +6 -7
- package/runtime/python/okstra_ctl/initial_prompt_materialization.py +9 -2
- package/runtime/python/okstra_ctl/json_boundary.py +51 -5
- package/runtime/python/okstra_ctl/jsonl.py +21 -0
- package/runtime/python/okstra_ctl/manager_cli.py +148 -1
- package/runtime/python/okstra_ctl/manager_journal.py +126 -0
- package/runtime/python/okstra_ctl/manager_launch.py +3 -3
- package/runtime/python/okstra_ctl/manager_log.py +221 -0
- package/runtime/python/okstra_ctl/manager_paths.py +8 -0
- package/runtime/python/okstra_ctl/manager_registration.py +29 -0
- package/runtime/python/okstra_ctl/manager_resume.py +59 -0
- package/runtime/python/okstra_ctl/manager_split.py +2 -2
- package/runtime/python/okstra_ctl/manager_store.py +116 -17
- package/runtime/python/okstra_ctl/manager_sync.py +45 -25
- package/runtime/python/okstra_ctl/manager_view.py +35 -2
- package/runtime/python/okstra_ctl/material.py +2 -0
- package/runtime/python/okstra_ctl/model_cli.py +64 -14
- package/runtime/python/okstra_ctl/model_defaults.py +22 -0
- package/runtime/python/okstra_ctl/model_io/renderers.py +16 -2
- package/runtime/python/okstra_ctl/model_io_cli.py +7 -1
- package/runtime/python/okstra_ctl/operation_invocation.py +207 -28
- package/runtime/python/okstra_ctl/path_hints.py +14 -3
- package/runtime/python/okstra_ctl/paths.py +6 -1
- package/runtime/python/okstra_ctl/phases/catalog.py +24 -7
- package/runtime/python/okstra_ctl/phases/final_verification/validation.py +20 -0
- package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +3 -3
- package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +10 -0
- package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +23 -8
- package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +6 -4
- package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +38 -10
- package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +13 -0
- package/runtime/python/okstra_ctl/phases/implementation/spec.md +25 -0
- package/runtime/python/okstra_ctl/phases/implementation/validation.py +6 -0
- package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
- package/runtime/python/okstra_ctl/phases/implementation_option_selection/votes.py +11 -11
- package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +16 -9
- package/runtime/python/okstra_ctl/phases/implementation_planning/host-rules.md +3 -6
- package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -10
- package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +6 -6
- package/runtime/python/okstra_ctl/phases/improvement_discovery/lenses.py +12 -0
- package/runtime/python/okstra_ctl/phases/improvement_discovery/profile.md +7 -6
- package/runtime/python/okstra_ctl/phases/improvement_discovery/resolved_census.py +159 -0
- package/runtime/python/okstra_ctl/phases/improvement_discovery/spec.md +5 -2
- package/runtime/python/okstra_ctl/phases/improvement_discovery/validation.py +21 -7
- package/runtime/python/okstra_ctl/phases/release_handoff/boundary.json +1 -1
- package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +4 -1
- package/runtime/python/okstra_ctl/plan_verify_cli.py +6 -4
- package/runtime/python/okstra_ctl/render.py +28 -2
- package/runtime/python/okstra_ctl/report_assembly.py +53 -11
- package/runtime/python/okstra_ctl/report_contract.py +26 -0
- package/runtime/python/okstra_ctl/report_corrections.py +36 -20
- package/runtime/python/okstra_ctl/report_inputs.py +1 -0
- package/runtime/python/okstra_ctl/report_language.py +4 -1
- package/runtime/python/okstra_ctl/report_narrative.py +182 -7
- package/runtime/python/okstra_ctl/report_projections.py +64 -18
- package/runtime/python/okstra_ctl/report_synthesis_packet.py +97 -38
- package/runtime/python/okstra_ctl/review_policy.py +359 -0
- package/runtime/python/okstra_ctl/review_verdicts.py +291 -0
- package/runtime/python/okstra_ctl/run.py +67 -36
- package/runtime/python/okstra_ctl/run_context.py +10 -1
- package/runtime/python/okstra_ctl/set_work_status.py +4 -15
- package/runtime/python/okstra_ctl/stage_done.py +11 -0
- package/runtime/python/okstra_ctl/standalone_review_audit.py +28 -0
- package/runtime/python/okstra_ctl/task_list_cli.py +34 -8
- package/runtime/python/okstra_ctl/task_query.py +239 -0
- package/runtime/python/okstra_ctl/trace_review.py +264 -0
- package/runtime/python/okstra_ctl/trace_tasks.py +197 -0
- package/runtime/python/okstra_ctl/user_authorization.py +14 -0
- package/runtime/python/okstra_ctl/verification_generation.py +23 -1
- package/runtime/python/okstra_ctl/verification_input_types.py +15 -1
- package/runtime/python/okstra_ctl/verification_inputs.py +28 -6
- package/runtime/python/okstra_ctl/verification_invocation.py +7 -1
- package/runtime/python/okstra_ctl/verification_target.py +2 -0
- package/runtime/python/okstra_ctl/wizard/confirmation.py +7 -3
- package/runtime/python/okstra_ctl/wizard/launch.py +52 -0
- package/runtime/python/okstra_ctl/wizard/launch_cli.py +39 -0
- package/runtime/python/okstra_ctl/wizard/outcome.py +17 -16
- package/runtime/python/okstra_ctl/wizard/registry.py +1 -1
- package/runtime/python/okstra_ctl/wizard/render.py +8 -0
- package/runtime/python/okstra_ctl/wizard/state.py +2 -1
- package/runtime/python/okstra_ctl/worker_prompt_headers.py +24 -9
- package/runtime/python/okstra_ctl/worker_runner.py +66 -10
- package/runtime/python/okstra_ctl/write_policy.py +34 -1
- package/runtime/python/okstra_project/__init__.py +2 -0
- package/runtime/python/okstra_project/dirs.py +18 -0
- package/runtime/python/okstra_project/state.py +45 -20
- package/runtime/python/okstra_token_usage/blocks.py +74 -0
- package/runtime/python/okstra_token_usage/cli.py +23 -10
- package/runtime/python/okstra_token_usage/collect.py +25 -22
- package/runtime/python/okstra_token_usage/policy.py +193 -0
- package/runtime/schemas/doyouknow-config-v1.schema.json +20 -0
- package/runtime/schemas/doyouknow-v1.schema.json +65 -0
- package/runtime/schemas/final-report-v2.0.schema.json +157 -0
- package/runtime/schemas/final-report-v3.0.schema.json +157 -0
- package/runtime/schemas/memory-entry-contract-v1.json +11 -0
- package/runtime/schemas/record-secret-patterns.json +41 -0
- package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +1 -1
- package/runtime/skills/_fragments/wizard-confirm-step.md +1 -1
- package/runtime/skills/_fragments/wizard-preflight.md +1 -1
- package/runtime/skills/_fragments/wizard-prompt-loop.md +3 -5
- package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
- package/runtime/skills/_fragments/wizard-render-bundle.md +15 -29
- package/runtime/skills/okstra-brief-gen/SKILL.md +7 -7
- package/runtime/skills/okstra-brief-gen/references/tracker-recursion.md +1 -1
- package/runtime/skills/okstra-code-review/SKILL.md +92 -136
- package/runtime/skills/okstra-code-review/references/census-rules.md +29 -105
- package/runtime/skills/okstra-code-review/references/review-calibration.md +37 -61
- package/runtime/skills/okstra-discussion/SKILL.md +22 -38
- package/runtime/skills/okstra-explain-flow/SKILL.md +6 -2
- package/runtime/skills/okstra-manager/SKILL.md +31 -0
- package/runtime/skills/okstra-memory/SKILL.md +8 -1
- package/runtime/skills/okstra-pr-gen/SKILL.md +1 -1
- package/runtime/skills/okstra-run/SKILL.md +55 -183
- package/runtime/skills/okstra-schedule-gen/SKILL.md +9 -13
- package/runtime/skills/okstra-setup/SKILL.md +3 -2
- package/runtime/skills/okstra-setup/references/project-config.md +2 -4
- package/runtime/skills/okstra-tdd/SKILL.md +187 -0
- package/runtime/skills/okstra-user-response/SKILL.md +4 -2
- package/runtime/templates/implementation-worker-preamble.md +4 -9
- package/runtime/templates/manager/view.template.html +4 -0
- package/runtime/templates/report-writer-prompt-preamble.md +15 -3
- package/runtime/templates/trace/trace.template.md +42 -0
- package/runtime/templates/worker-prompt-preamble.md +4 -12
- package/runtime/validators/checks/fixtures-02.py +25 -33
- package/runtime/validators/validate-run.py +107 -38
|
@@ -85,6 +85,24 @@ def okstra_home() -> Path:
|
|
|
85
85
|
return home
|
|
86
86
|
|
|
87
87
|
|
|
88
|
+
def contained_relative_path(ref: str, root: Path) -> str | None:
|
|
89
|
+
"""Callers supply a resolved root for shared reference identity.
|
|
90
|
+
|
|
91
|
+
Unknown home names can be prose tokens such as ``~200``; the ``None``
|
|
92
|
+
result keeps those tokens from aborting source material processing.
|
|
93
|
+
Readers and writers share this interpretation so they name the same file.
|
|
94
|
+
"""
|
|
95
|
+
try:
|
|
96
|
+
candidate = Path(ref).expanduser()
|
|
97
|
+
except RuntimeError:
|
|
98
|
+
return None
|
|
99
|
+
path = (candidate if candidate.is_absolute() else root / candidate).resolve()
|
|
100
|
+
try:
|
|
101
|
+
return path.relative_to(root).as_posix()
|
|
102
|
+
except ValueError:
|
|
103
|
+
return None
|
|
104
|
+
|
|
105
|
+
|
|
88
106
|
def okstra_root(project_root: Path) -> Path:
|
|
89
107
|
"""`<project_root>/.okstra` 절대 path."""
|
|
90
108
|
return Path(project_root) / OKSTRA_RELATIVE
|
|
@@ -152,6 +152,23 @@ _DERIVED_STATUS_STRING_FIELDS = (
|
|
|
152
152
|
"workStatusUpdatedAt",
|
|
153
153
|
)
|
|
154
154
|
|
|
155
|
+
IMPLEMENTATION_TRACE_FIELDS = (
|
|
156
|
+
"executionKind", "implementationTracePath", "traceMetadata", "implementationTraces", "traceDigest",
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def implementation_trace_projection(manifest: dict) -> dict:
|
|
161
|
+
if manifest.get("executionKind") != "implementation-trace":
|
|
162
|
+
return {}
|
|
163
|
+
path = manifest.get("implementationTracePath", "")
|
|
164
|
+
metadata = manifest.get("traceMetadata", {})
|
|
165
|
+
return {
|
|
166
|
+
"executionKind": "implementation-trace", "implementationTracePath": path,
|
|
167
|
+
"traceMetadata": metadata, "traceCount": len(manifest.get("implementationTraces", [])),
|
|
168
|
+
"relatedTasks": manifest.get("relatedTasks", []), "title": metadata.get("title", ""),
|
|
169
|
+
"nextAction": {"kind": "delegate", "skill": "okstra-tdd", "path": path},
|
|
170
|
+
}
|
|
171
|
+
|
|
155
172
|
|
|
156
173
|
def derived_task_status(manifest: dict) -> dict:
|
|
157
174
|
"""Task status a caller acts on, projected off the raw manifest.
|
|
@@ -191,6 +208,7 @@ def _entry_with_manifest_state(entry: dict, task_root: Path) -> dict:
|
|
|
191
208
|
raw = entry.get("nextRecommendedPhase")
|
|
192
209
|
out["nextRecommendedPhase"] = promote_phase_pointer(raw)
|
|
193
210
|
out.update(derived_task_status(manifest))
|
|
211
|
+
out.update(implementation_trace_projection(manifest))
|
|
194
212
|
return out
|
|
195
213
|
|
|
196
214
|
|
|
@@ -206,6 +224,27 @@ def parse_task_key(task_key: str) -> tuple[str, str, str]:
|
|
|
206
224
|
return parts[0], parts[1], parts[2]
|
|
207
225
|
|
|
208
226
|
|
|
227
|
+
def resolve_task_root_read_only(
|
|
228
|
+
project_root: Path, task_key: str, *, catalog: list[dict] | None = None,
|
|
229
|
+
) -> Path | None:
|
|
230
|
+
project_root = Path(project_root)
|
|
231
|
+
_, task_group, task_id = parse_task_key(task_key)
|
|
232
|
+
requested_key = task_key.lower()
|
|
233
|
+
entries = read_task_catalog(project_root) if catalog is None else catalog
|
|
234
|
+
for entry in entries:
|
|
235
|
+
entry_key = entry.get("taskKey") or ""
|
|
236
|
+
if not isinstance(entry_key, str) or entry_key.lower() != requested_key:
|
|
237
|
+
continue
|
|
238
|
+
relative_path = entry.get("taskRootPath") or entry.get("taskRoot") or ""
|
|
239
|
+
if not isinstance(relative_path, str) or not relative_path:
|
|
240
|
+
continue
|
|
241
|
+
candidate = project_root / relative_path if not Path(relative_path).is_absolute() else Path(relative_path)
|
|
242
|
+
if candidate.is_dir():
|
|
243
|
+
return candidate
|
|
244
|
+
slug_path = project_root / TASKS_RELATIVE / slugify(task_group) / slugify(task_id)
|
|
245
|
+
return slug_path if slug_path.is_dir() else None
|
|
246
|
+
|
|
247
|
+
|
|
209
248
|
def find_task_root(project_root: Path, task_key: str) -> Optional[Path]:
|
|
210
249
|
"""task-key 로 task root 디렉터리를 해석한다.
|
|
211
250
|
|
|
@@ -215,26 +254,10 @@ def find_task_root(project_root: Path, task_key: str) -> Optional[Path]:
|
|
|
215
254
|
|
|
216
255
|
어느 쪽도 디렉터리로 존재하지 않으면 None.
|
|
217
256
|
"""
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
for entry in read_task_catalog(project_root):
|
|
223
|
-
entry_key = entry.get("taskKey") or ""
|
|
224
|
-
if not isinstance(entry_key, str) or entry_key.lower() != requested_ci:
|
|
225
|
-
continue
|
|
226
|
-
rel = entry.get("taskRootPath") or entry.get("taskRoot") or ""
|
|
227
|
-
if isinstance(rel, str) and rel:
|
|
228
|
-
abs_path = project_root / rel if not Path(rel).is_absolute() else Path(rel)
|
|
229
|
-
if abs_path.is_dir():
|
|
230
|
-
_reconcile_task_root_best_effort(project_root, abs_path)
|
|
231
|
-
return abs_path
|
|
232
|
-
|
|
233
|
-
slug_path = project_root / TASKS_RELATIVE / slugify(task_group) / slugify(task_id)
|
|
234
|
-
if slug_path.is_dir():
|
|
235
|
-
_reconcile_task_root_best_effort(project_root, slug_path)
|
|
236
|
-
return slug_path
|
|
237
|
-
return None
|
|
257
|
+
task_root = resolve_task_root_read_only(project_root, task_key)
|
|
258
|
+
if task_root is not None:
|
|
259
|
+
_reconcile_task_root_best_effort(Path(project_root), task_root)
|
|
260
|
+
return task_root
|
|
238
261
|
|
|
239
262
|
|
|
240
263
|
def resolve_task_id(
|
|
@@ -396,6 +419,8 @@ def task_read_side_snapshot(project_root: Path, task_key: str) -> dict:
|
|
|
396
419
|
workflow = {}
|
|
397
420
|
return {
|
|
398
421
|
"projectRoot": identity["projectRoot"],
|
|
422
|
+
**implementation_trace_projection(manifest),
|
|
423
|
+
**({"implementationTraces": manifest.get("implementationTraces", [])} if manifest.get("executionKind") == "implementation-trace" else {}),
|
|
399
424
|
"taskKey": manifest.get("taskKey"),
|
|
400
425
|
"taskType": manifest.get("taskType"),
|
|
401
426
|
"taskRoot": identity["taskRoot"],
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""Per-source usage block constructors (consumed by collect())."""
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
|
+
import math
|
|
4
5
|
from collections.abc import Mapping
|
|
5
6
|
from typing import Any
|
|
6
7
|
|
|
@@ -11,6 +12,7 @@ from .pricing import (
|
|
|
11
12
|
)
|
|
12
13
|
|
|
13
14
|
_CACHE_INCLUDED_SOURCES = frozenset({"codex-cli", "grok-cli", "kimi-cli"})
|
|
15
|
+
SESSION_JSONL_PROVIDERS = frozenset({"claude"})
|
|
14
16
|
|
|
15
17
|
|
|
16
18
|
def accounting_workers(state: Mapping[str, Any]) -> list[dict]:
|
|
@@ -23,6 +25,78 @@ def accounting_workers(state: Mapping[str, Any]) -> list[dict]:
|
|
|
23
25
|
return rows
|
|
24
26
|
|
|
25
27
|
|
|
28
|
+
def report_usage_workers(state: Mapping[str, Any]) -> list[dict]:
|
|
29
|
+
"""Keep visible workers, excluding the lead's duplicate accounting row."""
|
|
30
|
+
return [row for row in accounting_workers(state) if "lead" not in {
|
|
31
|
+
str(row.get("workerId") or "").strip().lower(),
|
|
32
|
+
str(row.get("role") or "").strip().lower(),
|
|
33
|
+
}]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def usage_participants(state: Mapping[str, Any]) -> list[dict]:
|
|
37
|
+
"""Exclude declared non-executions, retaining observed or attempted work."""
|
|
38
|
+
participants = []
|
|
39
|
+
for row in report_usage_workers(state):
|
|
40
|
+
usage = row.get("usage") if isinstance(row.get("usage"), Mapping) else {}
|
|
41
|
+
observed = usage.get("source") not in (None, "unavailable")
|
|
42
|
+
timed = any(row.get(key) or usage.get(key) for key in ("startedAt", "endedAt"))
|
|
43
|
+
counters = any(usage.get(key) not in (None, 0) for key in (
|
|
44
|
+
"totalTokens", "cacheReadTokens", "cliTotalTokens", "billableEquivalentTokens", "durationMs",
|
|
45
|
+
))
|
|
46
|
+
attempts = any(isinstance(attempt, Mapping) and attempt.get("status") not in (None, "not-run")
|
|
47
|
+
for attempt in row.get("usageAttempts") or [])
|
|
48
|
+
if row.get("status") != "not-run" or observed or timed or counters or attempts:
|
|
49
|
+
participants.append(row)
|
|
50
|
+
return participants
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cli_assignment_provider(worker: Mapping[str, Any]) -> str:
|
|
54
|
+
"""Resolve separate CLI accounting exactly as the collector does."""
|
|
55
|
+
from okstra_ctl.models import provider_wrappers
|
|
56
|
+
|
|
57
|
+
worker_id = str(worker.get("workerId") or "").strip()
|
|
58
|
+
explicit_provider = str(worker.get("provider") or "").strip()
|
|
59
|
+
provider = explicit_provider or str(worker.get("agent") or "").strip()
|
|
60
|
+
if provider in SESSION_JSONL_PROVIDERS:
|
|
61
|
+
return ""
|
|
62
|
+
runner = str(worker.get("runner") or "").strip()
|
|
63
|
+
if runner and runner != "cli-wrapper":
|
|
64
|
+
return ""
|
|
65
|
+
if not explicit_provider and worker_id == "report-writer":
|
|
66
|
+
provider = "codex"
|
|
67
|
+
return provider if provider in provider_wrappers() else ""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cli_usage_required(worker: Mapping[str, Any]) -> bool:
|
|
71
|
+
usage = worker.get("usage") if isinstance(worker.get("usage"), Mapping) else {}
|
|
72
|
+
return bool(cli_assignment_provider(worker)) or str(usage.get("source", "")).endswith("-cli") or any(
|
|
73
|
+
key in usage for key in ("cliNote", "cliTotalTokens", "cliEstimatedCostUsd", "cliExecutionStatus")
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def finite_non_negative(value: object) -> bool:
|
|
78
|
+
return (not isinstance(value, bool) and isinstance(value, (int, float)) and value >= 0
|
|
79
|
+
and (not isinstance(value, float) or math.isfinite(value)))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def usage_is_incomplete(usage: Mapping[str, Any], *, cli: bool = False) -> bool:
|
|
83
|
+
source = str(usage.get("source", ""))
|
|
84
|
+
return source == "unavailable" or bool(usage.get("missingSessionIds")) and (cli or source.endswith("-cli"))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def usage_is_measured_zero(usage: Mapping[str, Any], *, cli: bool = False) -> bool:
|
|
88
|
+
"""A cache read or missing session prevents inferring an unrecorded zero."""
|
|
89
|
+
if usage_is_incomplete(usage, cli=cli):
|
|
90
|
+
return False
|
|
91
|
+
# Attached CLI counters omit the CLI's cache counters; wrapper zeros cannot prove CLI zero spend.
|
|
92
|
+
if cli and not str(usage.get("source", "")).endswith("-cli"):
|
|
93
|
+
return False
|
|
94
|
+
keys = ("cliTotalTokens" if cli else "totalTokens", "inputTokens", "outputTokens",
|
|
95
|
+
"cacheReadTokens", "cachedInputTokens", "cacheCreationTokens", "billableEquivalentTokens")
|
|
96
|
+
primary = keys[0]
|
|
97
|
+
return primary in usage and all(finite_non_negative(usage.get(key, 0)) and usage.get(key, 0) == 0 for key in keys)
|
|
98
|
+
|
|
99
|
+
|
|
26
100
|
def usage_blocks(state: dict) -> list[dict]:
|
|
27
101
|
blocks = [state.get("leadUsage") or {}]
|
|
28
102
|
blocks.extend(worker.get("usage") or {} for worker in accounting_workers(state))
|
|
@@ -7,6 +7,7 @@ import sys
|
|
|
7
7
|
from pathlib import Path
|
|
8
8
|
|
|
9
9
|
from .collect import collect
|
|
10
|
+
from .policy import usage_accounting_policy, usage_diagnostics
|
|
10
11
|
from .report import (
|
|
11
12
|
SubstituteRefusedError,
|
|
12
13
|
populate_token_cells,
|
|
@@ -93,6 +94,11 @@ def main() -> int:
|
|
|
93
94
|
|
|
94
95
|
updated = collect(args.team_state, args.project_root,
|
|
95
96
|
incremental=not args.no_cache)
|
|
97
|
+
advisory = usage_accounting_policy(updated) == "advisory"
|
|
98
|
+
if advisory:
|
|
99
|
+
_errors, missing = usage_diagnostics(updated)
|
|
100
|
+
for row in missing:
|
|
101
|
+
print(f"token-usage advisory: {row['item']} — {row['risk']}", file=sys.stderr)
|
|
96
102
|
|
|
97
103
|
if args.write:
|
|
98
104
|
args.team_state.write_text(
|
|
@@ -106,22 +112,22 @@ def main() -> int:
|
|
|
106
112
|
s = updated.get("usageSummary") or {}
|
|
107
113
|
cost = s.get("estimatedCostUsd") or {}
|
|
108
114
|
print(
|
|
109
|
-
f"raw: lead={s.get('leadTotalTokens',
|
|
110
|
-
f"workers={s.get('workerTotalTokens',
|
|
111
|
-
f"grand={s.get('grandTotalTokens',
|
|
115
|
+
f"raw: lead={_display(s.get('leadTotalTokens'), ',')} "
|
|
116
|
+
f"workers={_display(s.get('workerTotalTokens'), ',')} "
|
|
117
|
+
f"grand={_display(s.get('grandTotalTokens'), ',')}",
|
|
112
118
|
file=sys.stderr,
|
|
113
119
|
)
|
|
114
120
|
print(
|
|
115
|
-
f"billable-equiv: lead={s.get('leadBillableEquivalentTokens',
|
|
116
|
-
f"workers={s.get('workerBillableEquivalentTokens',
|
|
117
|
-
f"grand={s.get('grandBillableEquivalentTokens',
|
|
121
|
+
f"billable-equiv: lead={_display(s.get('leadBillableEquivalentTokens'), ',')} "
|
|
122
|
+
f"workers={_display(s.get('workerBillableEquivalentTokens'), ',')} "
|
|
123
|
+
f"grand={_display(s.get('grandBillableEquivalentTokens'), ',')}",
|
|
118
124
|
file=sys.stderr,
|
|
119
125
|
)
|
|
120
126
|
print(
|
|
121
|
-
f"cost USD: lead=${cost.get('lead',
|
|
122
|
-
f"claude-workers=${cost.get('claudeWorkers',
|
|
123
|
-
f"cli-workers=${cost.get('cliWorkers',
|
|
124
|
-
f"grand=${cost.get('grandTotal',
|
|
127
|
+
f"cost USD: lead=${_display(cost.get('lead'), '.2f')} "
|
|
128
|
+
f"claude-workers=${_display(cost.get('claudeWorkers'), '.2f')} "
|
|
129
|
+
f"cli-workers=${_display(cost.get('cliWorkers'), '.2f')} "
|
|
130
|
+
f"grand=${_display(cost.get('grandTotal'), '.2f')}",
|
|
125
131
|
file=sys.stderr,
|
|
126
132
|
)
|
|
127
133
|
print(
|
|
@@ -131,6 +137,9 @@ def main() -> int:
|
|
|
131
137
|
)
|
|
132
138
|
|
|
133
139
|
if args.substitute_data is not None:
|
|
140
|
+
if advisory:
|
|
141
|
+
print("token-usage advisory: published report preserved; recollection is stored only in team-state.", file=sys.stderr)
|
|
142
|
+
return 0
|
|
134
143
|
try:
|
|
135
144
|
cells_changed = populate_token_cells(
|
|
136
145
|
args.substitute_data,
|
|
@@ -151,5 +160,9 @@ def main() -> int:
|
|
|
151
160
|
return 0
|
|
152
161
|
|
|
153
162
|
|
|
163
|
+
def _display(value: object, spec: str) -> str:
|
|
164
|
+
return format(value, spec) if isinstance(value, (int, float)) else "unavailable"
|
|
165
|
+
|
|
166
|
+
|
|
154
167
|
if __name__ == "__main__":
|
|
155
168
|
sys.exit(main())
|
|
@@ -9,7 +9,13 @@ from pathlib import Path
|
|
|
9
9
|
from typing import Any
|
|
10
10
|
from okstra_project.dirs import OKSTRA_RELATIVE
|
|
11
11
|
|
|
12
|
-
from .blocks import
|
|
12
|
+
from .blocks import (
|
|
13
|
+
SESSION_JSONL_PROVIDERS as _SESSION_JSONL_PROVIDERS,
|
|
14
|
+
accounting_workers,
|
|
15
|
+
cli_assignment_provider as _cli_assignment_provider,
|
|
16
|
+
na_block,
|
|
17
|
+
usage_block,
|
|
18
|
+
)
|
|
13
19
|
from .claude import (
|
|
14
20
|
claude_code_status_total,
|
|
15
21
|
claude_session_totals,
|
|
@@ -38,6 +44,7 @@ from .grok import (
|
|
|
38
44
|
)
|
|
39
45
|
from .paths import claude_project_dir, find_session_jsonl, utc_now
|
|
40
46
|
from .pricing import antigravity_cost_usd, provider_billable_equivalent, provider_cost_usd
|
|
47
|
+
from .policy import manifest_for_usage, usage_accounting_policy, usage_diagnostics
|
|
41
48
|
from okstra_ctl.usage_identity import (
|
|
42
49
|
unrostered_usage_workers,
|
|
43
50
|
usage_dispatch_records,
|
|
@@ -602,26 +609,6 @@ def _codex_worker_windows(project_root: Path, state: dict) -> dict[str, list[tup
|
|
|
602
609
|
return windows
|
|
603
610
|
|
|
604
611
|
|
|
605
|
-
# Claude 의 트랜스크립트는 세션 jsonl 이고, 그것은 이 모듈의 Claude 경로가
|
|
606
|
-
# 읽는다. 별도의 CLI 트랜스크립트가 없으므로 CLI 경로에 태우면 매번
|
|
607
|
-
# `no transcript was found` 가 붙는다 — 세션을 찾아 토큰을 붙인 행에도.
|
|
608
|
-
_SESSION_JSONL_PROVIDERS = frozenset({"claude"})
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
def _cli_assignment_provider(worker: dict) -> str:
|
|
612
|
-
worker_id = str(worker.get("workerId") or "").strip()
|
|
613
|
-
explicit_provider = str(worker.get("provider") or "").strip()
|
|
614
|
-
provider = explicit_provider or str(worker.get("agent") or "").strip()
|
|
615
|
-
if provider in _SESSION_JSONL_PROVIDERS:
|
|
616
|
-
return ""
|
|
617
|
-
runner = str(worker.get("runner") or "").strip()
|
|
618
|
-
if runner and runner != "cli-wrapper":
|
|
619
|
-
return ""
|
|
620
|
-
if not explicit_provider and worker_id == "report-writer":
|
|
621
|
-
provider = "codex"
|
|
622
|
-
return provider if provider in provider_wrappers() else ""
|
|
623
|
-
|
|
624
|
-
|
|
625
612
|
def _cli_sessions_for_windows(
|
|
626
613
|
provider: str,
|
|
627
614
|
project_root: Path,
|
|
@@ -1139,6 +1126,9 @@ def _attach_cli_usage(block: dict, cli: dict) -> None:
|
|
|
1139
1126
|
"cliSessionPaths",
|
|
1140
1127
|
"cliNote",
|
|
1141
1128
|
"cliExecutionStatus",
|
|
1129
|
+
"requestedSessionIds",
|
|
1130
|
+
"missingSessionIds",
|
|
1131
|
+
"unattributedCliSessionPaths",
|
|
1142
1132
|
):
|
|
1143
1133
|
if key in cli:
|
|
1144
1134
|
block[key] = cli[key]
|
|
@@ -1723,16 +1713,29 @@ def collect(
|
|
|
1723
1713
|
project_root: Path | None = None,
|
|
1724
1714
|
*,
|
|
1725
1715
|
incremental: bool = True,
|
|
1716
|
+
manifest: dict | None = None,
|
|
1726
1717
|
) -> dict:
|
|
1727
1718
|
from okstra_ctl.application.collect_usage import collect_usage
|
|
1728
1719
|
from okstra_ctl.ports.usage_accounting import UsageRequest
|
|
1729
1720
|
from okstra_ctl.registry.host_registry import default_host_registry
|
|
1730
1721
|
|
|
1731
1722
|
state = json.loads(team_state_path.read_text())
|
|
1723
|
+
run_manifest = manifest if manifest is not None else manifest_for_usage(team_state_path, state=state)
|
|
1724
|
+
if not run_manifest and "usageAccountingPolicy" in state:
|
|
1725
|
+
raise ValueError(f"run manifest not found for {team_state_path}")
|
|
1726
|
+
policy = usage_accounting_policy(run_manifest)
|
|
1727
|
+
if "usageAccountingPolicy" in state and state["usageAccountingPolicy"] != policy:
|
|
1728
|
+
raise ValueError("team-state usageAccountingPolicy does not match its run manifest")
|
|
1732
1729
|
cwd = project_root or _infer_project_root(team_state_path, state)
|
|
1733
1730
|
adapter = default_host_registry().resolve(str(state.get("leadRuntime") or ""))
|
|
1734
1731
|
request = UsageRequest(team_state_path, cwd, incremental)
|
|
1735
|
-
|
|
1732
|
+
updated = collect_usage(request, adapter.usage_accounting()).payload
|
|
1733
|
+
if policy == "advisory":
|
|
1734
|
+
updated["usageAccountingPolicy"] = policy
|
|
1735
|
+
errors, _missing = usage_diagnostics(updated)
|
|
1736
|
+
if errors:
|
|
1737
|
+
raise ValueError("; ".join(errors))
|
|
1738
|
+
return updated
|
|
1736
1739
|
|
|
1737
1740
|
|
|
1738
1741
|
def _infer_project_root(team_state_path: Path, state: dict) -> Path:
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Usage policy and diagnostics shared by collection and report validation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import warnings
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from okstra_ctl.json_boundary import JsonBoundaryError, load_owned_object
|
|
10
|
+
|
|
11
|
+
from .blocks import (
|
|
12
|
+
cli_usage_required,
|
|
13
|
+
finite_non_negative,
|
|
14
|
+
usage_is_measured_zero,
|
|
15
|
+
usage_participants,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def usage_accounting_policy(manifest: Mapping[str, Any]) -> str:
|
|
20
|
+
policy = manifest.get("usageAccountingPolicy", "strict")
|
|
21
|
+
if policy not in ("strict", "advisory"):
|
|
22
|
+
raise ValueError(f"unknown usageAccountingPolicy: {policy!r}")
|
|
23
|
+
return policy
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _usage_path(raw: str, project_root: object, team_state_path: Path) -> Path | None:
|
|
27
|
+
candidate = Path(raw)
|
|
28
|
+
if not candidate.parts:
|
|
29
|
+
return None
|
|
30
|
+
if candidate.is_absolute():
|
|
31
|
+
return candidate.resolve()
|
|
32
|
+
if isinstance(project_root, str) and Path(project_root).is_absolute():
|
|
33
|
+
return (Path(project_root) / candidate).resolve()
|
|
34
|
+
if candidate.parts[0] in ("state", "manifests"):
|
|
35
|
+
return (team_state_path.parent.parent / candidate).resolve()
|
|
36
|
+
artifact_home = next((parent for parent in team_state_path.parents if parent.name == ".okstra"), None)
|
|
37
|
+
if artifact_home is not None and candidate.parts[0] == ".okstra":
|
|
38
|
+
return (artifact_home.parent / candidate).resolve()
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def manifest_for_usage(team_state_path: Path, *, state: Mapping[str, Any] | None = None) -> Mapping[str, Any]:
|
|
43
|
+
"""Resolve the run by its recorded team-state path, including legacy names."""
|
|
44
|
+
manifests = team_state_path.parent.parent / "manifests"
|
|
45
|
+
recorded_manifest = (state or {}).get("runManifestPath")
|
|
46
|
+
if isinstance(recorded_manifest, str) and recorded_manifest.strip():
|
|
47
|
+
path = _usage_path(recorded_manifest, (state or {}).get("projectRoot"), team_state_path)
|
|
48
|
+
if path is None or path.parent != manifests.resolve():
|
|
49
|
+
raise ValueError(f"run manifest is outside the team-state run: {recorded_manifest}")
|
|
50
|
+
manifest = load_owned_object(path, artifact="run manifest")
|
|
51
|
+
recorded = manifest.get("teamStatePath")
|
|
52
|
+
if not isinstance(recorded, str) or not recorded.strip() or _usage_path(
|
|
53
|
+
recorded, manifest.get("projectRoot"), team_state_path,
|
|
54
|
+
) != team_state_path.resolve():
|
|
55
|
+
raise ValueError(f"run manifest does not reference {team_state_path}")
|
|
56
|
+
return manifest
|
|
57
|
+
matches = []
|
|
58
|
+
paths = sorted(manifests.glob("run-manifest-*.json"))
|
|
59
|
+
if (manifests / "run.json").is_file():
|
|
60
|
+
paths.append(manifests / "run.json")
|
|
61
|
+
for path in paths:
|
|
62
|
+
try:
|
|
63
|
+
manifest = load_owned_object(path, artifact="run manifest")
|
|
64
|
+
except JsonBoundaryError as exc:
|
|
65
|
+
expected = "run-manifest-" + team_state_path.name.removeprefix("team-state-")
|
|
66
|
+
if path.name == expected:
|
|
67
|
+
raise
|
|
68
|
+
warnings.warn(f"Unreadable manifest skipped while resolving usage policy: {exc}", RuntimeWarning)
|
|
69
|
+
continue
|
|
70
|
+
recorded = manifest.get("teamStatePath")
|
|
71
|
+
if not isinstance(recorded, str) or not recorded.strip():
|
|
72
|
+
continue
|
|
73
|
+
if _usage_path(recorded, manifest.get("projectRoot"), team_state_path) == team_state_path.resolve():
|
|
74
|
+
matches.append(manifest)
|
|
75
|
+
if len(matches) > 1:
|
|
76
|
+
raise ValueError(f"multiple run manifests reference {team_state_path}")
|
|
77
|
+
if matches:
|
|
78
|
+
return matches[0]
|
|
79
|
+
return {}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def usage_diagnostics(team_state: Mapping[str, Any]) -> tuple[list[str], list[dict[str, str]]]:
|
|
83
|
+
"""Separate observed absence from malformed or ambiguous accounting."""
|
|
84
|
+
errors = []
|
|
85
|
+
for key in ("workers", "additionalWorkerUsage"):
|
|
86
|
+
if key not in team_state:
|
|
87
|
+
continue
|
|
88
|
+
rows = team_state[key]
|
|
89
|
+
if not isinstance(rows, list):
|
|
90
|
+
errors.append(f"team-state.{key} must be a list.")
|
|
91
|
+
continue
|
|
92
|
+
for index, row in enumerate(rows):
|
|
93
|
+
if not isinstance(row, Mapping):
|
|
94
|
+
errors.append(f"team-state.{key}[{index}] must be an object.")
|
|
95
|
+
if errors:
|
|
96
|
+
return errors, []
|
|
97
|
+
summary = team_state.get("usageSummary")
|
|
98
|
+
errors = _summary_errors(summary)
|
|
99
|
+
missing: list[dict[str, str]] = []
|
|
100
|
+
lead_usage = team_state.get("leadUsage")
|
|
101
|
+
entries = [("leadUsage", lead_usage, cli_usage_required({"usage": lead_usage}))]
|
|
102
|
+
entries.extend(
|
|
103
|
+
(f"worker {worker.get('role') or worker.get('workerId') or '<unknown>'}", worker.get("usage"),
|
|
104
|
+
cli_usage_required(worker))
|
|
105
|
+
for worker in usage_participants(team_state)
|
|
106
|
+
)
|
|
107
|
+
if isinstance(summary, Mapping) and isinstance(summary.get("unattributedWorkerUsage"), Mapping):
|
|
108
|
+
entries.append(("unattributed worker usage", summary["unattributedWorkerUsage"], False))
|
|
109
|
+
for target, usage, needs_cli in entries:
|
|
110
|
+
invalid, absent = _classify_usage(target, usage, needs_cli)
|
|
111
|
+
errors.extend(invalid)
|
|
112
|
+
missing.extend(absent)
|
|
113
|
+
return errors, missing
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _summary_errors(summary: object) -> list[str]:
|
|
117
|
+
errors = []
|
|
118
|
+
if (not isinstance(summary, Mapping) or not isinstance(summary.get("collectedAt"), str)
|
|
119
|
+
or not summary["collectedAt"].strip()):
|
|
120
|
+
errors.append("team-state.usageSummary.collectedAt is missing — usage collection was skipped.")
|
|
121
|
+
if not isinstance(summary, Mapping):
|
|
122
|
+
return errors
|
|
123
|
+
for key in ("leadTotalTokens", "workerTotalTokens", "grandTotalTokens",
|
|
124
|
+
"leadCacheReadTokens", "workerCacheReadTokens", "grandCacheReadTokens",
|
|
125
|
+
"leadBillableEquivalentTokens", "workerBillableEquivalentTokens", "grandBillableEquivalentTokens"):
|
|
126
|
+
value = summary.get(key)
|
|
127
|
+
if value is not None and not finite_non_negative(value):
|
|
128
|
+
errors.append(f"usageSummary.{key} must be null or a finite non-negative number.")
|
|
129
|
+
costs = summary.get("estimatedCostUsd")
|
|
130
|
+
if isinstance(costs, Mapping):
|
|
131
|
+
for key in ("lead", "claudeWorkers", "cliWorkers", "grandTotal"):
|
|
132
|
+
if costs.get(key) is not None and not finite_non_negative(costs[key]):
|
|
133
|
+
errors.append(f"usageSummary.estimatedCostUsd.{key} must be null or a finite non-negative number.")
|
|
134
|
+
elif "estimatedCostUsd" in summary:
|
|
135
|
+
errors.append("usageSummary.estimatedCostUsd must be an object.")
|
|
136
|
+
if summary.get("unattributedTeamSessions") or summary.get("unattributedWorkerUsage"):
|
|
137
|
+
errors.append("team-state usage attribution is ambiguous for unassigned worker sessions.")
|
|
138
|
+
return errors
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _classify_usage(target: str, usage: object, needs_cli: bool) -> tuple[list[str], list[dict[str, str]]]:
|
|
142
|
+
errors = []
|
|
143
|
+
missing = []
|
|
144
|
+
if (not isinstance(usage, Mapping) or not isinstance(usage.get("source"), str)
|
|
145
|
+
or not usage["source"].strip()):
|
|
146
|
+
return [f"{target}: usage source is missing or malformed."], missing
|
|
147
|
+
if not isinstance(usage.get("collectedAt"), str) or not usage["collectedAt"].strip():
|
|
148
|
+
return [f"{target}: usage collectedAt is missing."], missing
|
|
149
|
+
if any(key in usage and (not isinstance(usage[key], str) or not usage[key].strip()) for key in ("note", "cliNote")):
|
|
150
|
+
return [f"{target}: usage notes must be non-empty strings."], missing
|
|
151
|
+
if usage.get("attribution") == "ambiguous" or usage.get("unattributedCliSessionPaths"):
|
|
152
|
+
return [f"{target}: CLI session attribution is ambiguous."], missing
|
|
153
|
+
unavailable = usage["source"] == "unavailable"
|
|
154
|
+
for key in ("totalTokens", "cliTotalTokens", "estimatedCostUsd", "cliEstimatedCostUsd", "billableEquivalentTokens", "cacheReadTokens"):
|
|
155
|
+
value = usage.get(key)
|
|
156
|
+
if value is None and (key != "totalTokens" or unavailable):
|
|
157
|
+
continue
|
|
158
|
+
if not finite_non_negative(value):
|
|
159
|
+
errors.append(f"{target}: {key} must be a finite non-negative number.")
|
|
160
|
+
session_ids = usage.get("missingSessionIds", [])
|
|
161
|
+
if not isinstance(session_ids, list) or any(not isinstance(item, str) or not item.strip() for item in session_ids):
|
|
162
|
+
errors.append(f"{target}: missingSessionIds must be an array of non-empty session IDs.")
|
|
163
|
+
if errors:
|
|
164
|
+
return errors, missing
|
|
165
|
+
|
|
166
|
+
def absent(item: str, reason: str) -> None:
|
|
167
|
+
missing.append({"item": item, "risk": reason, "owner": "Okstra lead", "source": "token-usage"})
|
|
168
|
+
|
|
169
|
+
if unavailable:
|
|
170
|
+
note = usage.get("note")
|
|
171
|
+
if not isinstance(note, str) or not note.strip():
|
|
172
|
+
errors.append(f"{target}: unavailable usage has no recorded reason.")
|
|
173
|
+
else:
|
|
174
|
+
absent(target, note + (f" Missing session IDs: {', '.join(session_ids)}." if session_ids else ""))
|
|
175
|
+
return errors, missing
|
|
176
|
+
if session_ids:
|
|
177
|
+
absent(f"{target} sessions", f"Session usage is partial; no transcript was found for session IDs: {', '.join(session_ids)}.")
|
|
178
|
+
if needs_cli and usage.get("cliTotalTokens") is None:
|
|
179
|
+
note = usage.get("cliNote")
|
|
180
|
+
if not isinstance(note, str) or not note.strip():
|
|
181
|
+
errors.append(f"{target}: missing CLI usage has no recorded reason.")
|
|
182
|
+
else:
|
|
183
|
+
absent(f"{target} CLI usage", note)
|
|
184
|
+
host_cost_applies = not usage["source"].endswith("-cli") or "estimatedCostUsd" in usage
|
|
185
|
+
measured_zero = usage_is_measured_zero(usage)
|
|
186
|
+
if host_cost_applies and usage.get("estimatedCostUsd") is None and not measured_zero:
|
|
187
|
+
absent(f"{target} billing cost", "Billing cost is unavailable for the recorded host usage/model.")
|
|
188
|
+
if (needs_cli and usage.get("cliTotalTokens") is not None and usage.get("cliEstimatedCostUsd") is None
|
|
189
|
+
and not usage_is_measured_zero(usage, cli=True)):
|
|
190
|
+
absent(f"{target} CLI billing cost", usage.get("cliNote") or "CLI billing cost is unavailable for the recorded usage/model.")
|
|
191
|
+
if not measured_zero and usage.get("billableEquivalentTokens") is None:
|
|
192
|
+
absent(f"{target} billable token equivalent", "Billable token equivalence is unavailable for the recorded usage/model.")
|
|
193
|
+
return errors, missing
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"type": "object",
|
|
4
|
+
"additionalProperties": false,
|
|
5
|
+
"required": ["schemaVersion", "autoRegister", "scope", "sources", "includeProjects", "excludeProjects", "includeGroups", "excludeGroups"],
|
|
6
|
+
"properties": {
|
|
7
|
+
"schemaVersion": {"type": "integer", "const": 1},
|
|
8
|
+
"autoRegister": {"type": "boolean"},
|
|
9
|
+
"scope": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/text"}]},
|
|
10
|
+
"sources": {"type": "array", "uniqueItems": true, "items": {"enum": ["memory", "manager", "task"]}},
|
|
11
|
+
"includeProjects": {"$ref": "#/$defs/names"},
|
|
12
|
+
"excludeProjects": {"$ref": "#/$defs/names"},
|
|
13
|
+
"includeGroups": {"$ref": "#/$defs/names"},
|
|
14
|
+
"excludeGroups": {"$ref": "#/$defs/names"}
|
|
15
|
+
},
|
|
16
|
+
"$defs": {
|
|
17
|
+
"text": {"type": "string", "minLength": 1, "pattern": "\\S"},
|
|
18
|
+
"names": {"type": "array", "maxItems": 1000, "uniqueItems": true, "items": {"$ref": "#/$defs/text"}}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"type": "object",
|
|
4
|
+
"additionalProperties": false,
|
|
5
|
+
"required": ["schemaVersion", "scope", "recordKey", "requestId", "expectedPreviousRevision", "source", "record", "nodes", "relations"],
|
|
6
|
+
"properties": {
|
|
7
|
+
"schemaVersion": {"const": 1},
|
|
8
|
+
"scope": {"$ref": "#/$defs/text"},
|
|
9
|
+
"recordKey": {"$ref": "#/$defs/text"},
|
|
10
|
+
"requestId": {"$ref": "#/$defs/text"},
|
|
11
|
+
"expectedPreviousRevision": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/text"}]},
|
|
12
|
+
"source": {
|
|
13
|
+
"type": "object",
|
|
14
|
+
"additionalProperties": false,
|
|
15
|
+
"required": ["kind", "id", "revision", "locator"],
|
|
16
|
+
"properties": {
|
|
17
|
+
"kind": {"$ref": "#/$defs/text"},
|
|
18
|
+
"id": {"$ref": "#/$defs/text"},
|
|
19
|
+
"revision": {"$ref": "#/$defs/text"},
|
|
20
|
+
"locator": {"$ref": "#/$defs/text"}
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"record": {
|
|
24
|
+
"type": "object",
|
|
25
|
+
"additionalProperties": false,
|
|
26
|
+
"required": ["title", "summary"],
|
|
27
|
+
"properties": {
|
|
28
|
+
"title": {"$ref": "#/$defs/text"},
|
|
29
|
+
"summary": {"$ref": "#/$defs/text"},
|
|
30
|
+
"body": {"type": "string"},
|
|
31
|
+
"type": {"enum": ["context", "work", "decision", "investigation", "verification", "follow-up"]}
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"nodes": {"type": "array", "items": {"$ref": "#/$defs/node"}, "uniqueItems": true, "maxItems": 1000},
|
|
35
|
+
"relations": {"type": "array", "items": {"$ref": "#/$defs/relation"}, "uniqueItems": true, "maxItems": 4000}
|
|
36
|
+
},
|
|
37
|
+
"$defs": {
|
|
38
|
+
"text": {"type": "string", "minLength": 1, "pattern": "\\S"},
|
|
39
|
+
"node": {
|
|
40
|
+
"type": "object",
|
|
41
|
+
"additionalProperties": false,
|
|
42
|
+
"required": ["key", "kind", "scope", "title"],
|
|
43
|
+
"properties": {
|
|
44
|
+
"key": {"$ref": "#/$defs/text"},
|
|
45
|
+
"ref": {"$ref": "#/$defs/text"},
|
|
46
|
+
"kind": {"enum": ["concept", "flow", "entity", "project", "repository", "commit", "ticket", "task", "artifact", "record"]},
|
|
47
|
+
"scope": {"$ref": "#/$defs/text"},
|
|
48
|
+
"title": {"$ref": "#/$defs/text"}
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"relation": {
|
|
52
|
+
"type": "object",
|
|
53
|
+
"additionalProperties": false,
|
|
54
|
+
"required": ["from", "to", "kind", "reason", "evidence", "standing"],
|
|
55
|
+
"properties": {
|
|
56
|
+
"from": {"$ref": "#/$defs/text"},
|
|
57
|
+
"to": {"$ref": "#/$defs/text"},
|
|
58
|
+
"kind": {"$ref": "#/$defs/text"},
|
|
59
|
+
"reason": {"$ref": "#/$defs/text"},
|
|
60
|
+
"evidence": {"type": "array", "items": {"$ref": "#/$defs/text"}, "minItems": 1},
|
|
61
|
+
"standing": {"enum": ["observed", "user-stated", "candidate"]}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|