okstra 0.228.1 → 0.229.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.
@@ -89,9 +89,95 @@ remains readable and is not retrofitted. Snapshot publication and reference chec
89
89
  are covered by `tests/run/test_project_qa_command_gate.py` and
90
90
  `tests/application/test_host_orchestration_render.py`.
91
91
 
92
+ QA declarations retain the optional `language` selector for the verifier's existing
93
+ diff-language skip policy. An absent selector remains absent and means always run.
94
+ Present selectors must be non-empty identifiers using letters, digits, `.`, `_`,
95
+ `+`, `#` or `-`, beginning with a letter or digit. The shared QA metadata validator
96
+ checks their shape during declaration loading and snapshot reading.
97
+ Changing a selector cannot replace a published snapshot. Frozen selectors remain
98
+ visible after current project settings change. The declaration immutability,
99
+ allowed-field and projection tests in `test_project_qa_command_gate.py` cover this.
100
+
92
101
  These declarations do not prove that a command ran. Preparation does not require
93
102
  future inspection scripts to exist, and execution receipts are a separate contract.
94
103
 
104
+ New snapshots also include optional `qaSourceObservations`, grouped by QA category
105
+ and array position. Each row records the frozen declaration's `entryDigest`, its
106
+ `sourceStatus`, and an `observedSourceDigest` when related sources were readable.
107
+ Entry digests cover exactly the frozen declaration fields. Categories, row counts,
108
+ declaration digests and status consistency are checked by
109
+ `_verification_source_errors` before a stored observation is returned.
110
+
111
+ Source observations use the selected source worktree. The shared `qa_source_status`
112
+ policy distinguishes `not-declared`, `no-baseline`, `unchanged` and `changed`.
113
+ An incomplete observation keeps `not-queried` with its error and no observed
114
+ digest. Missing files and symlinked paths cannot produce a successful observation.
115
+ `source_digest` rejects more than 1,024 related paths before sorting or reading
116
+ files. Preparation and inspection retain that failure as an unavailable
117
+ observation; registration rejects the oversized source list. The boundary and
118
+ zero-read rejection are covered by `test_qa_observation_bounds_shared_source_reads`.
119
+ Repeated source-digest reads reuse the first digest for each path within one
120
+ preparation or inspection. Later operations use fresh readers for changed bytes.
121
+ Resuming a run keeps its frozen observations. Older snapshots without this field
122
+ remain readable, and the fixed-text view identifies their observations as not
123
+ captured. Source status neither skips a check nor proves a test passed.
124
+ `test_project_qa_command_gate.py` covers selected worktrees, errors, tampering,
125
+ legacy inputs, repeated reads and per-operation cache lifetime.
126
+
127
+ `capture_verification_source` provides the source-classification boundary for
128
+ verification-generation seals. Its in-memory `VerificationSourceSnapshot` retains
129
+ the source root, tracked path set, generated roots, explicit input paths, and
130
+ read-only protected/generated fingerprint maps. Tracked files and explicit inputs
131
+ take precedence over generated roots. Unclassified existing files, including
132
+ Git-ignored files, remain protected. The existing collector excludes installed
133
+ dependency trees, the runtime artifact tree, and other registered worktrees;
134
+ explicit inputs and tracked files are recovered from excluded artifact and
135
+ dependency trees. Explicit inputs use the shared QA regular-file validator and reject
136
+ symlinked paths. Recovered tracked symlinks retain their link fingerprints;
137
+ symlinked ancestors are rejected without reading outside the source root.
138
+
139
+ `compare_verification_sources` requires the same root and classification on both
140
+ sides. It separates protected changes, generated changes, new unclassified paths,
141
+ and changes to the tracked path set. A generated file becoming tracked changes
142
+ the protected input set even when its bytes stay the same. The classification,
143
+ real-read counts, read-only maps, and comparison guards are covered by
144
+ `tests/run/test_batch_mutation_audit_paths.py`. These observations are the source
145
+ boundary for later generation publication and execution receipts. Existing batch
146
+ audit and free verification-target behavior retain their existing contracts.
147
+
148
+ `prepare_verification_generation` publishes source and inspection-file seals under
149
+ `RunRef.verification_generation`, separated by run, stage and generation ordinal.
150
+ It binds the frozen input reference to the observed Git head, source classification
151
+ and actual inspection-file digests. Shared-root inspection inputs remain protected
152
+ and reuse source reads. Publication is serialized and atomic; protected changes
153
+ reject generation reuse, while allowed output changes preserve the original bytes.
154
+ The reader bounds path expansion and checks schema, classification and byte digests
155
+ without rereading live inputs. `tests/run/test_verification_generation.py` covers
156
+ correction generations, tampering, lock waits and target changes.
157
+
158
+ With a frozen approved plan, a generation also records `conformanceStages` and
159
+ includes the actual manifest and selected scripts in its inspection-file seal.
160
+ Implementation selects the current stage and earlier stages whose declared or
161
+ actual script appears in the caller's project-relative `changed_artifact_paths`.
162
+ The caller also supplies `conformance_baseline`, the pre-implementation actual
163
+ stage-to-script mapping. It retains scope when a prior exempt stage's added check
164
+ is deleted or renamed. A changed baseline script cannot disappear with its entry
165
+ and turn back into an exemption.
166
+ Final verification selects all declared stages, including a stage-isolated run.
167
+ Manifest entries must match the frozen plan's scripts and cover its capabilities.
168
+ A planning exemption permits an actual check; it does not suppress that check.
169
+ Missing future scripts do not block implementation. Selected missing scripts,
170
+ duplicate or undeclared stage identities, unsafe paths, and manifest changes
171
+ during capture prevent publication. The existing conformance module owns command,
172
+ entry and declaration comparison rules shared with the legacy report validator.
173
+ Generation collection checks task-root confinement before that comparison.
174
+ These cases are covered by
175
+ `tests/run/test_verification_generation.py` for separate and shared source roots.
176
+ Records without an approved plan retain their existing shape. This storage API
177
+ does not yet collect worker mutation paths or dispatch verification. Dispatch
178
+ ownership, mutation-observation binding and execution receipts remain integration
179
+ work; a generation seal is not evidence that its commands ran.
180
+
95
181
  `okstra model-io run-input --run-manifest <path>` projects the recorded
96
182
  `verificationInputsPath` and `verificationInputsDigest` as fixed scalar lines.
97
183
  Absent or non-scalar values display `-`, including older manifests without a
package/docs/cli.md CHANGED
@@ -951,7 +951,7 @@ The `okstra` Node CLI (`bin/okstra`) provides both installer/admin commands and
951
951
  | `okstra incremental-scope <args…>` | Decide re-verify vs carry-forward scope for an `implementation-planning` clarification re-run. Thin shim into `scripts/okstra_ctl/incremental_scope.py` (deterministic): it reads the dependency graph from the prior run `data.json`'s `implementationPlanning.stageMap` and returns `mode:"incremental"` only when the base-ref SHA is unchanged and the affected stages' `downstream_stage_closure` covers at most half of all stages; `--full-reason` (selected option / Stage Map / approach) still forces `mode:"full"`. An answered `C-NNN` that traces to no stage returns `mode:"unresolved"` rather than full — pass `--impacted` with the stage numbers or `--full-reason`. `--run-manifest <path>` is required for a decision (not for `--preview`): the same decision is written to the record that manifest names in `incrementalDecisionPath`, so the report writer's authoring contract and `okstra incremental-carry` read it instead of CSVs the lead re-typed. `mode: "unresolved"` is a question back to the lead and is deliberately not recorded. `--preview --prev-data <path> --answered-clarifications <csv>` runs the link half alone — no base SHA, no side effects — and prints `{wouldForceFull, unlinkedIds, reason}`; unlinked ids set `wouldForceFull: false` and fill `unlinkedIds` |
952
952
  | `okstra incremental-carry <args…>` | Merge carried-forward plan-item verdicts into an incremental re-run. Contract v3 takes `--prev-data`, `--cur-narrative`, and the convergence-owned `--state`; it verifies carried stage rows and writes only `--out-state`, tagging copied verdicts with `carriedForwardFromSeq`. Pass `--decision <incrementalDecisionPath>` for the two stage sets — the same record the report writer's authoring contract was built from — instead of `--carry-stages` / `--reverify-stages`, which the lead re-typed off stdout; the two forms cannot be combined, and a record whose `mode` is not `incremental` is refused. Unchanged `P-Val-*` / `P-Req-*` / `P-Rb-*` rows whose extract hash still matches are carried the same way, and the sibling `plan-items-*.json` `dispatchQueue` is rewritten to match. The historical v2 `--cur-data --out` form remains readable. Ownership, scope, item, or schema drift raises `CarryError` and forces a full fallback. |
953
953
  | `okstra code-review target --task-key <k> --stage <N> [--project-root <dir>] [--cwd <dir>] [--json]` / `okstra code-review target --branch <name> --base <ref> [--date <YYYY-MM-DD>] [--project-root <dir>] [--cwd <dir>] [--json]` | Resolve what a code review reads and where its result file goes. Output is always JSON, so `--json` only makes that explicit. `--project-root` and `--cwd` are shared pre-dispatch arguments and apply to both modes; `--cwd` is only consulted when `--project-root` is absent. Both modes return `{ ok, projectRoot, mode, worktreePath, branch, baseCommit, headCommit, reviewPath, round }`; stage mode additionally returns `taskKey`, `taskRoot`, and `stage`. Stage mode takes the diff base from the `base_ref` recorded on that stage's worktree-registry row when it was provisioned — not from a rule re-applied at review time — and names the result `.okstra/tasks/<task-group>/<task-id>/code-reviews/stage-<NN>.md`, where a re-review of the same stage becomes `-r2`, `-r3`, … (the `round` field). Only a legacy row provisioned before `base_ref` was recorded falls back to re-deriving the base through `stage_targets`, and a failure there is reported as `stage_base_unresolved`. `worktreePath` comes back empty whenever the stage worktree is not usable as a live checkout — the registry row is no longer `active` (whole-task final-verification released it), the row never carried a path, or the recorded directory is gone — and the review then reads the `branch` ref instead. Branch mode requires an explicit `--base` branch or commit, rejects invalid refs, freezes it as a commit, leaves `worktreePath` empty for fixed-head reads, and names the result `.project-docs/code-reviews/<branch>/<YYYY-MM-DD>-<NN>.md`, where `<NN>` (the `round` field) is the next sequence number for that date — the highest already on disk plus one. Read-only: it resolves paths and creates no directory and no file, so the review directory does not exist until the caller writes the report. Backend for the okstra-code-review skill |
954
- | `okstra code-review check-coverage --project-root <dir> --head <headCommit> --census <table-path> --completion <completion-path> [--completion <gap-fill-path> ...]` | Audits compact grouped-cell verdicts from one reviewer's verified standalone completions. Rejects changed model assignments, invalid evidence or a declared Review head baseline different from the requested head (exit 2); lists missing/unknown IDs (exit 1); complete usable coverage exits 0. The census has `## Rules` (Rule, Group, Reference) and `## Cells` (Cell, Target, Group) tables. Each result row explicitly accounts for the group's rules through Checked, N/A and Findings, with one target-source path:line that exists at `--head`; evidence files are read from that commit, not the working tree. Checked general G2/G3/G5 criteria also require source-cited observations after ` :: ` in Evidence. Missing rules or observations are reported without expanding a target-by-bullet table; the lead audits selected references and semantic truth. |
954
+ | `okstra code-review check-coverage --project-root <dir> --base <baseCommit> --head <headCommit> --census <table-path> --completion <completion-path> [--completion <gap-fill-path> ...]` | Audits compact grouped-cell verdicts from one reviewer's verified standalone completions. Rejects changed model assignments, invalid evidence or a declared Review head baseline different from the requested head (exit 2); lists missing/unknown IDs (exit 1); complete usable coverage exits 0. The census has `## Rules` (Rule, Group, Reference) and `## Cells` (Cell, Target, Group) tables. Each result row explicitly accounts for the group's rules through Checked, N/A and Findings, with one target-source path:line that exists at `--head`; evidence files are read from that commit, not the working tree. Explicit `base:path:line` evidence reads the supplied `--base`; line 0 is a file-level anchor accepted only for an empty regular file. `check-lines` also accepts removed base lines and changed empty-file anchors. Checked general G2/G3/G5 criteria also require source-cited observations after ` :: ` in Evidence. Missing rules or observations are reported without expanding a target-by-bullet table; the lead audits selected references and semantic truth. |
955
955
  | `okstra code-review scope --project-root <dir> --base <baseCommit> --head <headCommit> --census <path> --policy <path> [--policy <path> ...] [--previous-head <priorHead> --previous-census <path> --completion <path> ...]` | Read-only scope proposal per reviewer. Fingerprints catalog resources and all supplied policy/calibration/instruction sources; prints the baseline, Recheck IDs and Carry candidates. Verified prior completion baselines and dependency inventories permit candidates only for unchanged clean/N/A cells with identical identities. Prior findings, changed dependencies and missing inventories reopen cells; changed rules/base, rewritten history or unmapped changed files require full inspection. Invalid input/evidence exits 2. Pass the skill, calibration, duty and applied project instructions as policies. Current reviewers independently validate the impact closure and publish full current verdicts through the existing completion boundary; candidate status never proves a clean verdict or dependency completeness. |
956
956
  | `okstra set-work-status <token> <todo\|in-progress\|blocked\|done> [--note <text> \| --note-file <path>] [--task-group <g>] [--project-root <dir>]` | Update user-managed `workStatus`. Existing briefs can be registered without a run. Direct completion requires a work and verification summary; use a UTF-8 note file for longer results. Records are shared through group context, inspect, and subsequent runs without claiming cross-verification. Ambiguous IDs return `matches[]`. A `share` failure with `statusRecorded:true` can be retried with the same command. |
957
957
  | `okstra worktree-lookup <project-id> <task-group> <task-id>` | Return the `worktree_registry.lookup` result: reserved path, branch, base ref, and current status |
@@ -284,8 +284,10 @@ Important modules:
284
284
  | `clarification_items/` | Unified §5 clarification table parser and approval blockers. `parsing` walks the §1 table, `dispositions` decides what an answer means (it opens nothing), `rows` reads either schema, `sidecars` handles user responses, and `scan` / `carry` build on those for the fail-closed gate read and the next run's carry-in |
285
285
  | `md_table.py` | Markdown pipe-table escape/split SSOT — the `mdcell` filter (`escape_pipes`) and the `\|`-aware `split_pipe_row`; shared by the renderer, HTML view, and validators |
286
286
  | `qa_commands.py` | QA command deny-list validation for plans |
287
- | `qa_procedures.py` | Project-relative procedure loading, content and related-source digests, fixed inspection rows, and serialized atomic QA registration |
288
- | `verification_inputs.py` | Immutable per-run QA declaration and procedure snapshots, strict schema and digest checks, and serialized publication inside the project artifact tree |
287
+ | `qa_procedures.py` | Project-relative procedure loading, content and related-source digests, shared source-status observations with per-operation digest readers, fixed inspection rows, and serialized atomic QA registration |
288
+ | `verification_inputs.py` | Immutable per-run QA declaration, procedure and source-observation snapshots, strict schema and digest checks, and serialized publication inside the project artifact tree |
289
+ | `verification_generation.py` | Immutable generation seals for observed source, Git head and inspection files, with frozen-input binding and strict readers |
290
+ | `verification_conformance.py` | Frozen-plan conformance scope selection and actual manifest/script validation for generation seals |
289
291
  | `verification_input_ref.py` | Optional verification input path and digest references shared by manifest rendering and compact context hydration |
290
292
  | `verification_input_types.py` | Pure snapshot payload types and version constants shared by storage and its port |
291
293
  | `verification_plan.py` | Approved-plan verification expectation capture and validation using the canonical report-row schema and conformance declaration parser |
@@ -415,7 +417,7 @@ Important modules:
415
417
  | `assignment_environment.py` | loads ambient host-adapter facts once, outside the deterministic assignment logic; read by `run.py`, `dispatch_core.py`, the wizard's role step, and `agent-prompt materialize` |
416
418
  | `execution_identity.py` | provider-neutral execution identity value objects — participant assignment, role execution, invocation, attempt, execution manifest — and their versioned readers |
417
419
  | `attempt_evidence.py` | atomic attempt-evidence seals and the orchestrator-owned host event streams written around each worker attempt |
418
- | `execution_mutation_audit.py` | batch-scoped source and Git mutation audit for worker invocations (snapshots taken around a dispatch batch) |
420
+ | `execution_mutation_audit.py` | Batch-scoped source and Git mutation audit, plus read-only verification source snapshots that separate protected inputs, declared generated outputs, and unclassified new files |
419
421
  | `mutation_recovery.py` | recovery decisions after a sealed or unsealed implementer attempt that mutated source |
420
422
  | `write_policy.py` | canonical invocation write policy — which paths an invocation may write — and the enforcement the runner truthfully reports; read by the provider wrapper, `worker_request.py`, `dispatch_core.py`, and report assembly |
421
423
  | `role_requirements.py` | parses the canonical role requirements that phase profiles declare |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "okstra",
3
- "version": "0.228.1",
3
+ "version": "0.229.0",
4
4
  "description": "Host-aware multi-provider cross-verification orchestrator runtime and agent skills.",
5
5
  "license": "MIT",
6
6
  "author": "devonshin",
@@ -1,5 +1,5 @@
1
1
  {
2
- "package": "0.228.1",
3
- "builtAt": "2026-11-01T12:00:58.508Z",
2
+ "package": "0.229.0",
3
+ "builtAt": "2026-11-02T05:32:06.274Z",
4
4
  "repoRoot": "/home/runner/work/okstra/okstra"
5
5
  }
@@ -37,7 +37,7 @@ from okstra_ctl.registry.provider_registry import ( # noqa: E402
37
37
  )
38
38
  from okstra_ctl.worker_request import build_request, idle_timeout # noqa: E402
39
39
  from okstra_ctl.worker_runner import LIVE, QUIET, run_worker # noqa: E402
40
- from okstra_ctl.dispatch_core import verify_served_model # noqa: E402
40
+ from okstra_ctl.dispatch_core import verify_served_model, verify_served_model_ref # noqa: E402
41
41
  from okstra_ctl.dispatch_state import DispatchError # noqa: E402
42
42
  from okstra_ctl.execution_manifest import read_execution_manifest_view # noqa: E402
43
43
  from okstra_ctl.write_policy import ( # noqa: E402
@@ -49,8 +49,10 @@ from okstra_ctl.write_policy import ( # noqa: E402
49
49
  from okstra_ctl.model_pool import ModelPool # noqa: E402
50
50
  from okstra_ctl.agent.invocation import ( # noqa: E402
51
51
  AgentInvocationError,
52
+ AgentModelAssignment,
52
53
  agent_model_assignment_from_payload,
53
54
  invocation_metadata_identity,
55
+ verify_agent_invocation,
54
56
  )
55
57
 
56
58
  _USAGE = (
@@ -88,8 +90,8 @@ class Invocation:
88
90
  class _V2InvocationContext:
89
91
  status_extra: Mapping[str, Any]
90
92
  verify_attestation: Callable[[ServedModelAttestation], str]
91
- write_policy: WritePolicy
92
- write_enforcement: WriteEnforcement
93
+ write_policy: WritePolicy | None
94
+ write_enforcement: WriteEnforcement | None
93
95
  reasoning_effort: str
94
96
 
95
97
 
@@ -237,7 +239,10 @@ def _v2_status_extra(
237
239
  except AgentInvocationError as exc:
238
240
  raise PreflightError(64, str(exc)) from exc
239
241
  if identity is None:
240
- raise PreflightError(64, "new worker dispatch requires v2 invocation metadata")
242
+ return _standalone_context(
243
+ metadata_path, metadata, assignment, project_root, prompt_path,
244
+ provider_id, model, role,
245
+ )
241
246
  if (
242
247
  assignment.provider != provider_id
243
248
  or assignment.model_execution_value != model
@@ -323,6 +328,50 @@ def _v2_status_extra(
323
328
  )
324
329
 
325
330
 
331
+ def _standalone_context(
332
+ metadata_path: Path, metadata: Mapping[str, Any], assignment: AgentModelAssignment,
333
+ project_root: Path, prompt_path: Path, provider_id: str, model: str, role: str,
334
+ ) -> _V2InvocationContext:
335
+ if metadata.get("dispatchKind") != "standalone":
336
+ raise PreflightError(64, "new worker dispatch requires v2 invocation metadata")
337
+ errors = verify_agent_invocation(
338
+ metadata_path, project_root=project_root, expected_run_manifest_path=None,
339
+ )
340
+ if errors:
341
+ raise PreflightError(64, "; ".join(errors))
342
+ if assignment.provider != provider_id or assignment.model_execution_value != model:
343
+ raise PreflightError(64, "invocation metadata model assignment does not match wrapper")
344
+ try:
345
+ expected_role = role_for_duty(str(metadata["audience"]))
346
+ actual_role = normalize_role(role)
347
+ except ValueError as exc:
348
+ raise PreflightError(64, f"invocation metadata role is invalid: {exc}") from exc
349
+ if expected_role != actual_role:
350
+ raise PreflightError(64, "invocation metadata duty does not match role")
351
+ recorded = project_root / metadata["prompt"]["path"]
352
+ if recorded.resolve() != prompt_path.resolve():
353
+ raise PreflightError(64, "invocation metadata prompt does not match wrapper")
354
+ pool = ModelPool.from_registry(default_provider_registry())
355
+ try:
356
+ selected = pool.resolve_alias(assignment.provider, assignment.model_execution_value)
357
+ except ValueError as exc:
358
+ raise PreflightError(64, str(exc)) from exc
359
+
360
+ def verify_attestation(attestation: ServedModelAttestation) -> str:
361
+ try:
362
+ verify_served_model_ref(
363
+ str(selected.model_ref), attestation, pool=pool,
364
+ )
365
+ except DispatchError as exc:
366
+ return str(exc)
367
+ return ""
368
+
369
+ return _V2InvocationContext(
370
+ {"standaloneInvocationId": metadata["invocationId"], "role": actual_role},
371
+ verify_attestation, None, None, "",
372
+ )
373
+
374
+
326
375
  def _execution_authority(
327
376
  *,
328
377
  metadata: Mapping[str, Any],
@@ -6,8 +6,9 @@
6
6
  "Return an evidence-backed verdict for every assigned review census cell, acting as a correctness, maintainability and documented-convention gate, and without changing the census or the code under review."
7
7
  ],
8
8
  "requiredConduct": [
9
- "On follow-up reviews, inspect the correction delta and its impact closure. Treat carry candidates as proposals: independently search affected callers, callees, contracts and tests before attesting inheritance from this slot's verified prior verdicts. Reopen candidates for newly discovered effects or evidence of a real defect; fall back to full inspection when the boundary is uncertain. Account for the full current census and distinguish inspected from inherited cells.",
10
- "Inspect every cell's actual diff and surrounding behavior, apply the assigned standard, trace affected call paths and tests where relevant, look for regressions and missing validation, preserve the cell identifier, and return either concrete findings or an evidence-backed clean verdict.",
9
+ "On follow-up reviews, inspect the correction delta and its impact closure. Treat carry candidates as proposals: independently search affected callers, callees, contracts and tests before attesting inheritance from this slot's verified prior verdicts. Reopen candidates for newly discovered effects or evidence of a real defect; fall back to full inspection when the boundary is uncertain. Account for this slot's full assigned census and distinguish inspected from inherited cells.",
10
+ "Inspect every assigned cell's actual diff and full context: whole target files, enclosing definitions, affected callers and callees, contracts, outcome consumers and related tests at the frozen head. Follow transitive effects as needed. An assigned specialty limits verdict ownership, not context reads. Route suspected issues outside the assignment to the lead without changing the census. Preserve the cell identifier and return concrete findings or an evidence-backed clean verdict.",
11
+ "Use the lead's shared test execution evidence, checking its head and inputs. Review test assertions, failure and boundary cases and self-mocking where assigned. Distinguish inspected tests from executed tests, report missing or failed verification, and ask the lead for any additional necessary execution rather than launching duplicate suites or editing code.",
11
12
  "Return one compact Coverage Verdicts table row per assigned target/group cell. Explicitly account for every shared-catalog rule ID under Checked, N/A with an inline applicability reason, or Findings with finding IDs. Share one literal inspected target-source path:line per row. Do not expand pack bullets into separate verdict rows, use all-checked claims, or mark unread rules checked.",
12
13
  "Inspect before accounting: evaluate changed constructs against every applicable canonical clause, follow result mappings and the work done by existing callees, and identify findings before compressing the coverage table. Passing tests and linters do not establish conformance to every assigned rule."
13
14
  ],
@@ -24,6 +25,8 @@
24
25
  "For checked G2, G3 and G5 rules in general cells, the Evidence field includes source-cited clean observations after ::, keyed by rule ID. G2 traces dependency outcome meanings through diagnostic values; G3 identifies workload dimensions, downstream work and limits before that work; G5 names the applicable canonical clauses and observed conformance. Missing or unsupported inspection stays unaccounted instead of clean."
25
26
  ],
26
27
  "collaborationContract": [
28
+ "The spawning coordinator divides the received full census and delivers each subset to its responsible child. Each child investigates that assignment and returns explicit coverage and findings. The coordinator compares all responses with both the child assignments and the full census, sends omissions back to the same logical child with its prior results, and repeats until nothing remains unaccounted for. Only then return the consolidated model report; blocked or incomplete coverage is never a completed review.",
29
+ "Honor the assigned coordinator or specialty role without recursive delegation. A model-team coordinator owns the full census, itself spawns the six same-provider/model specialty subagents, collects and verifies their completions, requests their gap-fills, and consolidates their rule statuses and findings with child provenance before returning its model report. Do not transfer child spawning or consolidation to the orchestrator. Correct any aggregation discrepancy in the spawning coordinator's report. A specialty subagent inspects only its assigned rule subset and does not spawn further reviewers. Preserve independence between model teams; never borrow another team's verdict to fill a gap.",
27
30
  "Keep verdicts independent from other reviewers and the author. Do not echo a finding without verifying it, suppress a unique defect for consistency, or resolve cross-cell overlap by changing identifiers; return overlap information to the lead."
28
31
  ],
29
32
  "completionCriteria": [
@@ -83,11 +83,12 @@ def _keyed_values(text: str) -> dict[str, str]:
83
83
  values: dict[str, str] = {}
84
84
  if text == "-":
85
85
  return values
86
- for entry in text.split(";"):
86
+ # Reviewers write prose reasons; only a semicolon before the next `RULE=` separates assignments.
87
+ for entry in re.split(r";(?=\s*[A-Z][A-Z0-9]*=)", text):
87
88
  key, separator, value = entry.partition("=")
88
89
  key, value = key.strip(), value.strip()
89
90
  if not separator or not key or not value or key in values:
90
- raise ValueError("empty or duplicate rule assignment")
91
+ raise ValueError(f"empty or duplicate rule assignment: {entry.strip()!r}")
91
92
  values[key] = value
92
93
  return values
93
94
 
@@ -102,6 +103,7 @@ class _HeadTree:
102
103
  root: Path
103
104
  commit: str
104
105
  line_counts: dict[str, int] = field(default_factory=dict)
106
+ base: _HeadTree | None = None
105
107
 
106
108
  def line_count(self, path: str) -> int:
107
109
  if path not in self.line_counts:
@@ -147,14 +149,21 @@ def _head_tree(project_root: Path, head: str) -> _HeadTree:
147
149
 
148
150
 
149
151
  def _source_evidence(tree: _HeadTree, cell: ReviewCell, evidence: str) -> str:
150
- match = re.fullmatch(r"(.+?):([1-9][0-9]*)`?(?: — .+)?", evidence.strip("`"))
152
+ source = evidence.strip("`")
153
+ if source.startswith("base:"):
154
+ if tree.base is None:
155
+ raise ValueError("base-side evidence requires --base")
156
+ tree = tree.base
157
+ source = source.removeprefix("base:")
158
+ match = re.fullmatch(r"(.+?):(0|[1-9][0-9]*)`?(?: — .+)?", source)
151
159
  target = cell.target.partition(":")[0]
152
160
  if match is None or match[1] != target:
153
161
  raise ValueError("evidence must cite the target source path:line")
154
162
  relative = PurePosixPath(target)
155
163
  if relative.is_absolute() or ".." in relative.parts:
156
164
  raise ValueError("source evidence escapes project")
157
- if int(match[2]) > tree.line_count(target):
165
+ count = tree.line_count(target)
166
+ if int(match[2]) > count or (int(match[2]) == 0 and count != 0):
158
167
  raise ValueError("source evidence line does not exist at head")
159
168
  return evidence
160
169
 
@@ -172,13 +181,13 @@ def _checked_rule_evidence(
172
181
  if observations.keys() - set(checked):
173
182
  raise ValueError("clean check evidence names an unchecked rule")
174
183
  for observation in observations.values():
175
- match = re.fullmatch(r"(`?.+?:[1-9][0-9]*`?) (.+)", observation)
184
+ match = re.fullmatch(r"(`?.+?:(?:0|[1-9][0-9]*)`?) (.+)", observation)
176
185
  if match is None:
177
186
  raise ValueError("clean check evidence needs source path:line and an observation")
178
187
  if re.fullmatch(r"(?:checked|clean|no issues?|none|n/?a)", match[2], re.I):
179
188
  raise ValueError("clean check evidence needs an observation, not a verdict label")
180
189
  citation = match[1].strip("`")
181
- source_cell = ReviewCell(citation.partition(":")[0], cell.group)
190
+ source_cell = ReviewCell(citation.removeprefix("base:").partition(":")[0], cell.group)
182
191
  _source_evidence(tree, source_cell, citation)
183
192
  return text
184
193
 
@@ -257,9 +266,12 @@ def _group_results(
257
266
 
258
267
  def check_review_coverage(
259
268
  project_root: Path, census_path: Path, completions: Sequence[Path], head: str,
269
+ *, base: str = "",
260
270
  ) -> CellVerdicts:
261
271
  census = read_review_census(census_path)
262
272
  tree = _head_tree(project_root, head)
273
+ if base:
274
+ tree.base = _head_tree(project_root, base)
263
275
  if not completions or len(set(completions)) != len(completions):
264
276
  raise ValueError("pass distinct completion paths for one reviewer")
265
277
  bodies: list[str] = []
@@ -109,7 +109,8 @@ def review_scope(
109
109
  old = read_review_census(previous_census)
110
110
  if old.rules != census.rules or old.references != census.references:
111
111
  return full("rule catalog changed")
112
- verdicts = check_review_coverage(root, previous_census, completions, prior.commit)
112
+ verdicts = check_review_coverage(root, previous_census, completions, prior.commit,
113
+ base=base_commit)
113
114
  if verdicts.missing or verdicts.unknown:
114
115
  return full("previous review coverage is incomplete")
115
116
  try:
@@ -92,7 +92,7 @@ def _branch_snapshot(repo: Path, branch: str, base: str, review_date: str) -> di
92
92
  _CLI_EPILOG = r"""Usage:
93
93
  okstra code-review target --task-key <k> --stage <N> [--base <ref>] [--project-root <dir>] [--cwd <dir>] --json
94
94
  okstra code-review target --branch <name> --base <ref> [--date <YYYY-MM-DD>] [--project-root <dir>] --json
95
- okstra code-review check-coverage --head <ref> --census <table-path> --completion <completion-path> [--completion ...] [--project-root <dir>]
95
+ okstra code-review check-coverage --head <ref> [--base <ref>] --census <table-path> --completion <completion-path> [--completion ...] [--project-root <dir>]
96
96
  okstra code-review scope --base <ref> --head <ref> --census <path> --policy <path> [--previous-head <ref> --previous-census <path> --completion <path> ...]
97
97
  okstra code-review check-lines --base <ref> --head <ref> --cite <path:line> [--cite ...] [--project-root <dir>]
98
98
 
@@ -104,8 +104,8 @@ mode selects the base from the stage registry row. Both modes resolve the
104
104
  selected base to a fixed commit; branch mode requires an explicit base. An empty
105
105
  worktreePath means the review reads the branch ref
106
106
  instead of a checked-out tree. This is read-only — it never creates
107
- directories or files. `check-coverage` reads each evidence file at `--head`, not
108
- the working tree, prints covered cells, missing rules and unknown cells, and exits
107
+ directories or files. `check-coverage` reads head evidence at `--head` and explicit
108
+ base evidence at `--base`, never the working tree, prints covered cells, missing rules and unknown cells, and exits
109
109
  1 for incomplete coverage and 2 for invalid input or completion evidence.
110
110
  """
111
111
 
@@ -132,7 +132,7 @@ def _build_parser() -> argparse.ArgumentParser:
132
132
  )
133
133
  parser.add_argument(
134
134
  "--cite", action="append", default=[],
135
- help="check-lines: a finding's `path:line` (repeatable)",
135
+ help="check-lines: path:line, base:path:line or empty path:0 (repeatable)",
136
136
  )
137
137
  parser.add_argument("--census", default="", help="check-coverage: shared Rules and grouped Cells tables")
138
138
  parser.add_argument("--completion", action="append", default=[],
@@ -185,16 +185,12 @@ def render_code_review_target_text(payload: dict) -> str:
185
185
 
186
186
 
187
187
  _HUNK_RE = re.compile(
188
- r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", re.MULTILINE,
188
+ r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.MULTILINE,
189
189
  )
190
190
 
191
191
 
192
192
  def changed_lines(repo: Path, base: str, head: str) -> dict[str, set[int]]:
193
- """Head-side line numbers each file's diff touched.
194
-
195
- A deletion within a surviving file anchors on the line before the cut.
196
- A deleted file has no head-side citation.
197
- """
193
+ """Changed head anchors and explicit base-side deletion anchors."""
198
194
  options = (
199
195
  "--no-ext-diff", "--no-color", "--submodule=short", "-M",
200
196
  )
@@ -218,28 +214,49 @@ def changed_lines(repo: Path, base: str, head: str) -> dict[str, set[int]]:
218
214
  if status.startswith((b"R", b"C")):
219
215
  paths.append(os.fsdecode(next(fields)))
220
216
  selection = [f"{base}:{paths[0]}", f"{head}:{paths[1]}", "--"]
221
- if status == b"D":
222
- continue
223
217
  patch = subprocess.run(
224
218
  ["git", "-C", str(repo), "diff", "-U0", *options, *selection],
225
219
  capture_output=True, check=False,
226
220
  )
227
221
  if patch.returncode != 0:
228
222
  raise StateError(os.fsdecode(patch.stderr).strip(), stage="diff")
229
- touched = lines.setdefault(paths[-1], set())
230
- for section in os.fsdecode(patch.stdout).split("\ndiff --git "):
231
- header_lines = section.partition("\n@@ ")[0].split("\n")
232
- if "+++ /dev/null" in header_lines:
233
- continue
234
- for match in _HUNK_RE.finditer(section):
235
- start = int(match[1])
236
- count = 1 if match[2] is None else int(match[2])
237
- touched.update(
238
- range(start, start + count) if count else {max(start, 1)}
239
- )
223
+ _collect_changed_lines(lines, paths, os.fsdecode(patch.stdout))
224
+ if status == b"D":
225
+ lines.pop(paths[0], None)
226
+ source_commit, source_path = (base, paths[0]) if status == b"D" else (head, paths[-1])
227
+ size = subprocess.run(
228
+ ["git", "--literal-pathspecs", "-C", str(repo), "ls-tree", "-l", "-z",
229
+ source_commit, "--", source_path],
230
+ capture_output=True, check=False,
231
+ )
232
+ if size.returncode != 0:
233
+ raise StateError(os.fsdecode(size.stderr).strip(), stage="diff")
234
+ if size.stdout.partition(b"\t")[0].split()[-1:] == [b"0"]:
235
+ lines[f"base:{paths[0]}" if status == b"D" else paths[-1]] = {0}
240
236
  return lines
241
237
 
242
238
 
239
+ def _collect_changed_lines(
240
+ lines: dict[str, set[int]], paths: list[str], patch: str,
241
+ ) -> None:
242
+ for section in patch.split("\ndiff --git "):
243
+ header = section.partition("\n@@ ")[0].split("\n")
244
+ deleted = "+++ /dev/null" in header
245
+ if not deleted:
246
+ touched = lines.setdefault(paths[-1], set())
247
+ for match in _HUNK_RE.finditer(section):
248
+ old_start, new_start = int(match[1]), int(match[3])
249
+ old_count = 1 if match[2] is None else int(match[2])
250
+ new_count = 1 if match[4] is None else int(match[4])
251
+ if old_count:
252
+ lines.setdefault(f"base:{paths[0]}", set()).update(
253
+ range(old_start, old_start + old_count)
254
+ )
255
+ if not deleted:
256
+ touched.update(range(new_start, new_start + new_count) if new_count
257
+ else {max(new_start, 1)})
258
+
259
+
243
260
  def render_check_lines(changed: dict[str, set[int]], cites: list[str]) -> tuple[str, bool]:
244
261
  rows = ["Okstra code review citation check\n"]
245
262
  all_ok = True
@@ -298,6 +315,7 @@ def _check_coverage(args: argparse.Namespace, project_root: Path) -> int:
298
315
  result = check_review_coverage(
299
316
  project_root, Path(args.census), [Path(path) for path in args.completion],
300
317
  args.head,
318
+ base=args.base,
301
319
  )
302
320
  except (OSError, ValueError, AgentInvocationError) as exc:
303
321
  print(f"check-coverage: {exc}", file=sys.stderr)
@@ -103,6 +103,37 @@ def strip_stage_declaration_label(stage: int, value: str) -> str:
103
103
  return stripped[match.end():]
104
104
 
105
105
 
106
+ def conformance_script_matches(actual: str, declared: str) -> bool:
107
+ if actual == declared:
108
+ return True
109
+ if not actual or not declared:
110
+ return False
111
+ if actual.startswith("/") != declared.startswith("/"):
112
+ longer, shorter = (
113
+ (actual, declared) if actual.startswith("/") else (declared, actual)
114
+ )
115
+ return longer.endswith("/" + shorter)
116
+ return False
117
+
118
+
119
+ def conformance_entry_mismatches(
120
+ *, actual_script: str, declared_script: str,
121
+ actual_requires: object, declared_requires: frozenset[str],
122
+ ) -> list[str]:
123
+ errors = []
124
+ if not conformance_script_matches(actual_script, declared_script):
125
+ errors.append("script mismatch")
126
+ actual_capabilities = (
127
+ frozenset(actual_requires)
128
+ if isinstance(actual_requires, list)
129
+ and all(isinstance(value, str) for value in actual_requires)
130
+ else None
131
+ )
132
+ if actual_capabilities is None or not actual_capabilities >= declared_requires:
133
+ errors.append("requires mismatch")
134
+ return errors
135
+
136
+
106
137
  def missing_declared_scripts(entries: object, task_root: Path) -> list[str]:
107
138
  """승인 계획이 가리키는 script 파일이 task_root 아래에 없으면 오류.
108
139