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
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Bind standalone reviews to selected frozen rules and source integrity."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, replace
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import TYPE_CHECKING, Mapping
|
|
7
|
+
|
|
8
|
+
from .json_boundary import load_owned_object, load_owned_object_snapshot
|
|
9
|
+
from .qa_procedures import content_digest
|
|
10
|
+
from .review_policy import (
|
|
11
|
+
code_review_guidance_paths,
|
|
12
|
+
review_policy_context,
|
|
13
|
+
render_review_rule_catalog,
|
|
14
|
+
render_selected_review_policy,
|
|
15
|
+
review_policy_errors,
|
|
16
|
+
select_review_policy,
|
|
17
|
+
)
|
|
18
|
+
from .review_verdicts import _head_tree, parse_review_census
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from .agent.invocation import AgentInvocationRequest
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class CodeReviewInputs:
|
|
26
|
+
policy_path: Path
|
|
27
|
+
census_path: Path
|
|
28
|
+
base: str
|
|
29
|
+
head: str
|
|
30
|
+
resources: tuple[str, ...] = ()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _validate_census_binding(text: str, inputs: CodeReviewInputs, digest: str) -> None:
|
|
34
|
+
digest_lines = [line for line in text.splitlines() if line.startswith("Review policy digest: ")]
|
|
35
|
+
expected = "Review policy digest: " + digest
|
|
36
|
+
if digest_lines != [expected]:
|
|
37
|
+
raise ValueError("assigned census and shared review policy digest differ")
|
|
38
|
+
resource_lines = [line.removeprefix("Review resources: ").strip()
|
|
39
|
+
for line in text.splitlines() if line.startswith("Review resources: ")]
|
|
40
|
+
if len(resource_lines) != 1:
|
|
41
|
+
raise ValueError("assigned census requires one explicit resource selection")
|
|
42
|
+
declared = [] if resource_lines == ["-"] else [part.strip() for part in resource_lines[0].split(";")]
|
|
43
|
+
if len(set(declared)) != len(declared) or sorted(declared) != sorted(inputs.resources):
|
|
44
|
+
raise ValueError("review resource selection differs from the assigned census")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _review_payload(request: AgentInvocationRequest) -> dict:
|
|
48
|
+
inputs = request.review_inputs
|
|
49
|
+
if inputs is None:
|
|
50
|
+
raise ValueError("standalone code review requires frozen policy, census, base and head")
|
|
51
|
+
root = request.project_root.resolve()
|
|
52
|
+
for path in (inputs.policy_path, inputs.census_path):
|
|
53
|
+
path.resolve(strict=True).relative_to(root)
|
|
54
|
+
tree = _head_tree(root, inputs.head)
|
|
55
|
+
base = _head_tree(root, inputs.base).commit
|
|
56
|
+
if tree._git("merge-base", "--is-ancestor", base, tree.commit).returncode:
|
|
57
|
+
raise ValueError("review base is not an ancestor of head")
|
|
58
|
+
census_text = inputs.census_path.read_text(encoding="utf-8")
|
|
59
|
+
stored_policy = load_owned_object_snapshot(
|
|
60
|
+
inputs.policy_path, artifact="shared frozen review policy",
|
|
61
|
+
schema={"type": "object"}, validate_cross_fields=review_policy_errors,
|
|
62
|
+
)
|
|
63
|
+
_validate_census_binding(census_text, inputs, content_digest(stored_policy.raw_bytes))
|
|
64
|
+
census = parse_review_census(census_text)
|
|
65
|
+
targets = tuple(dict.fromkeys(cell.target.partition(":")[0] for cell in census.cells.values()))
|
|
66
|
+
paths, manifests = review_policy_context(root, tree.commit, targets, base=base)
|
|
67
|
+
for target in targets:
|
|
68
|
+
exists_at_head = tree._git("cat-file", "-e", f"{tree.commit}:{target}").returncode == 0
|
|
69
|
+
(tree if exists_at_head else _head_tree(root, base)).line_count(target)
|
|
70
|
+
policy = stored_policy.value
|
|
71
|
+
guidance = code_review_guidance_paths(policy)
|
|
72
|
+
if len(guidance) != 3:
|
|
73
|
+
raise ValueError("frozen code-review protocol guidance is incomplete")
|
|
74
|
+
selected = select_review_policy(
|
|
75
|
+
policy, targets, project_paths=paths, manifest_contents=manifests,
|
|
76
|
+
guidance_paths=guidance,
|
|
77
|
+
resources=inputs.resources,
|
|
78
|
+
)
|
|
79
|
+
canonical = parse_review_census(
|
|
80
|
+
render_review_rule_catalog(selected) + "\n## Cells\n", allow_empty=True,
|
|
81
|
+
)
|
|
82
|
+
for group, rules in census.rules.items():
|
|
83
|
+
for rule in rules:
|
|
84
|
+
references = [part.strip() for part in census.references[rule].split(";")]
|
|
85
|
+
if (rule not in canonical.rules.get(group, ())
|
|
86
|
+
or canonical.references[rule] not in references):
|
|
87
|
+
raise ValueError(f"assigned census weakens the frozen rule catalog: {rule}")
|
|
88
|
+
return {"schemaVersion": 1, "base": base, "head": tree.commit,
|
|
89
|
+
"census": census_text, "policy": selected}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def bind_review_invocation(request: AgentInvocationRequest) -> AgentInvocationRequest:
|
|
93
|
+
from .agent.invocation import (
|
|
94
|
+
AgentInstructionSource, AgentInvocationError, _canonical_json, _publish_or_reuse_exact,
|
|
95
|
+
)
|
|
96
|
+
if request.run_manifest_path is not None or request.audience != "code-reviewer":
|
|
97
|
+
if request.review_inputs is not None:
|
|
98
|
+
raise AgentInvocationError("frozen code-review inputs require a standalone code reviewer")
|
|
99
|
+
return request
|
|
100
|
+
if request.purpose != "code-review":
|
|
101
|
+
raise AgentInvocationError("code reviewer requires purpose code-review")
|
|
102
|
+
from .code_review_integrity import capture_review_source
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
payload = _review_payload(request)
|
|
106
|
+
root = request.project_root.resolve()
|
|
107
|
+
policy_path = request.prompt_path.parent / f"{request.invocation_id}.review-policy.json"
|
|
108
|
+
metadata = {"invocationId": request.invocation_id, "audience": request.audience,
|
|
109
|
+
"contractSource": {"dutyRootPath": request.duty_root.resolve().relative_to(root).as_posix()},
|
|
110
|
+
"instruction": {"sourcePaths": [{"kind": row.kind, "path": row.path}
|
|
111
|
+
for row in request.instruction.source_paths]}}
|
|
112
|
+
baseline_path, baseline_digest = capture_review_source(
|
|
113
|
+
root, request.prompt_path, request.metadata_path, metadata,
|
|
114
|
+
)
|
|
115
|
+
payload.update(sourceSnapshotPath=baseline_path, sourceSnapshotDigest=baseline_digest)
|
|
116
|
+
raw = _canonical_json(payload)
|
|
117
|
+
_publish_or_reuse_exact(policy_path, raw)
|
|
118
|
+
relative = policy_path.resolve().relative_to(root).as_posix()
|
|
119
|
+
supplement = (
|
|
120
|
+
"\n\n## Frozen code-review inputs\n\n"
|
|
121
|
+
f"Frozen code-review policy: {relative}\n"
|
|
122
|
+
f"Frozen code-review policy digest: {content_digest(raw)}\n"
|
|
123
|
+
f"Frozen source base: {payload['base']}\nFrozen source head: {payload['head']}\n"
|
|
124
|
+
"Apply the captured rule bodies below. Source paths identify provenance; "
|
|
125
|
+
"do not replace these bodies with live installed files.\n"
|
|
126
|
+
+ render_selected_review_policy(payload["policy"])
|
|
127
|
+
+ "\n## Assigned review census\n\n" + payload["census"]
|
|
128
|
+
)
|
|
129
|
+
instruction = replace(
|
|
130
|
+
request.instruction, body=request.instruction.body.rstrip() + supplement,
|
|
131
|
+
source_paths=(*request.instruction.source_paths,
|
|
132
|
+
AgentInstructionSource("project", relative),
|
|
133
|
+
AgentInstructionSource("project", baseline_path)),
|
|
134
|
+
)
|
|
135
|
+
return replace(request, instruction=instruction)
|
|
136
|
+
except (OSError, ValueError, KeyError) as exc:
|
|
137
|
+
raise AgentInvocationError(f"cannot bind frozen code-review inputs: {exc}") from exc
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def review_policy_path(project: Path, metadata: Mapping) -> Path | None:
|
|
141
|
+
identity = metadata["invocationId"]
|
|
142
|
+
relative = f".okstra/agent-invocations/code-review/{identity}.review-policy.json"
|
|
143
|
+
sources = metadata["instruction"]["sourcePaths"]
|
|
144
|
+
if not any(row["kind"] == "project" and row["path"] == relative for row in sources):
|
|
145
|
+
return None
|
|
146
|
+
if metadata["audience"] != "code-reviewer" or metadata["contractSource"]["mode"] != "standalone":
|
|
147
|
+
raise ValueError("frozen code-review policy is bound to the wrong invocation")
|
|
148
|
+
return project / relative
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def read_invocation_review_policy(project: Path, metadata: Mapping) -> dict | None:
|
|
152
|
+
path = review_policy_path(project, metadata)
|
|
153
|
+
if path is None:
|
|
154
|
+
return None
|
|
155
|
+
payload = load_owned_object(path, artifact="invocation frozen review policy")
|
|
156
|
+
fields = {"schemaVersion", "base", "head", "census", "policy",
|
|
157
|
+
"sourceSnapshotPath", "sourceSnapshotDigest"}
|
|
158
|
+
if (set(payload) != fields or payload["schemaVersion"] != 1
|
|
159
|
+
or review_policy_errors(payload["policy"])):
|
|
160
|
+
raise ValueError("invocation frozen review policy is invalid")
|
|
161
|
+
expected = path.with_name(f"{metadata['invocationId']}.review-source.json").relative_to(project).as_posix()
|
|
162
|
+
if payload["sourceSnapshotPath"] != expected:
|
|
163
|
+
raise ValueError("review source snapshot path is not canonical")
|
|
164
|
+
raw = (project / expected).read_bytes()
|
|
165
|
+
if content_digest(raw) != payload["sourceSnapshotDigest"]:
|
|
166
|
+
raise ValueError("review source snapshot digest changed")
|
|
167
|
+
return payload
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def review_policy_errors_for_prompt(project: Path, metadata: Mapping, prompt: bytes) -> list[str]:
|
|
171
|
+
try:
|
|
172
|
+
path = review_policy_path(project, metadata)
|
|
173
|
+
if path is None:
|
|
174
|
+
return []
|
|
175
|
+
read_invocation_review_policy(project, metadata)
|
|
176
|
+
line = f"Frozen code-review policy digest: {content_digest(path.read_bytes())}"
|
|
177
|
+
if prompt.decode("utf-8").splitlines().count(line) != 1:
|
|
178
|
+
return ["frozen code-review policy differs from the prompt"]
|
|
179
|
+
except (OSError, ValueError, KeyError) as exc:
|
|
180
|
+
return [f"frozen code-review inputs are invalid: {exc}"]
|
|
181
|
+
return []
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def complete_review_audit(project: Path, metadata_path: Path, metadata: Mapping) -> str | None:
|
|
185
|
+
from .code_review_integrity import finalize_review_integrity
|
|
186
|
+
|
|
187
|
+
payload = read_invocation_review_policy(project, metadata)
|
|
188
|
+
if payload is None:
|
|
189
|
+
return None
|
|
190
|
+
return finalize_review_integrity(
|
|
191
|
+
project, metadata_path, metadata,
|
|
192
|
+
payload["sourceSnapshotPath"], payload["sourceSnapshotDigest"],
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def verify_review_completion(
|
|
197
|
+
project: Path, metadata_path: Path, metadata: Mapping, completion: Mapping,
|
|
198
|
+
) -> None:
|
|
199
|
+
from .code_review_integrity import verify_review_integrity
|
|
200
|
+
|
|
201
|
+
payload = read_invocation_review_policy(project, metadata)
|
|
202
|
+
if payload is None:
|
|
203
|
+
if completion["schemaVersion"] != 1:
|
|
204
|
+
raise ValueError("unexpected review integrity completion")
|
|
205
|
+
return
|
|
206
|
+
if completion["schemaVersion"] != 2:
|
|
207
|
+
raise ValueError("frozen code review requires integrity-bound completion")
|
|
208
|
+
verify_review_integrity(
|
|
209
|
+
project, metadata_path, metadata,
|
|
210
|
+
payload["sourceSnapshotPath"], payload["sourceSnapshotDigest"],
|
|
211
|
+
completion["reviewAuditDigest"],
|
|
212
|
+
)
|
|
@@ -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")
|