okstra 0.232.0 → 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 -283
- package/dist/cli-registry.mjs +8 -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 +36 -5
- package/docs/architecture.md +10 -4
- package/docs/cli.md +279 -2
- package/docs/contributor-change-matrix.md +1 -2
- package/docs/project-structure-overview.md +31 -41
- 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/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/sources/manager.py +48 -9
- 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 +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/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/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 +6 -2
- 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/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,381 @@
|
|
|
1
|
+
"""Prepare every specialist invocation of a standalone code review in one call."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .code_review_census import ASSIGNMENT_AXES, subset_review_census, write_review_assignments
|
|
10
|
+
from .code_review_scope import review_scope, shared_review_policy
|
|
11
|
+
from .operation_invocation import require_distinct_providers
|
|
12
|
+
|
|
13
|
+
PURPOSE = "code-review"
|
|
14
|
+
BATCH_SCHEMA_VERSION = 1
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class ReviewSlot:
|
|
19
|
+
ordinal: int
|
|
20
|
+
provider: str
|
|
21
|
+
model_ref: str
|
|
22
|
+
model: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class ReviewSlots:
|
|
27
|
+
duty_id: str
|
|
28
|
+
role_id: str
|
|
29
|
+
slots: tuple[ReviewSlot, ...]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class AttemptRequest:
|
|
34
|
+
"""One more attempt for a team and axis: full assignment when `cells` is empty."""
|
|
35
|
+
|
|
36
|
+
team: int
|
|
37
|
+
axis: str
|
|
38
|
+
kind: str
|
|
39
|
+
cells: tuple[str, ...] = ()
|
|
40
|
+
reasons: Mapping[str, str] | None = None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class _Batch:
|
|
45
|
+
project: Path
|
|
46
|
+
root: Path
|
|
47
|
+
record: dict
|
|
48
|
+
|
|
49
|
+
def path(self, relative: str) -> Path:
|
|
50
|
+
return self.project / relative
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def read_review_slots(path: Path) -> ReviewSlots:
|
|
54
|
+
"""Read `okstra agent-prompt resolve-operation --operation code-review --json` output."""
|
|
55
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
56
|
+
if not isinstance(payload, dict) or payload.get("operation") != PURPOSE:
|
|
57
|
+
raise ValueError("slots file is not a code-review resolve-operation result")
|
|
58
|
+
rows = payload.get("slots")
|
|
59
|
+
if not isinstance(rows, list) or not rows:
|
|
60
|
+
raise ValueError("slots file has no slots")
|
|
61
|
+
slots = []
|
|
62
|
+
for row in rows:
|
|
63
|
+
if not isinstance(row, dict) or not all(
|
|
64
|
+
isinstance(row.get(key), str) and row[key] for key in ("provider", "modelRef", "model")
|
|
65
|
+
) or type(row.get("ordinal")) is not int:
|
|
66
|
+
raise ValueError("slots file has a malformed slot")
|
|
67
|
+
slots.append(ReviewSlot(row["ordinal"], row["provider"], row["modelRef"], row["model"]))
|
|
68
|
+
if len({slot.ordinal for slot in slots}) != len(slots):
|
|
69
|
+
raise ValueError("slots file repeats a team ordinal")
|
|
70
|
+
require_distinct_providers([slot.provider for slot in slots])
|
|
71
|
+
duty, role = payload.get("dutyId"), payload.get("roleId")
|
|
72
|
+
if not isinstance(duty, str) or not isinstance(role, str) or not duty or not role:
|
|
73
|
+
raise ValueError("slots file has no duty or role")
|
|
74
|
+
return ReviewSlots(duty, role, tuple(slots))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def invocation_id(review_id: str, ordinal: int, axis: str, attempt: int) -> str:
|
|
78
|
+
return f"{review_id}-t{ordinal}-{axis}-a{attempt}"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def prepare_review_batch(
|
|
82
|
+
*,
|
|
83
|
+
project_root: Path,
|
|
84
|
+
review_id: str,
|
|
85
|
+
census: Path,
|
|
86
|
+
policy: Path,
|
|
87
|
+
base: str,
|
|
88
|
+
head: str,
|
|
89
|
+
slots_path: Path,
|
|
90
|
+
brief: Path,
|
|
91
|
+
host_runtime: str,
|
|
92
|
+
resources: Sequence[str] = (),
|
|
93
|
+
previous_batch: Path | None = None,
|
|
94
|
+
) -> Path:
|
|
95
|
+
"""Write assigned censuses, prompts and the batch record; return the record path."""
|
|
96
|
+
from .agent.prompt_cli.inputs import _is_slug
|
|
97
|
+
|
|
98
|
+
project = project_root.resolve()
|
|
99
|
+
root = project / ".okstra" / "agent-invocations" / PURPOSE
|
|
100
|
+
if not _is_slug(review_id):
|
|
101
|
+
raise ValueError("review id must be a lowercase slug")
|
|
102
|
+
slots = read_review_slots(slots_path)
|
|
103
|
+
census = census.absolute()
|
|
104
|
+
if census.resolve(strict=True) != (root / f"{review_id}.census.md").resolve():
|
|
105
|
+
raise ValueError(f"census must be {root / f'{review_id}.census.md'}")
|
|
106
|
+
batch_path = root / f"{review_id}.batch.json"
|
|
107
|
+
shared_review_policy(census, policy)
|
|
108
|
+
assignments = write_review_assignments(project, census)
|
|
109
|
+
record = {
|
|
110
|
+
"schemaVersion": BATCH_SCHEMA_VERSION, "reviewId": review_id,
|
|
111
|
+
"projectRoot": str(project), "base": base, "head": head,
|
|
112
|
+
"census": _relative(census, project), "policy": _relative(policy.absolute(), project),
|
|
113
|
+
"resources": list(resources), "hostRuntime": host_runtime,
|
|
114
|
+
"dutyId": slots.duty_id, "roleId": slots.role_id,
|
|
115
|
+
"brief": brief.read_text(encoding="utf-8").rstrip("\n"), "items": [],
|
|
116
|
+
}
|
|
117
|
+
batch = _Batch(project, root, record)
|
|
118
|
+
prior = _prior_rounds(project, record, previous_batch) if previous_batch else {}
|
|
119
|
+
context = _assignment_context(record, [slot.provider for slot in slots.slots])
|
|
120
|
+
for slot in slots.slots:
|
|
121
|
+
for axis in ASSIGNMENT_AXES:
|
|
122
|
+
if axis in assignments:
|
|
123
|
+
record["items"].append(_prepare_item(
|
|
124
|
+
batch, context, slot.ordinal, slot.provider, slot.model_ref, axis, 1, "initial",
|
|
125
|
+
assignments[axis], "", prior.get((slot.ordinal, axis, slot.provider, slot.model_ref)),
|
|
126
|
+
))
|
|
127
|
+
text = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
|
|
128
|
+
if batch_path.exists():
|
|
129
|
+
existing = json.loads(batch_path.read_text(encoding="utf-8"))
|
|
130
|
+
existing["items"] = [item for item in existing["items"] if item["attempt"] == 1]
|
|
131
|
+
if existing != record:
|
|
132
|
+
raise ValueError(f"existing file differs; choose a new review id: {batch_path}")
|
|
133
|
+
return batch_path
|
|
134
|
+
batch_path.write_text(text, encoding="utf-8")
|
|
135
|
+
return batch_path
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def gap_fill_requests(
|
|
139
|
+
batch_record: Mapping, state: Mapping, rejected: Mapping[int, Sequence[str]],
|
|
140
|
+
) -> tuple[list[AttemptRequest], list[str]]:
|
|
141
|
+
"""Requests for every team and axis whose latest attempt left cells open.
|
|
142
|
+
|
|
143
|
+
Returns the requests and the `team/axis` pairs stopped because their last
|
|
144
|
+
gap-fill did not reduce the open cells.
|
|
145
|
+
"""
|
|
146
|
+
census_cells = _cells_by_item(batch_record)
|
|
147
|
+
requests: list[AttemptRequest] = []
|
|
148
|
+
stopped: list[str] = []
|
|
149
|
+
for (team, axis), item in sorted(latest_items(batch_record).items()):
|
|
150
|
+
row = state["items"].get(item["invocationId"], {})
|
|
151
|
+
own = set(census_cells[item["invocationId"]])
|
|
152
|
+
rejects = [cell for cell in rejected.get(team, ()) if cell in _axis_cells(batch_record, team, axis)]
|
|
153
|
+
if row.get("state") in ("failed", "stalled"):
|
|
154
|
+
requests.append(AttemptRequest(team, axis, "gap-fill", tuple(sorted(own))))
|
|
155
|
+
continue
|
|
156
|
+
if row.get("state") != "completed":
|
|
157
|
+
continue
|
|
158
|
+
missing = dict(row["audit"]["missing"])
|
|
159
|
+
missing.update((cell, "rejected by the lead") for cell in rejects)
|
|
160
|
+
if not missing:
|
|
161
|
+
continue
|
|
162
|
+
if item["attempt"] > 1 and item.get("kind") == "gap-fill" and len(row["audit"]["missing"]) >= len(own):
|
|
163
|
+
stopped.append(f"{team}/{axis}")
|
|
164
|
+
continue
|
|
165
|
+
requests.append(AttemptRequest(team, axis, "gap-fill", tuple(sorted(missing)), missing))
|
|
166
|
+
return requests, stopped
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def add_review_attempts(project_root: Path, batch_path: Path, state: Mapping,
|
|
170
|
+
requests: Sequence[AttemptRequest]) -> list[dict]:
|
|
171
|
+
"""Prepare one new attempt per request and append it to the batch record.
|
|
172
|
+
|
|
173
|
+
The caller holds the review's state lock; the batch record only grows.
|
|
174
|
+
"""
|
|
175
|
+
batch = _load(project_root, batch_path)
|
|
176
|
+
record = batch.record
|
|
177
|
+
latest = latest_items(record)
|
|
178
|
+
context = _assignment_context(record, sorted({item["provider"] for item in record["items"]}))
|
|
179
|
+
added = []
|
|
180
|
+
for request in requests:
|
|
181
|
+
previous = latest[(request.team, request.axis)]
|
|
182
|
+
attempt = max(item["attempt"] for item in record["items"]
|
|
183
|
+
if (item["team"], item["axis"]) == (request.team, request.axis)) + 1
|
|
184
|
+
full = batch.path(_first_attempt(record, request.team, request.axis)["census"])
|
|
185
|
+
census = full
|
|
186
|
+
if request.cells and set(request.cells) != set(_axis_cells(record, request.team, request.axis)):
|
|
187
|
+
census = batch.root / f"{record['reviewId']}.{request.axis}.t{request.team}.a{attempt}.census.md"
|
|
188
|
+
_write_exact(census, subset_review_census(full.read_text(encoding="utf-8"), request.cells))
|
|
189
|
+
item = _prepare_item(
|
|
190
|
+
batch, context, request.team, previous["provider"], previous["modelRef"], request.axis,
|
|
191
|
+
attempt, request.kind, census,
|
|
192
|
+
_continuation(batch, previous, state, request), None, previous["wrapper"],
|
|
193
|
+
)
|
|
194
|
+
record["items"].append(item)
|
|
195
|
+
added.append(item)
|
|
196
|
+
if added:
|
|
197
|
+
temporary = batch_path.with_name(batch_path.name + ".partial")
|
|
198
|
+
temporary.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
199
|
+
temporary.replace(batch_path)
|
|
200
|
+
return added
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def latest_items(record: Mapping) -> dict[tuple[int, str], dict]:
|
|
204
|
+
latest: dict[tuple[int, str], dict] = {}
|
|
205
|
+
for item in record["items"]:
|
|
206
|
+
key = (item["team"], item["axis"])
|
|
207
|
+
if key not in latest or item["attempt"] > latest[key]["attempt"]:
|
|
208
|
+
latest[key] = item
|
|
209
|
+
return latest
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def render_batch_summary(batch_path: Path) -> str:
|
|
213
|
+
record = json.loads(batch_path.read_text(encoding="utf-8"))
|
|
214
|
+
rows = [f"Batch: {batch_path}\n", f"Items: {len(record['items'])}\n"]
|
|
215
|
+
for item in record["items"]:
|
|
216
|
+
rows.append(
|
|
217
|
+
f"Item: {item['invocationId']} | team {item['team']} | {item['modelRef']} | "
|
|
218
|
+
f"{item['axis']} | {item['prompt']}\n"
|
|
219
|
+
)
|
|
220
|
+
return "".join(rows)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _prepare_item(
|
|
224
|
+
batch: _Batch, context, team: int, provider: str, model_ref: str, axis: str, attempt: int,
|
|
225
|
+
kind: str, census: Path, continuation: str, previous: Mapping | None,
|
|
226
|
+
wrapper: str | None = None,
|
|
227
|
+
) -> dict:
|
|
228
|
+
from .agent.invocation import AgentInvocationError, verify_agent_invocation
|
|
229
|
+
from .agent.standalone import StandaloneInvocationRequest, prepare_standalone_invocation
|
|
230
|
+
from .code_review_invocation import CodeReviewInputs
|
|
231
|
+
from .registry.provider_registry import default_provider_registry
|
|
232
|
+
|
|
233
|
+
record, project, root = batch.record, batch.project, batch.root
|
|
234
|
+
policy = batch.path(record["policy"])
|
|
235
|
+
identity = invocation_id(record["reviewId"], team, axis, attempt)
|
|
236
|
+
prior = {}
|
|
237
|
+
if previous:
|
|
238
|
+
prior = {"previous_head": previous["head"], "previous_census": batch.path(previous["census"]),
|
|
239
|
+
"completions": [batch.path(path) for path in previous["completions"]]}
|
|
240
|
+
scope = review_scope(project, census, record["base"], record["head"], [],
|
|
241
|
+
policy=shared_review_policy(census, policy), **prior).render()
|
|
242
|
+
instruction = root / f"{identity}.instructions.md"
|
|
243
|
+
_write_exact(instruction, (
|
|
244
|
+
f"{record['brief']}\n\n## Assignment\n\n"
|
|
245
|
+
f"- Review ID: {record['reviewId']}\n"
|
|
246
|
+
f"- Model team: {team} ({model_ref})\n"
|
|
247
|
+
f"- Specialist axis: {axis}\n"
|
|
248
|
+
f"- Attempt: {attempt} ({kind})\n"
|
|
249
|
+
f"- Full census (context only): {record['census']}\n"
|
|
250
|
+
f"- Assigned census: {_relative(census, project)}\n\n"
|
|
251
|
+
f"{continuation}"
|
|
252
|
+
f"## Inspection scope\n\n```text\n{scope}```\n"
|
|
253
|
+
))
|
|
254
|
+
try:
|
|
255
|
+
prepared = prepare_standalone_invocation(StandaloneInvocationRequest(
|
|
256
|
+
project_root=project, invocation_id=identity, audience=record["dutyId"],
|
|
257
|
+
purpose=PURPOSE, context=context, provider=provider,
|
|
258
|
+
model_role=record["roleId"], model=model_ref.split("/", 1)[1],
|
|
259
|
+
instruction_path=instruction, prompt_path=root / f"{identity}.prompt.md",
|
|
260
|
+
requested_runner="cli-wrapper",
|
|
261
|
+
review_inputs=CodeReviewInputs(policy, census, record["base"], record["head"],
|
|
262
|
+
tuple(record["resources"])),
|
|
263
|
+
))
|
|
264
|
+
errors = verify_agent_invocation(
|
|
265
|
+
prepared.metadata_path, project_root=project, expected_run_manifest_path=None,
|
|
266
|
+
)
|
|
267
|
+
if errors:
|
|
268
|
+
raise ValueError("; ".join(errors))
|
|
269
|
+
except (AgentInvocationError, OSError, RuntimeError, ValueError) as exc:
|
|
270
|
+
done = ", ".join(str(item["invocationId"]) for item in record["items"]) or "none"
|
|
271
|
+
raise ValueError(f"{identity}: {exc}; already prepared and reused by an "
|
|
272
|
+
f"identical rerun: {done}") from exc
|
|
273
|
+
assignment = prepared.assignment
|
|
274
|
+
return {
|
|
275
|
+
"team": team, "axis": axis, "attempt": attempt, "kind": kind, "invocationId": identity,
|
|
276
|
+
"provider": provider, "modelRef": model_ref,
|
|
277
|
+
"modelExecutionValue": assignment.model_execution_value,
|
|
278
|
+
"runner": assignment.runner, "role": record["roleId"],
|
|
279
|
+
"wrapper": wrapper or default_provider_registry().resolve(provider).wrapper,
|
|
280
|
+
"census": _relative(census, project),
|
|
281
|
+
"instructions": _relative(instruction, project),
|
|
282
|
+
"prompt": _relative(prepared.prompt_path, project),
|
|
283
|
+
"metadata": _relative(prepared.metadata_path, project),
|
|
284
|
+
**({"previousBatch": previous["batch"]} if previous else {}),
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _continuation(batch: _Batch, previous: Mapping, state: Mapping, request: AttemptRequest) -> str:
|
|
289
|
+
from .agent.invocation import verify_standalone_completion
|
|
290
|
+
|
|
291
|
+
lines = [f"## Continuation\n\nThis attempt replaces attempt {previous['attempt']} "
|
|
292
|
+
f"({previous['invocationId']}) for the cells in the assigned census only.\n"]
|
|
293
|
+
for cell, reason in sorted((request.reasons or {}).items()):
|
|
294
|
+
lines.append(f"- {cell}: {reason}\n")
|
|
295
|
+
row = state["items"].get(previous["invocationId"], {})
|
|
296
|
+
if row.get("completion"):
|
|
297
|
+
body = verify_standalone_completion(
|
|
298
|
+
batch.path(row["completion"]), project_root=batch.project, expected_purpose=PURPOSE,
|
|
299
|
+
).returned_body
|
|
300
|
+
lines.append(f"\nVerified result of attempt {previous['attempt']}:\n\n````text\n{body.rstrip()}\n````\n")
|
|
301
|
+
elif row.get("reason"):
|
|
302
|
+
lines.append(f"\nAttempt {previous['attempt']} ended without a usable result: {row['reason']}\n")
|
|
303
|
+
return "".join(lines) + "\n"
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _prior_rounds(project: Path, record: Mapping, previous_batch: Path) -> dict[tuple, dict]:
|
|
307
|
+
"""Completions of a previous round that this round may offer as carry candidates."""
|
|
308
|
+
prior = _load(project, previous_batch)
|
|
309
|
+
old = prior.record
|
|
310
|
+
if old["base"] != record["base"] or old["policy"] != record["policy"]:
|
|
311
|
+
return {}
|
|
312
|
+
state_path = prior.root / f"{old['reviewId']}.state.json"
|
|
313
|
+
if not state_path.exists():
|
|
314
|
+
return {}
|
|
315
|
+
state = json.loads(state_path.read_text(encoding="utf-8"))
|
|
316
|
+
rounds: dict[tuple, dict] = {}
|
|
317
|
+
for (team, axis), first in ((key, _first_attempt(old, *key)) for key in latest_items(old)):
|
|
318
|
+
completions = [state["items"][item["invocationId"]]["completion"]
|
|
319
|
+
for item in sorted(old["items"], key=lambda item: -item["attempt"])
|
|
320
|
+
if (item["team"], item["axis"]) == (team, axis)
|
|
321
|
+
and state["items"].get(item["invocationId"], {}).get("state") == "completed"]
|
|
322
|
+
if completions:
|
|
323
|
+
rounds[(team, axis, first["provider"], first["modelRef"])] = {
|
|
324
|
+
"head": old["head"], "census": first["census"], "completions": completions,
|
|
325
|
+
"batch": _relative(previous_batch, project),
|
|
326
|
+
}
|
|
327
|
+
return rounds
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _assignment_context(record: Mapping, providers: Sequence[str]):
|
|
331
|
+
from .assignment_environment import load_assignment_context
|
|
332
|
+
from .dispatch_state import detect_terminal_backend
|
|
333
|
+
|
|
334
|
+
return load_assignment_context(
|
|
335
|
+
host_runtime=record["hostRuntime"], terminal_backend=detect_terminal_backend(),
|
|
336
|
+
execution_provider_ids=tuple(providers), include_native_provider=False,
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _load(project_root: Path, batch_path: Path) -> _Batch:
|
|
341
|
+
project = project_root.resolve()
|
|
342
|
+
root = project / ".okstra" / "agent-invocations" / PURPOSE
|
|
343
|
+
path = batch_path.resolve(strict=True)
|
|
344
|
+
if path.parent != root.resolve() or not path.name.endswith(".batch.json"):
|
|
345
|
+
raise ValueError("batch must be <review-id>.batch.json in the code-review artifact directory")
|
|
346
|
+
record = json.loads(path.read_text(encoding="utf-8"))
|
|
347
|
+
if record.get("schemaVersion") != BATCH_SCHEMA_VERSION or record.get("projectRoot") != str(project):
|
|
348
|
+
raise ValueError("batch belongs to another project root or schema")
|
|
349
|
+
return _Batch(project, root, record)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _first_attempt(record: Mapping, team: int, axis: str) -> dict:
|
|
353
|
+
return next(item for item in record["items"]
|
|
354
|
+
if (item["team"], item["axis"], item["attempt"]) == (team, axis, 1))
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _axis_cells(record: Mapping, team: int, axis: str) -> set[str]:
|
|
358
|
+
from .review_verdicts import read_review_census
|
|
359
|
+
|
|
360
|
+
project = Path(record["projectRoot"])
|
|
361
|
+
return set(read_review_census(project / _first_attempt(record, team, axis)["census"]).cells)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _cells_by_item(record: Mapping) -> dict[str, list[str]]:
|
|
365
|
+
from .review_verdicts import read_review_census
|
|
366
|
+
|
|
367
|
+
project = Path(record["projectRoot"])
|
|
368
|
+
return {item["invocationId"]: list(read_review_census(project / item["census"]).cells)
|
|
369
|
+
for item in record["items"]}
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _relative(path: Path, project: Path) -> str:
|
|
373
|
+
return path.resolve().relative_to(project).as_posix()
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _write_exact(path: Path, text: str) -> None:
|
|
377
|
+
if path.exists():
|
|
378
|
+
if path.read_text(encoding="utf-8") != text:
|
|
379
|
+
raise ValueError(f"existing file differs; choose a new review id: {path}")
|
|
380
|
+
return
|
|
381
|
+
path.write_text(text, encoding="utf-8")
|