okstra 0.232.0 → 0.234.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 -283
- 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/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.mjs +2 -17
- package/dist/lib/memory-auto-register.mjs.map +1 -1
- 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/docs/architecture/storage-model.md +55 -5
- package/docs/architecture.md +10 -4
- package/docs/cli.md +320 -3
- package/docs/contributor-change-matrix.md +1 -2
- package/docs/project-structure-overview.md +34 -43
- package/package.json +1 -1
- package/runtime/BUILD.json +2 -2
- package/runtime/agents/operations/trace-interface-review.json +6 -0
- package/runtime/agents/operations/trace-scope-review.json +6 -0
- package/runtime/prompts/coding-preflight/authoring-checks.md +1 -1
- package/runtime/prompts/coding-preflight/clean-code.md +18 -20
- package/runtime/prompts/coding-preflight/overview.md +1 -1
- package/runtime/prompts/duties/code-reviewer.json +1 -1
- 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 +2 -2
- package/runtime/prompts/profiles/_common-contract.md +1 -1
- package/runtime/python/okstra_ctl/agent/invocation.py +1 -0
- package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +66 -26
- package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +23 -8
- package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +28 -10
- package/runtime/python/okstra_ctl/agent/prompt_cli/results.py +8 -11
- package/runtime/python/okstra_ctl/agent/standalone.py +12 -0
- package/runtime/python/okstra_ctl/analysis_packet.py +22 -11
- package/runtime/python/okstra_ctl/business_flow/cli.py +60 -6
- package/runtime/python/okstra_ctl/business_flow/contracts.py +12 -1
- package/runtime/python/okstra_ctl/business_flow/engine.py +17 -5
- package/runtime/python/okstra_ctl/business_flow/history.py +60 -0
- package/runtime/python/okstra_ctl/business_flow/source.py +35 -2
- package/runtime/python/okstra_ctl/business_flow/store.py +51 -14
- package/runtime/python/okstra_ctl/business_flow/sweep.py +124 -0
- package/runtime/python/okstra_ctl/code_review_census.py +93 -2
- 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 +13 -0
- package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
- package/runtime/python/okstra_ctl/code_review_target.py +140 -15
- package/runtime/python/okstra_ctl/coverage_census.py +11 -2
- 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/domain/role.py +1 -0
- package/runtime/python/okstra_ctl/doyouknow/cli.py +9 -9
- package/runtime/python/okstra_ctl/doyouknow/config.py +2 -2
- package/runtime/python/okstra_ctl/doyouknow/group_view.py +152 -0
- package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +4 -3
- package/runtime/python/okstra_ctl/doyouknow/source_store.py +2 -2
- package/runtime/python/okstra_ctl/doyouknow/sources/business.py +116 -0
- package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +48 -9
- package/runtime/python/okstra_ctl/doyouknow/sync.py +34 -9
- package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
- package/runtime/python/okstra_ctl/fixed_text.py +10 -0
- 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 +33 -6
- package/runtime/python/okstra_ctl/manager_cli.py +122 -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_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 +42 -3
- 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 +3 -0
- 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/implementation/host-rules.md +3 -3
- package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +8 -6
- package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +1 -1
- 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 +12 -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 +5 -5
- 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/project_group.py +175 -0
- package/runtime/python/okstra_ctl/project_group_cli.py +62 -0
- package/runtime/python/okstra_ctl/render.py +28 -2
- package/runtime/python/okstra_ctl/report_assembly.py +38 -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 +179 -7
- package/runtime/python/okstra_ctl/report_projections.py +64 -18
- package/runtime/python/okstra_ctl/report_synthesis_packet.py +86 -36
- package/runtime/python/okstra_ctl/run.py +43 -35
- 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/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/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_project/state.py +20 -0
- 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/business-flow-v1.schema.json +3 -0
- package/runtime/schemas/doyouknow-config-v1.schema.json +1 -1
- 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 +58 -50
- package/runtime/skills/okstra-code-review/references/census-rules.md +6 -6
- package/runtime/skills/okstra-code-review/references/review-calibration.md +8 -12
- package/runtime/skills/okstra-discussion/SKILL.md +22 -38
- package/runtime/skills/okstra-explain-flow/SKILL.md +33 -4
- package/runtime/skills/okstra-manager/SKILL.md +24 -0
- package/runtime/skills/okstra-memory/SKILL.md +1 -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/doyouknow/group-view.css +103 -0
- package/runtime/templates/doyouknow/group-view.js +317 -0
- package/runtime/templates/doyouknow/group-view.template.html +72 -0
- 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/validators/checks/fixtures-02.py +25 -33
- package/runtime/validators/validate-run.py +93 -36
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Project task projection for TypeScript-owned implementation traces."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import re
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from okstra_project import StateError, parse_task_key, project_json_path, resolve_task_root_read_only
|
|
14
|
+
from okstra_project.dirs import OKSTRA_RELATIVE, contained_relative_path
|
|
15
|
+
|
|
16
|
+
from .direct_work import TASK_MANIFEST_MAX_BYTES, load_direct_task, publish_direct_work, record_direct_work
|
|
17
|
+
from .json_boundary import ReadBudget, load_owned_object, read_bounded_bytes, write_owned_object_atomic
|
|
18
|
+
from .run_context import task_mutex
|
|
19
|
+
|
|
20
|
+
TRACE_ATTEMPT_LIMIT = 128
|
|
21
|
+
TRACE_REQUEST_MAX_BYTES = 16 * 1024
|
|
22
|
+
TRACE_METADATA_LIST_LIMITS = {"tags": (20, 64), "changedFiles": (100, 512), "references": (20, 512), "relatedTasks": (50, 384)}
|
|
23
|
+
TRACE_METADATA_TEXT_LIMITS = {"title": 200, "summary": 2000}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class TraceSource:
|
|
28
|
+
frontmatter: dict
|
|
29
|
+
text: str
|
|
30
|
+
digest: str
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def read_task_trace(project_root: Path, trace_path: str, task_key: str, *, budget: ReadBudget | None = None) -> TraceSource:
|
|
34
|
+
root = project_root.resolve()
|
|
35
|
+
relative = Path(trace_path)
|
|
36
|
+
if relative.is_absolute() or len(relative.parts) != 4 or relative.parts[:2] != (*OKSTRA_RELATIVE.parts, "traces"):
|
|
37
|
+
raise ValueError("Trace path is outside project traces")
|
|
38
|
+
if trace_path != relative.as_posix() or contained_relative_path(trace_path, root) != trace_path or relative.suffix != ".md":
|
|
39
|
+
raise ValueError("Trace path is not canonical or contained")
|
|
40
|
+
content = read_bounded_bytes(root / relative, max_bytes=TASK_MANIFEST_MAX_BYTES, artifact="implementation trace", budget=budget)
|
|
41
|
+
text = content.decode("utf-8")
|
|
42
|
+
match = re.match(r"^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)", text)
|
|
43
|
+
header = json.loads(match[1]) if match else None
|
|
44
|
+
if not isinstance(header, dict) or not isinstance(header.get("task"), dict) or header["task"].get("key") != task_key:
|
|
45
|
+
raise ValueError("Trace owner does not match the task")
|
|
46
|
+
return TraceSource(header, text, hashlib.sha256(content).hexdigest())
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _validate_request(project_root: Path, request: dict) -> dict:
|
|
50
|
+
if not isinstance(request, dict) or len(json.dumps(request, ensure_ascii=False).encode()) > TRACE_REQUEST_MAX_BYTES:
|
|
51
|
+
raise ValueError("Trace request exceeds its input limit")
|
|
52
|
+
identity = request.get("task")
|
|
53
|
+
if (not isinstance(identity, dict) or set(identity) != {"key"}
|
|
54
|
+
or not isinstance(identity.get("key"), str) or len(identity["key"]) > 384):
|
|
55
|
+
raise ValueError("Trace task identity is invalid")
|
|
56
|
+
project_id, _, _ = parse_task_key(identity["key"])
|
|
57
|
+
project = load_owned_object(project_json_path(project_root), artifact="project config", max_bytes=TASK_MANIFEST_MAX_BYTES)
|
|
58
|
+
if project.get("projectId") != project_id:
|
|
59
|
+
raise ValueError("Trace task belongs to another project")
|
|
60
|
+
created = request.get("createdAt")
|
|
61
|
+
if isinstance(created, bool) or not isinstance(created, (int, float)) or not math.isfinite(created) or created < 0:
|
|
62
|
+
raise ValueError("Trace creation timestamp is invalid")
|
|
63
|
+
if (type(request.get("completed")) is not bool or not isinstance(request.get("currentStep"), str)
|
|
64
|
+
or len(request["currentStep"]) > 64):
|
|
65
|
+
raise ValueError("Trace projection state is invalid")
|
|
66
|
+
if not isinstance(request.get("tracePath"), str) or len(request["tracePath"]) > 1024:
|
|
67
|
+
raise ValueError("Trace path is invalid")
|
|
68
|
+
source = read_task_trace(project_root, request["tracePath"], identity["key"])
|
|
69
|
+
source_created = datetime.fromisoformat(source.frontmatter.get("createdAt", ""))
|
|
70
|
+
if source_created.tzinfo is None or round(source_created.timestamp() * 1000) != created:
|
|
71
|
+
raise ValueError("Trace creation timestamp does not match its source")
|
|
72
|
+
if source.digest != request.get("digest") or source.frontmatter.get("currentStep") != request["currentStep"]:
|
|
73
|
+
raise ValueError("Trace projection does not match its saved source")
|
|
74
|
+
steps = source.frontmatter.get("steps", {})
|
|
75
|
+
integration = steps.get("integration", {}) if isinstance(steps, dict) else {}
|
|
76
|
+
completed = isinstance(integration, dict) and integration.get("status") == "done"
|
|
77
|
+
if request["completed"] != completed:
|
|
78
|
+
raise ValueError("Trace completion projection does not match its source")
|
|
79
|
+
task = source.frontmatter["task"]
|
|
80
|
+
if set(task) != {"key", *TRACE_METADATA_LIST_LIMITS, *TRACE_METADATA_TEXT_LIMITS}:
|
|
81
|
+
raise ValueError("Trace metadata fields are invalid")
|
|
82
|
+
for field, limit in TRACE_METADATA_TEXT_LIMITS.items():
|
|
83
|
+
if not isinstance(task.get(field), str) or len(task[field]) > limit:
|
|
84
|
+
raise ValueError("Trace text metadata is invalid")
|
|
85
|
+
for field, (count, size) in TRACE_METADATA_LIST_LIMITS.items():
|
|
86
|
+
values = task.get(field)
|
|
87
|
+
if not isinstance(values, list) or len(values) > count or any(not isinstance(value, str) or not value.strip() or len(value) > size for value in values):
|
|
88
|
+
raise ValueError("Trace list metadata is invalid")
|
|
89
|
+
if request["completed"] and not task["summary"].strip():
|
|
90
|
+
raise ValueError("Completed traces require a feature summary")
|
|
91
|
+
return {**request, "task": task}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _attempts(manifest: dict) -> list[dict]:
|
|
95
|
+
attempts = manifest.get("implementationTraces", [])
|
|
96
|
+
if not isinstance(attempts, list) or len(attempts) > TRACE_ATTEMPT_LIMIT or any(not isinstance(item, dict) for item in attempts):
|
|
97
|
+
raise ValueError("Trace attempt history is invalid")
|
|
98
|
+
for item in attempts:
|
|
99
|
+
created = item.get("createdAt")
|
|
100
|
+
if (not isinstance(item.get("path"), str) or not isinstance(item.get("digest"), str)
|
|
101
|
+
or not isinstance(item.get("currentStep"), str) or type(item.get("completed")) is not bool
|
|
102
|
+
or isinstance(created, bool) or not isinstance(created, (int, float)) or not math.isfinite(created)):
|
|
103
|
+
raise ValueError("Trace attempt record is invalid")
|
|
104
|
+
return attempts
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _is_synced(manifest: dict, request: dict) -> bool:
|
|
108
|
+
return any(item.get("path") == request["tracePath"] and item.get("digest") == request["digest"]
|
|
109
|
+
and item.get("syncedDigest") == request["digest"] for item in _attempts(manifest))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _save_projection(path: Path, manifest: dict) -> None:
|
|
113
|
+
if len((json.dumps(manifest, indent=2, ensure_ascii=False) + "\n").encode()) > TASK_MANIFEST_MAX_BYTES:
|
|
114
|
+
raise ValueError("Task manifest exceeds its input limit")
|
|
115
|
+
write_owned_object_atomic(path, manifest, artifact="task manifest")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _record_attempt(manifest: dict, request: dict) -> bool:
|
|
119
|
+
path = request["tracePath"]
|
|
120
|
+
attempts = _attempts(manifest)
|
|
121
|
+
previous = next((item for item in attempts if item.get("path") == path), {})
|
|
122
|
+
others = [item for item in attempts if item.get("path") != path]
|
|
123
|
+
if len(others) >= TRACE_ATTEMPT_LIMIT:
|
|
124
|
+
raise ValueError("Trace attempt history is full")
|
|
125
|
+
attempt = {"path": path, "digest": request["digest"], "createdAt": request["createdAt"],
|
|
126
|
+
"currentStep": request["currentStep"], "completed": request["completed"]}
|
|
127
|
+
if previous.get("digest") == request["digest"] and previous.get("syncedDigest"):
|
|
128
|
+
attempt["syncedDigest"] = previous["syncedDigest"]
|
|
129
|
+
attempts = sorted([*others, attempt], key=lambda item: (item["createdAt"], item["path"]))
|
|
130
|
+
manifest["implementationTraces"] = attempts
|
|
131
|
+
if attempts[-1]["path"] != path:
|
|
132
|
+
return False
|
|
133
|
+
manifest.update({"executionKind": "implementation-trace", "implementationTracePath": path,
|
|
134
|
+
"traceDigest": request["digest"], "traceMetadata": {key: value for key, value in request["task"].items() if key != "key"}})
|
|
135
|
+
metadata = manifest["traceMetadata"]
|
|
136
|
+
manifest["relatedTasks"] = list(dict.fromkeys([*manifest.get("relatedTasks", []), *metadata["relatedTasks"]]))
|
|
137
|
+
status = "done" if request["completed"] else "in-progress"
|
|
138
|
+
if previous.get("digest") != request["digest"] or manifest.get("workStatus") != status:
|
|
139
|
+
manifest["workStatusUpdatedAt"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
140
|
+
manifest["updatedAt"] = manifest["workStatusUpdatedAt"]
|
|
141
|
+
manifest["workStatus"] = status
|
|
142
|
+
manifest["workStatusNote"] = metadata["summary"]
|
|
143
|
+
return True
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def trace_task_sync_status(project_root: Path, request: dict) -> dict:
|
|
147
|
+
_validate_request(project_root, request)
|
|
148
|
+
key = request["task"]["key"]
|
|
149
|
+
if resolve_task_root_read_only(project_root, key) is None:
|
|
150
|
+
return {"taskKey": key, "taskSync": "pending"}
|
|
151
|
+
_, manifest = load_direct_task(project_root, {"taskKey": key}, allow_create=False)
|
|
152
|
+
synced = _is_synced(manifest, request)
|
|
153
|
+
return {"taskKey": key, "taskSync": "synced" if synced else "pending"}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def synchronize_trace_task(project_root: Path, request: dict) -> dict:
|
|
157
|
+
_validate_request(project_root, request)
|
|
158
|
+
key = request["task"]["key"]
|
|
159
|
+
with task_mutex(key):
|
|
160
|
+
request = _validate_request(project_root, request)
|
|
161
|
+
path, manifest = load_direct_task(project_root, {"taskKey": key}, allow_create=True)
|
|
162
|
+
if _is_synced(manifest, request):
|
|
163
|
+
return {"taskKey": key, "taskSync": "synced"}
|
|
164
|
+
latest = _record_attempt(manifest, request)
|
|
165
|
+
_save_projection(path, manifest)
|
|
166
|
+
if latest and request["completed"]:
|
|
167
|
+
record_direct_work(project_root, path, manifest)
|
|
168
|
+
_save_projection(path, manifest)
|
|
169
|
+
publish_direct_work(project_root, manifest)
|
|
170
|
+
for attempt in manifest["implementationTraces"]:
|
|
171
|
+
if attempt["path"] == request["tracePath"]:
|
|
172
|
+
attempt["syncedDigest"] = request["digest"]
|
|
173
|
+
_save_projection(path, manifest)
|
|
174
|
+
return {"taskKey": key, "taskSync": "synced"}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def main(argv: list[str] | None = None) -> int:
|
|
178
|
+
parser = argparse.ArgumentParser(prog="trace task projection")
|
|
179
|
+
parser.add_argument("operation", choices=("sync", "status"))
|
|
180
|
+
parser.add_argument("--project-root", required=True, type=Path)
|
|
181
|
+
parser.add_argument("--request", required=True)
|
|
182
|
+
args = parser.parse_args(argv)
|
|
183
|
+
try:
|
|
184
|
+
if len(args.request.encode()) > TRACE_REQUEST_MAX_BYTES:
|
|
185
|
+
raise ValueError("Trace request exceeds its input limit")
|
|
186
|
+
request = json.loads(args.request)
|
|
187
|
+
operation = synchronize_trace_task if args.operation == "sync" else trace_task_sync_status
|
|
188
|
+
result = operation(args.project_root.resolve(), request)
|
|
189
|
+
except (OSError, ValueError, TypeError, KeyError, RecursionError, StateError):
|
|
190
|
+
print(json.dumps({"error": {"code": "TASK_SYNC_FAILED", "message": "Trace task projection failed; retry synchronization after checking its source and project."}}))
|
|
191
|
+
return 1
|
|
192
|
+
print(json.dumps(result))
|
|
193
|
+
return 0
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
if __name__ == "__main__":
|
|
197
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Shared shape validation for a displayed wizard confirmation receipt."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def validate_wizard_authorization(record: object) -> None:
|
|
6
|
+
if not isinstance(record, dict) or (
|
|
7
|
+
record.get("schemaVersion") != "1.0"
|
|
8
|
+
or record.get("source") != "wizard-confirmation"
|
|
9
|
+
or record.get("response") != "proceed"
|
|
10
|
+
or not isinstance(record.get("prompt"), str)
|
|
11
|
+
or not record["prompt"].strip()
|
|
12
|
+
or not isinstance(record.get("scope"), dict)
|
|
13
|
+
):
|
|
14
|
+
raise ValueError("user authorization requires the displayed prompt, proceed response, and scope")
|
|
@@ -16,7 +16,7 @@ from okstra_ctl.worktree import (
|
|
|
16
16
|
)
|
|
17
17
|
from okstra_ctl.work_categories import resolve_work_category
|
|
18
18
|
|
|
19
|
-
from .render import render_args
|
|
19
|
+
from .render import render_args, wizard_persist_actions
|
|
20
20
|
from .ids import S_CONFIRM, _STAGE_SCOPED_TASK_TYPES
|
|
21
21
|
from .state import (
|
|
22
22
|
Prompt,
|
|
@@ -109,12 +109,13 @@ def _build_confirm(state: WizardState) -> Prompt:
|
|
|
109
109
|
같은 블록을 낸다.
|
|
110
110
|
"""
|
|
111
111
|
t = _p(state.workspace_root, "confirm")
|
|
112
|
-
if not state.confirmation_prompt:
|
|
112
|
+
if not state.confirmation_prompt or state.confirmation_persist_actions is None:
|
|
113
113
|
state.confirmation_stages = resolve_wizard_stage_intent(
|
|
114
114
|
task_type=state.task_type, selected_stage=state.selected_stage,
|
|
115
115
|
selected_stages=state.selected_stages,
|
|
116
116
|
).chain_stages
|
|
117
117
|
state.confirmation_scope = render_args(state)
|
|
118
|
+
state.confirmation_persist_actions = wizard_persist_actions(state)
|
|
118
119
|
state.confirmation_prompt = f"{confirmation_block(state)}\n\n{t['label']}"
|
|
119
120
|
return Prompt(
|
|
120
121
|
step=S_CONFIRM, kind="pick",
|
|
@@ -139,19 +140,22 @@ def _submit_confirm(state: WizardState, value: str) -> Optional[str]:
|
|
|
139
140
|
selected_stages=state.selected_stages,
|
|
140
141
|
).chain_stages
|
|
141
142
|
if (not state.confirmation_prompt or state.confirmation_scope != render_args(state)
|
|
142
|
-
or state.confirmation_stages != stages
|
|
143
|
+
or state.confirmation_stages != stages
|
|
144
|
+
or state.confirmation_persist_actions != wizard_persist_actions(state)):
|
|
143
145
|
raise WizardError("confirmation scope changed; display the confirmation again before proceeding")
|
|
144
146
|
state.user_authorization = {
|
|
145
147
|
"schemaVersion": "1.0", "source": "wizard-confirmation",
|
|
146
148
|
"response": value, "prompt": state.confirmation_prompt,
|
|
147
149
|
"scope": state.confirmation_scope.copy(),
|
|
148
150
|
"stageScope": state.confirmation_stages.split(",") if state.confirmation_stages else [],
|
|
151
|
+
"persistActions": [action.copy() for action in state.confirmation_persist_actions or []],
|
|
149
152
|
}
|
|
150
153
|
else:
|
|
151
154
|
state.user_authorization = {}
|
|
152
155
|
state.confirmation_prompt = ""
|
|
153
156
|
state.confirmation_scope = {}
|
|
154
157
|
state.confirmation_stages = ""
|
|
158
|
+
state.confirmation_persist_actions = None
|
|
155
159
|
state.confirmed = value == "proceed"
|
|
156
160
|
return f"confirm: {value}"
|
|
157
161
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Read one confirmed wizard snapshot for bundle preparation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from okstra_ctl.run import prepare_exception_applies
|
|
8
|
+
from okstra_ctl.user_authorization import validate_wizard_authorization
|
|
9
|
+
|
|
10
|
+
from .outcome import wizard_outcome
|
|
11
|
+
from .state import WizardError
|
|
12
|
+
from .statefile import load_state_file
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class ConfirmedWizardLaunch:
|
|
17
|
+
project_root: str
|
|
18
|
+
render_argv: tuple[str, ...]
|
|
19
|
+
persist_actions: tuple[dict[str, str], ...]
|
|
20
|
+
chain_stages: str
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_confirmed_launch(
|
|
24
|
+
path: Path, *, stage: str = "", qa_waiver: str = "", tdd_bypass: str = "",
|
|
25
|
+
) -> ConfirmedWizardLaunch:
|
|
26
|
+
if not path.is_absolute():
|
|
27
|
+
raise WizardError("wizard state file path must be absolute")
|
|
28
|
+
state = load_state_file(path)
|
|
29
|
+
if state.user_authorization != {}:
|
|
30
|
+
validate_wizard_authorization(state.user_authorization)
|
|
31
|
+
outcome = wizard_outcome(state)
|
|
32
|
+
for option, value in (("--qa-waiver", qa_waiver), ("--tdd-bypass", tdd_bypass)):
|
|
33
|
+
if value and not prepare_exception_applies(state.task_type, option):
|
|
34
|
+
raise WizardError(f"{option} is not supported for confirmed task type {state.task_type}")
|
|
35
|
+
actions = outcome["persistActions"]
|
|
36
|
+
recorded_actions = state.user_authorization.get("persistActions")
|
|
37
|
+
if (actions or recorded_actions) and recorded_actions != actions:
|
|
38
|
+
raise WizardError("template save scope changed or was not recorded; confirm the save action again")
|
|
39
|
+
argv = outcome["renderArgv"]
|
|
40
|
+
chain = outcome["orchestration"]["chainStages"]
|
|
41
|
+
if stage:
|
|
42
|
+
if state.task_type != "implementation":
|
|
43
|
+
raise WizardError("wizard stage override is implementation-only")
|
|
44
|
+
if stage not in chain.split(","):
|
|
45
|
+
raise WizardError("requested stage is outside the confirmed stage scope")
|
|
46
|
+
argv[argv.index("--stage") + 1] = stage
|
|
47
|
+
return ConfirmedWizardLaunch(
|
|
48
|
+
project_root=state.project_root,
|
|
49
|
+
render_argv=tuple(argv),
|
|
50
|
+
persist_actions=tuple(actions),
|
|
51
|
+
chain_stages=chain,
|
|
52
|
+
)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Internal JSON transport for confirmed wizard bundle inputs."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from .launch import load_confirmed_launch
|
|
10
|
+
from .state import WizardError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def main(argv: list[str]) -> int:
|
|
14
|
+
parser = argparse.ArgumentParser()
|
|
15
|
+
parser.add_argument("--state-file", required=True)
|
|
16
|
+
parser.add_argument("--stage", default="")
|
|
17
|
+
parser.add_argument("--qa-waiver", default="")
|
|
18
|
+
parser.add_argument("--tdd-bypass", default="")
|
|
19
|
+
args = parser.parse_args(argv)
|
|
20
|
+
try:
|
|
21
|
+
launch = load_confirmed_launch(
|
|
22
|
+
Path(args.state_file), stage=args.stage,
|
|
23
|
+
qa_waiver=args.qa_waiver, tdd_bypass=args.tdd_bypass,
|
|
24
|
+
)
|
|
25
|
+
except (OSError, ValueError, WizardError) as exc:
|
|
26
|
+
print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False))
|
|
27
|
+
return 1
|
|
28
|
+
print(json.dumps({
|
|
29
|
+
"ok": True,
|
|
30
|
+
"projectRoot": launch.project_root,
|
|
31
|
+
"renderArgv": launch.render_argv,
|
|
32
|
+
"persistActions": launch.persist_actions,
|
|
33
|
+
"chainStages": launch.chain_stages,
|
|
34
|
+
}, ensure_ascii=False))
|
|
35
|
+
return 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == "__main__":
|
|
39
|
+
raise SystemExit(main(sys.argv[1:]))
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
"""승인된 상태에서 실행 인자와 확인 화면을 조립한다."""
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
|
+
from pathlib import Path
|
|
4
5
|
from typing import Any
|
|
5
6
|
|
|
7
|
+
from okstra_ctl.phases.catalog import PhaseAssetError, host_rules
|
|
8
|
+
|
|
6
9
|
from .confirmation import confirmation_block
|
|
7
|
-
from .render import _stage_intent, render_args
|
|
10
|
+
from .render import _stage_intent, render_args, wizard_persist_actions
|
|
8
11
|
from .state import WizardError, WizardState
|
|
9
12
|
|
|
10
13
|
|
|
@@ -22,33 +25,31 @@ def _render_argv(rendered: dict[str, Any], *, host_runtime: str) -> list[str]:
|
|
|
22
25
|
return argv
|
|
23
26
|
|
|
24
27
|
|
|
25
|
-
def _wizard_persist_actions(state: WizardState) -> list[dict[str, str]]:
|
|
26
|
-
if state.task_type != "release-handoff":
|
|
27
|
-
return []
|
|
28
|
-
from okstra_ctl.phases.release_handoff.wizard import pr_template_persist_actions
|
|
29
|
-
|
|
30
|
-
return pr_template_persist_actions(state)
|
|
31
|
-
|
|
32
|
-
|
|
33
28
|
def wizard_outcome(state: WizardState) -> dict[str, Any]:
|
|
34
29
|
"""Public outcome for callers that need launch data and follow-up writes.
|
|
35
30
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
`renderArgs` made the renderer reject the wizard's own output.
|
|
31
|
+
Execution inputs and orchestration signals stay separate so compatibility
|
|
32
|
+
callers cannot send stage-chain instructions to the prepare parser.
|
|
33
|
+
Native skills pass the confirmed state file to bundle preparation instead
|
|
34
|
+
of reconstructing these compatibility argument views.
|
|
41
35
|
"""
|
|
42
36
|
if state.aborted:
|
|
43
37
|
raise WizardError("wizard was aborted by the user — outcome is unavailable")
|
|
44
38
|
if state.confirmed is not True:
|
|
45
39
|
raise WizardError("wizard is not complete — outcome is unavailable")
|
|
46
40
|
rendered = render_args(state)
|
|
41
|
+
try:
|
|
42
|
+
host_rules_file = host_rules(Path(state.workspace_root), state.task_type)
|
|
43
|
+
except PhaseAssetError as exc:
|
|
44
|
+
raise WizardError(str(exc)) from exc
|
|
47
45
|
return {
|
|
48
46
|
"renderArgs": rendered,
|
|
49
47
|
"renderArgv": _render_argv(rendered, host_runtime=state.host_runtime),
|
|
50
|
-
"orchestration": {
|
|
51
|
-
|
|
48
|
+
"orchestration": {
|
|
49
|
+
"chainStages": _stage_intent(state).chain_stages,
|
|
50
|
+
"hostRulesPath": str(host_rules_file.resolve()) if host_rules_file is not None else "",
|
|
51
|
+
},
|
|
52
|
+
"persistActions": wizard_persist_actions(state),
|
|
52
53
|
"confirmationText": state.user_authorization.get("prompt") or confirmation_block(state),
|
|
53
54
|
"userAuthorization": state.user_authorization or None,
|
|
54
55
|
}
|
|
@@ -651,7 +651,7 @@ STEPS: list[Step] = [
|
|
|
651
651
|
or bool(s.fix_cycle))
|
|
652
652
|
and s.confirmed is None),
|
|
653
653
|
build=_build_confirm, submit=_submit_confirm,
|
|
654
|
-
owns=("confirmed", "edit_target", "confirmation_prompt", "confirmation_stages", "confirmation_scope", "user_authorization")),
|
|
654
|
+
owns=("confirmed", "edit_target", "confirmation_prompt", "confirmation_stages", "confirmation_scope", "confirmation_persist_actions", "user_authorization")),
|
|
655
655
|
# 되감기는 이 step 뒤에서 일어나 answered 에 남는다. 반복 가능이 아니면 두 번째
|
|
656
656
|
# 수정에서 건너뛰어져 위저드가 미확정인 채 done 을 냈다(dev-11126 planning).
|
|
657
657
|
Step(S_EDIT_TARGET,
|
|
@@ -149,3 +149,11 @@ def render_args(state: WizardState) -> dict[str, Any]:
|
|
|
149
149
|
raise WizardError("confirmed scope changed; obtain confirmation for the changed inputs")
|
|
150
150
|
rendered["user-authorization-json"] = json.dumps(state.user_authorization, ensure_ascii=False)
|
|
151
151
|
return rendered
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def wizard_persist_actions(state: WizardState) -> list[dict[str, str]]:
|
|
155
|
+
if state.task_type != "release-handoff":
|
|
156
|
+
return []
|
|
157
|
+
from okstra_ctl.phases.release_handoff.wizard import pr_template_persist_actions
|
|
158
|
+
|
|
159
|
+
return pr_template_persist_actions(state)
|
|
@@ -158,6 +158,7 @@ class WizardState:
|
|
|
158
158
|
confirmation_stages: str = ""
|
|
159
159
|
confirmation_prompt: str = ""
|
|
160
160
|
confirmation_scope: dict[str, Any] = field(default_factory=dict)
|
|
161
|
+
confirmation_persist_actions: list[dict[str, str]] | None = None
|
|
161
162
|
user_authorization: dict[str, Any] = field(default_factory=dict)
|
|
162
163
|
edit_target: str = ""
|
|
163
164
|
# terminal: user picked 중단 — no further prompt ever applies
|
|
@@ -676,7 +677,7 @@ _FIELD_DEFAULTS: dict[str, Any] = {
|
|
|
676
677
|
"fix_cycle": "",
|
|
677
678
|
"reasoning_effort": "",
|
|
678
679
|
"confirmed": None, "edit_target": "", "confirmation_prompt": "", "confirmation_stages": "",
|
|
679
|
-
"confirmation_scope": {}, "user_authorization": {},
|
|
680
|
+
"confirmation_scope": {}, "confirmation_persist_actions": None, "user_authorization": {},
|
|
680
681
|
}
|
|
681
682
|
|
|
682
683
|
|
|
@@ -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
|
|
|
@@ -401,6 +419,8 @@ def task_read_side_snapshot(project_root: Path, task_key: str) -> dict:
|
|
|
401
419
|
workflow = {}
|
|
402
420
|
return {
|
|
403
421
|
"projectRoot": identity["projectRoot"],
|
|
422
|
+
**implementation_trace_projection(manifest),
|
|
423
|
+
**({"implementationTraces": manifest.get("implementationTraces", [])} if manifest.get("executionKind") == "implementation-trace" else {}),
|
|
404
424
|
"taskKey": manifest.get("taskKey"),
|
|
405
425
|
"taskType": manifest.get("taskType"),
|
|
406
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))
|