okstra 0.234.0 → 0.235.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.
Files changed (109) hide show
  1. package/dist/cli-registry.mjs +7 -0
  2. package/dist/cli-registry.mjs.map +1 -1
  3. package/dist/commands/implementation-report/implementation-report.d.mts +1 -0
  4. package/dist/commands/implementation-report/implementation-report.mjs +73 -0
  5. package/dist/commands/implementation-report/implementation-report.mjs.map +1 -0
  6. package/dist/commands/trace/comparison.d.mts +39 -0
  7. package/dist/commands/trace/comparison.mjs +138 -0
  8. package/dist/commands/trace/comparison.mjs.map +1 -0
  9. package/dist/commands/trace/document.d.mts +8 -0
  10. package/dist/commands/trace/document.mjs +37 -0
  11. package/dist/commands/trace/document.mjs.map +1 -0
  12. package/dist/commands/trace/line-counts.d.mts +15 -0
  13. package/dist/commands/trace/line-counts.mjs +107 -0
  14. package/dist/commands/trace/line-counts.mjs.map +1 -0
  15. package/dist/commands/trace/model.d.mts +2 -1
  16. package/dist/commands/trace/model.mjs +13 -1
  17. package/dist/commands/trace/model.mjs.map +1 -1
  18. package/dist/commands/trace/progression.mjs +12 -7
  19. package/dist/commands/trace/progression.mjs.map +1 -1
  20. package/dist/commands/trace/task-link.d.mts +3 -0
  21. package/dist/commands/trace/task-link.mjs.map +1 -1
  22. package/dist/commands/trace/trace.mjs +66 -46
  23. package/dist/commands/trace/trace.mjs.map +1 -1
  24. package/dist/lib/python-helper.d.mts +1 -1
  25. package/dist/lib/python-helper.mjs +11 -5
  26. package/dist/lib/python-helper.mjs.map +1 -1
  27. package/dist/lib/types.d.mts +1 -0
  28. package/docs/architecture/storage-model.md +50 -0
  29. package/docs/cli.md +31 -15
  30. package/docs/project-structure-overview.md +6 -1
  31. package/package.json +1 -1
  32. package/runtime/BUILD.json +2 -2
  33. package/runtime/agents/operations/trace-tests-review.json +6 -0
  34. package/runtime/prompts/duties/test-reviewer.json +32 -0
  35. package/runtime/prompts/lead/report-writer.md +13 -1
  36. package/runtime/python/okstra_ctl/agent/invocation.py +109 -56
  37. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +17 -0
  38. package/runtime/python/okstra_ctl/attempt_evidence.py +5 -2
  39. package/runtime/python/okstra_ctl/code_review_census.py +38 -0
  40. package/runtime/python/okstra_ctl/code_review_coverage.py +15 -4
  41. package/runtime/python/okstra_ctl/code_review_prepare.py +15 -3
  42. package/runtime/python/okstra_ctl/code_review_scope.py +3 -2
  43. package/runtime/python/okstra_ctl/code_review_target.py +16 -6
  44. package/runtime/python/okstra_ctl/conformance_evidence.py +44 -21
  45. package/runtime/python/okstra_ctl/consumers.py +6 -1
  46. package/runtime/python/okstra_ctl/design_review.py +6 -26
  47. package/runtime/python/okstra_ctl/design_review_evidence.py +6 -26
  48. package/runtime/python/okstra_ctl/dispatch_core.py +9 -2
  49. package/runtime/python/okstra_ctl/dispatch_state.py +5 -0
  50. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  51. package/runtime/python/okstra_ctl/execution_manifest.py +8 -0
  52. package/runtime/python/okstra_ctl/implementation_comparison/__init__.py +12 -0
  53. package/runtime/python/okstra_ctl/implementation_comparison/__main__.py +129 -0
  54. package/runtime/python/okstra_ctl/implementation_comparison/assembly.py +340 -0
  55. package/runtime/python/okstra_ctl/implementation_comparison/baseline.py +254 -0
  56. package/runtime/python/okstra_ctl/implementation_comparison/business_reuse.py +118 -0
  57. package/runtime/python/okstra_ctl/implementation_comparison/commit_source.py +113 -0
  58. package/runtime/python/okstra_ctl/implementation_comparison/html.py +49 -0
  59. package/runtime/python/okstra_ctl/implementation_comparison/inputs.py +348 -0
  60. package/runtime/python/okstra_ctl/implementation_comparison/model.py +47 -0
  61. package/runtime/python/okstra_ctl/implementation_comparison/preparation.py +195 -0
  62. package/runtime/python/okstra_ctl/implementation_comparison/publication.py +317 -0
  63. package/runtime/python/okstra_ctl/implementation_comparison/run_evidence.py +208 -0
  64. package/runtime/python/okstra_ctl/implementation_comparison/run_integration.py +198 -0
  65. package/runtime/python/okstra_ctl/implementation_comparison/source.py +342 -0
  66. package/runtime/python/okstra_ctl/implementation_comparison/target.py +144 -0
  67. package/runtime/python/okstra_ctl/implementation_comparison/task_assembly.py +333 -0
  68. package/runtime/python/okstra_ctl/implementation_comparison/task_selection.py +309 -0
  69. package/runtime/python/okstra_ctl/implementation_generation_evidence.py +134 -0
  70. package/runtime/python/okstra_ctl/implementation_outcome.py +2 -2
  71. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +1 -0
  72. package/runtime/python/okstra_ctl/json_boundary.py +28 -8
  73. package/runtime/python/okstra_ctl/paths.py +7 -4
  74. package/runtime/python/okstra_ctl/plan_run_root.py +8 -4
  75. package/runtime/python/okstra_ctl/qa_procedures.py +33 -2
  76. package/runtime/python/okstra_ctl/render.py +4 -0
  77. package/runtime/python/okstra_ctl/report_execution_evidence.py +88 -15
  78. package/runtime/python/okstra_ctl/report_finalize.py +18 -4
  79. package/runtime/python/okstra_ctl/report_html/render.py +46 -7
  80. package/runtime/python/okstra_ctl/report_html/validation.py +32 -0
  81. package/runtime/python/okstra_ctl/report_synthesis_packet.py +37 -3
  82. package/runtime/python/okstra_ctl/report_view_artifacts.py +12 -0
  83. package/runtime/python/okstra_ctl/review_verdicts.py +9 -0
  84. package/runtime/python/okstra_ctl/run.py +16 -0
  85. package/runtime/python/okstra_ctl/stage_done.py +11 -3
  86. package/runtime/python/okstra_ctl/stage_ledger.py +2 -2
  87. package/runtime/python/okstra_ctl/stage_map.py +3 -3
  88. package/runtime/python/okstra_ctl/trace_review.py +1 -0
  89. package/runtime/python/okstra_ctl/trace_tasks.py +22 -7
  90. package/runtime/python/okstra_ctl/verification_dispatch.py +32 -0
  91. package/runtime/python/okstra_ctl/verification_evidence.py +23 -3
  92. package/runtime/python/okstra_ctl/verification_generation.py +3 -2
  93. package/runtime/python/okstra_ctl/verification_inputs.py +3 -2
  94. package/runtime/python/okstra_ctl/verification_invocation.py +7 -3
  95. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +17 -0
  96. package/runtime/skills/okstra-brief-gen/SKILL.md +52 -6
  97. package/runtime/skills/okstra-code-review/SKILL.md +1 -1
  98. package/runtime/skills/okstra-code-review/references/census-rules.md +1 -1
  99. package/runtime/skills/okstra-code-review/references/review-calibration.md +1 -1
  100. package/runtime/skills/okstra-run/SKILL.md +31 -0
  101. package/runtime/skills/okstra-tdd/SKILL.md +75 -11
  102. package/runtime/templates/reports/html/assets/implementation-comparison.css +39 -0
  103. package/runtime/templates/reports/html/assets/implementation-comparison.js +55 -0
  104. package/runtime/templates/reports/html/i18n/en.json +113 -0
  105. package/runtime/templates/reports/html/i18n/ko.json +113 -0
  106. package/runtime/templates/reports/html/implementation-comparison.template.html +77 -0
  107. package/runtime/templates/reports/implementation-comparison-notes.md +72 -0
  108. package/runtime/templates/trace/trace.template.md +2 -0
  109. package/runtime/validators/validate-report-views.py +4 -36
@@ -2005,6 +2005,10 @@ def render_run_manifest(run_manifest_path: str, ctx: dict) -> None:
2005
2005
  )
2006
2006
  if _lead_runtime(ctx) == "claude-code":
2007
2007
  payload["claudeSessionId"] = ctx.get("CLAUDE_SESSION_ID", "")
2008
+ if "IMPLEMENTATION_COMPARISON_JSON" in ctx:
2009
+ payload["implementationComparison"] = json.loads(ctx["IMPLEMENTATION_COMPARISON_JSON"])
2010
+ elif "implementationComparison" in existing_run_manifest:
2011
+ payload["implementationComparison"] = existing_run_manifest["implementationComparison"]
2008
2012
  payload.update(execution_identity)
2009
2013
  _guard_invocation_manifest_rewrite(existing_run_manifest, payload)
2010
2014
  _write_json(Path(run_manifest_path), payload)
@@ -12,16 +12,18 @@ from __future__ import annotations
12
12
  import signal
13
13
  from dataclasses import dataclass
14
14
  from pathlib import Path
15
- from typing import Any, Literal, Mapping, TypedDict
15
+ from typing import Any, Callable, Iterable, Literal, Mapping, TypedDict
16
16
 
17
17
  from .conformance_evidence import (
18
- BoundInvocation, bound_attempt, evidence_read_errors, load_run_verifiers,
18
+ BoundInvocation, CheckRunRecord, bound_attempt, evidence_read_errors, load_run_verifiers,
19
19
  read_latest_check_run,
20
20
  )
21
21
  from .paths import RunRef
22
- from .qa_procedures import content_digest
22
+ from .json_boundary import ArtifactByteReader
23
+ from .qa_procedures import content_digest, project_artifact_relative_path, read_fingerprinted_artifact
23
24
  from .report_inputs import uses_execution_evidence
24
25
  from .verification_evidence import shell_exit_code
26
+ from .verification_invocation import VerificationGenerationReference
25
27
 
26
28
  EXECUTION_EVIDENCE_BLOCKING = "execution-evidence BLOCKING:"
27
29
  OUTPUT_TAIL_LINES = 20
@@ -82,40 +84,103 @@ class VerifierEvidence:
82
84
  references: tuple[ExecutionEvidenceReference, ...]
83
85
 
84
86
 
87
+ @dataclass(frozen=True)
88
+ class EvidenceSelection:
89
+ role_execution_ref: str
90
+ invocation_ref: str
91
+ attempt: int
92
+ generation_number: int
93
+ generation_reference: VerificationGenerationReference
94
+ check_runs: tuple[tuple[str, int], ...]
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class ReportEvidenceSnapshot:
99
+ evidence: dict[str, VerifierEvidence]
100
+ fingerprints: dict[str, str | None]
101
+ selections: tuple[EvidenceSelection, ...]
102
+ checks: Mapping[str, CheckRunRecord]
103
+
104
+
85
105
  def collect_report_evidence(
86
106
  project: Path, manifest_path: Path,
87
107
  ) -> dict[str, VerifierEvidence]:
88
108
  """Each verifier with an attempt bound to the newest generation, by role
89
109
  execution."""
90
110
  with evidence_read_errors():
91
- return _collect(project.resolve(), manifest_path.resolve())
111
+ return _collect(project.resolve(), manifest_path.resolve())[0]
92
112
 
93
113
 
94
- def _collect(project: Path, manifest_path: Path) -> dict[str, VerifierEvidence]:
95
- run = load_run_verifiers(project, manifest_path)
96
- newest = max((binding.generation_number for bindings in run.verifiers.values()
114
+ def collect_report_evidence_snapshot(
115
+ project: Path, manifest_path: Path, *, reader: ArtifactByteReader | None = None,
116
+ directory_entries: Callable[[Path], Iterable[Path]] | None = None,
117
+ generation_number: int | None = None,
118
+ generation_reference: VerificationGenerationReference | None = None,
119
+ ) -> ReportEvidenceSnapshot:
120
+ if (generation_number is None) != (generation_reference is None):
121
+ raise ValueError("Generation selection requires its number and sealed reference")
122
+ project = project.resolve()
123
+ fingerprints: dict[str, str | None] = {}
124
+ artifact_reader = Path.read_bytes if reader is None else reader
125
+ checks: dict[str, CheckRunRecord] = {}
126
+
127
+ def observed(path: Path) -> bytes:
128
+ return read_fingerprinted_artifact(project, path, artifact_reader, fingerprints)
129
+
130
+ with evidence_read_errors():
131
+ evidence, selections = _collect(
132
+ project, project / project_artifact_relative_path(project, manifest_path), reader=observed,
133
+ directory_entries=directory_entries,
134
+ generation_number=generation_number,
135
+ generation_reference=generation_reference,
136
+ checks=checks,
137
+ )
138
+ return ReportEvidenceSnapshot(evidence, fingerprints, selections, checks)
139
+
140
+
141
+ def _collect(
142
+ project: Path, manifest_path: Path, *, reader: ArtifactByteReader | None = None,
143
+ directory_entries: Callable[[Path], Iterable[Path]] | None = None,
144
+ generation_number: int | None = None,
145
+ generation_reference: VerificationGenerationReference | None = None,
146
+ checks: dict[str, CheckRunRecord] | None = None,
147
+ ) -> tuple[dict[str, VerifierEvidence], tuple[EvidenceSelection, ...]]:
148
+ run = load_run_verifiers(project, manifest_path, **({"reader": reader} if reader is not None else {}))
149
+ newest = generation_number if generation_number is not None else max((binding.generation_number for bindings in run.verifiers.values()
97
150
  for binding in bindings if binding.generation is not None),
98
151
  default=None)
99
152
  evidence = {}
153
+ selections = []
100
154
  for role_execution_ref in run.verifiers:
101
155
  bound = None if newest is None else bound_attempt(run, role_execution_ref, newest)
102
- if bound is not None:
103
- evidence[role_execution_ref] = _verifier_evidence(
156
+ if bound is not None and (generation_reference is None or bound[0].generation_ref == generation_reference.to_payload()):
157
+ verifier = _verifier_evidence(
104
158
  project, run.ref, role_execution_ref, *bound,
159
+ reader=reader, directory_entries=directory_entries, checks=checks,
105
160
  )
106
- return evidence
161
+ evidence[role_execution_ref] = verifier
162
+ selections.append(EvidenceSelection(role_execution_ref, verifier.invocation_ref, verifier.attempt,
163
+ bound[0].generation_number,
164
+ VerificationGenerationReference.from_payload(dict(verifier.generation_ref)),
165
+ tuple((row["checkRef"], row["checkRun"]) for row in verifier.references)))
166
+ return evidence, tuple(selections)
107
167
 
108
168
 
109
169
  def _verifier_evidence(
110
170
  project: Path, ref: RunRef, role_execution_ref: str, binding: BoundInvocation,
111
171
  attempt: int,
172
+ *, reader: ArtifactByteReader | None = None,
173
+ directory_entries: Callable[[Path], Iterable[Path]] | None = None,
174
+ checks: dict[str, CheckRunRecord] | None = None,
112
175
  ) -> VerifierEvidence:
113
176
  invocation_ref = binding.invocation.invocation_ref
114
177
  return VerifierEvidence(
115
178
  role_execution_ref, invocation_ref, attempt, binding.generation_ref,
116
179
  tuple(
117
- _reference(project, ref, role_execution_ref, binding, attempt, check_ref)
118
- for check_ref in ref.verification_check_refs(invocation_ref, attempt)
180
+ _reference(project, ref, role_execution_ref, binding, attempt, check_ref,
181
+ reader=reader, directory_entries=directory_entries, checks=checks)
182
+ for check_ref in ref.verification_check_refs(invocation_ref, attempt,
183
+ **({"directory_entries": directory_entries} if directory_entries is not None else {}))
119
184
  ),
120
185
  )
121
186
 
@@ -123,15 +188,23 @@ def _verifier_evidence(
123
188
  def _reference(
124
189
  project: Path, ref: RunRef, role_execution_ref: str, binding: BoundInvocation,
125
190
  attempt: int, check_ref: str,
191
+ *, reader: ArtifactByteReader | None = None,
192
+ directory_entries: Callable[[Path], Iterable[Path]] | None = None,
193
+ checks: dict[str, CheckRunRecord] | None = None,
126
194
  ) -> ExecutionEvidenceReference:
127
195
  invocation_ref = binding.invocation.invocation_ref
128
- check = read_latest_check_run(ref, role_execution_ref, binding, attempt, check_ref)
196
+ check = read_latest_check_run(ref, role_execution_ref, binding, attempt, check_ref,
197
+ **({"reader": reader} if reader is not None else {}),
198
+ **({"directory_entries": directory_entries} if directory_entries is not None else {}))
129
199
  if check is None:
130
200
  raise ValueError(f"{check_ref} of {invocation_ref} has no check run directory")
131
201
  record, path = check.record, check.path
202
+ record_path = path.relative_to(project).as_posix()
203
+ if checks is not None:
204
+ checks[record_path] = check
132
205
  return {
133
- "recordPath": path.relative_to(project).as_posix(),
134
- "recordDigest": content_digest(path.read_bytes()) if path.is_file() else None,
206
+ "recordPath": record_path,
207
+ "recordDigest": content_digest(check.raw_bytes) if check.raw_bytes is not None else None,
135
208
  "invocationRef": invocation_ref, "attempt": attempt, "checkRef": check_ref,
136
209
  "checkRun": check.check_run, "generation": dict(binding.generation_ref),
137
210
  "collection": "complete" if check.defect is None else "incomplete",
@@ -185,10 +185,12 @@ def task_id(manifest: Mapping[str, Any]) -> str:
185
185
 
186
186
 
187
187
  def _category_seq(manifest: Mapping[str, Any], category: str) -> str:
188
- seqs = manifest.get("runSequencesByCategory")
189
- if not isinstance(seqs, Mapping):
190
- raise FinalizeError("run manifest has no runSequencesByCategory object")
191
- return require_string(seqs, category)
188
+ from .report_view_artifacts import manifest_category_sequence
189
+
190
+ try:
191
+ return manifest_category_sequence(manifest, category)
192
+ except ValueError as exc:
193
+ raise FinalizeError(str(exc)) from exc
192
194
 
193
195
 
194
196
  def run_seq(manifest: Mapping[str, Any]) -> str:
@@ -726,6 +728,12 @@ def run_finalize(
726
728
  failed = business_flow_warnings(step["result"])
727
729
  if failed:
728
730
  payload["businessFlowWarnings"] = failed
731
+ elif step["name"] == "implementation-comparison":
732
+ comparison = step["result"]
733
+ payload["comparison"] = comparison["comparison"]
734
+ payload["linkStatus"] = comparison["linkStatus"]
735
+ if comparison["warnings"]:
736
+ payload["comparisonWarnings"] = comparison["warnings"]
729
737
  census = _census_summary(ctx)
730
738
  if census is not None:
731
739
  payload["censusWarnings"] = census
@@ -806,6 +814,12 @@ def _execute_finalize_steps(
806
814
  business = _finalize_business_effects(ctx)
807
815
  if business is not None:
808
816
  steps.append({"name": "business-flow", "exitCode": 0, "result": business})
817
+ if ctx.task_type == "implementation":
818
+ from .implementation_comparison.run_integration import finalize_run_comparison
819
+
820
+ comparison = finalize_run_comparison(ctx.project_root, ctx.manifest_path)
821
+ if comparison is not None:
822
+ steps.append({"name": "implementation-comparison", "exitCode": 0, "result": comparison})
809
823
  if validated and not first_failure:
810
824
  _record_run_end(ctx.team_state_path)
811
825
  return steps, first_failure
@@ -3,7 +3,9 @@ from __future__ import annotations
3
3
 
4
4
  import hashlib
5
5
  import json
6
+ import os
6
7
  from pathlib import Path
8
+ import tempfile
7
9
 
8
10
  import okstra_vendor # noqa: F401 # registers vendored dependency aliases
9
11
  from jinja2 import Environment, StrictUndefined, select_autoescape
@@ -13,7 +15,7 @@ from ..final_report_schema import load_schema_for_data, validate
13
15
  from ..i18n import HTML_DICTIONARY_REL, load_dictionary, make_jinja_global
14
16
  from ..report_view_artifacts import user_responses_dir_for_report
15
17
  from ..usage_cells import format_duration_ms
16
- from ..json_boundary import load_owned_object
18
+ from ..json_boundary import load_owned_object_snapshot, read_bounded_bytes
17
19
  from ..report_template_loader import report_template_loader
18
20
  from .common import anchor_index, worker_finding_links
19
21
  from .context_links import (
@@ -35,10 +37,44 @@ from .models import HtmlRunMeta
35
37
  from .report_index import inject_report_index
36
38
  from .router import HtmlRenderError, resolve_html_route
37
39
  from .run_usage import run_usage
40
+ from .validation import dead_in_page_links, external_resource_errors
38
41
 
39
42
 
40
- def _sha256(path: Path) -> str:
41
- return hashlib.sha256(path.read_bytes()).hexdigest()
43
+ def _sha256(path: Path, max_bytes: int | None = None) -> str:
44
+ raw = path.read_bytes() if max_bytes is None else read_bounded_bytes(path, max_bytes=max_bytes, artifact="HTML publication input")
45
+ return hashlib.sha256(raw).hexdigest()
46
+
47
+
48
+ class HtmlSourceChanged(HtmlRenderError):
49
+ """A preserved source changed before its derived HTML could be replaced."""
50
+
51
+
52
+ def write_html_atomic(
53
+ output_path: Path, document: str, *, source_path: Path, source_digest: str,
54
+ expected_html_digest: str | None = None, max_input_bytes: int | None = None,
55
+ ) -> Path:
56
+ encoded = document.encode("utf-8")
57
+ output_path.parent.mkdir(parents=True, exist_ok=True)
58
+ descriptor, name = tempfile.mkstemp(prefix=f".{output_path.name}.", dir=output_path.parent)
59
+ temporary = Path(name)
60
+ try:
61
+ with os.fdopen(descriptor, "wb") as handle:
62
+ handle.write(encoded)
63
+ handle.flush()
64
+ os.fsync(handle.fileno())
65
+ stored = read_bounded_bytes(temporary, max_bytes=len(encoded), artifact="generated HTML")
66
+ stored_text = stored.decode("utf-8")
67
+ errors = external_resource_errors(stored_text) + dead_in_page_links(stored_text)
68
+ if stored != encoded or errors:
69
+ raise HtmlRenderError("invalid HTML before publication: " + "; ".join(errors))
70
+ if _sha256(source_path, max_input_bytes) != source_digest:
71
+ raise HtmlSourceChanged("report source changed before HTML publication")
72
+ if expected_html_digest is not None and _sha256(output_path, max_input_bytes) != expected_html_digest:
73
+ raise HtmlRenderError("existing HTML changed before link publication")
74
+ os.replace(temporary, output_path)
75
+ finally:
76
+ temporary.unlink(missing_ok=True)
77
+ return output_path
42
78
 
43
79
 
44
80
  def _templates_root(start: Path | None = None) -> Path:
@@ -98,7 +134,8 @@ def render_v2_html_view(
98
134
  no reader ever compared, which made a derived artifact a precondition for
99
135
  another derived artifact.
100
136
  """
101
- data = load_owned_object(data_path, artifact="final report record")
137
+ snapshot = load_owned_object_snapshot(data_path, artifact="final report record")
138
+ data = snapshot.value
102
139
  errors = validate(data, load_schema_for_data(data))
103
140
  if errors:
104
141
  raise HtmlRenderError("invalid v2 final-report data: " + "; ".join(errors[:5]))
@@ -160,7 +197,7 @@ def render_v2_html_view(
160
197
  "taskType": view.task_type,
161
198
  "lang": lang,
162
199
  "sourceData": source_data,
163
- "dataSha256": _sha256(data_path),
200
+ "dataSha256": hashlib.sha256(snapshot.raw_bytes).hexdigest(),
164
201
  "clarificationItems": data.get("clarificationItems", []),
165
202
  # 브리프의 최종 상태 행과 이 run 의 `endStateCoverage` 판정을 한 표로.
166
203
  # 모든 phase 가 EB/PB/EO 아이디를 인용하지만 문장은 브리프에만 있고,
@@ -192,9 +229,11 @@ def render_v2_html_view(
192
229
  output_path = _html_path(data_path)
193
230
  document = env.get_template(route.template_name).render(**context)
194
231
  document = inject_report_index(document, label=translate("base.contents"))
195
- output_path.write_text(document, encoding="utf-8")
196
232
  # The footer tells the reader to drop the exported file here, so the
197
233
  # directory has to exist before they go looking for it — on every report,
198
234
  # not only those with clarification rows: the footer is rendered on all.
199
235
  user_responses_dir.mkdir(parents=True, exist_ok=True)
200
- return output_path
236
+ return write_html_atomic(
237
+ output_path, document, source_path=data_path,
238
+ source_digest=hashlib.sha256(snapshot.raw_bytes).hexdigest(),
239
+ )
@@ -0,0 +1,32 @@
1
+ """Shared self-contained resource and in-page link checks."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+
7
+ _EXTERNAL_URL_RE = re.compile(
8
+ r'<(?:script|link|img|iframe|source|video|audio)\s[^>]*?(?:src|href)\s*=\s*["\']https?://',
9
+ re.IGNORECASE,
10
+ )
11
+ _ANCHOR_HREF_RE = re.compile(r'href="#([^"]+)"')
12
+ _ELEMENT_ID_RE = re.compile(r'(?<![\w-])id="([^"]+)"')
13
+
14
+
15
+ def external_resource_errors(document: str) -> list[str]:
16
+ if _EXTERNAL_URL_RE.search(document):
17
+ return ["html contains external URL in script/link/img — must be self-contained"]
18
+ return []
19
+
20
+
21
+ def dead_in_page_links(document: str) -> list[str]:
22
+ body = document.split("<body", 1)[-1]
23
+ body = re.sub(r"<script.*?</script>|<style.*?</style>", "", body, flags=re.DOTALL)
24
+ ids = set(_ELEMENT_ID_RE.findall(body))
25
+ dead = sorted({target for target in _ANCHOR_HREF_RE.findall(body) if target not in ids})
26
+ if not dead:
27
+ return []
28
+ return [
29
+ "dead in-page link(s): "
30
+ + ", ".join(f"#{target}" for target in dead[:12])
31
+ + (f" (+{len(dead) - 12} more)" if len(dead) > 12 else "")
32
+ ]
@@ -7,7 +7,7 @@ import os
7
7
  import re
8
8
  import tempfile
9
9
  from collections import Counter
10
- from dataclasses import dataclass
10
+ from dataclasses import dataclass, replace
11
11
  from pathlib import Path
12
12
  from typing import Any, Mapping
13
13
 
@@ -98,6 +98,7 @@ class ReportSynthesisPacket:
98
98
  # 거절할 때까지 그 지시를 거를 근거가 없었다(2026-09-03 실측).
99
99
  allowed_top_level: tuple[str, ...] = ()
100
100
  authoring_format: str = "markdown-v1"
101
+ implementation_comparison: dict[str, Any] | None = None
101
102
 
102
103
  def _carry_instructions(self) -> list[str]:
103
104
  """이번 run 의 이월 지시. 증분이 아니면 빈 목록.
@@ -335,7 +336,7 @@ class ReportSynthesisPacket:
335
336
  ]
336
337
 
337
338
  def to_dict(self) -> dict[str, Any]:
338
- return {
339
+ payload = {
339
340
  "schemaVersion": "1.0",
340
341
  "taskKey": self.task_key,
341
342
  "taskType": self.task_type,
@@ -348,7 +349,8 @@ class ReportSynthesisPacket:
348
349
  "Write the complete human-readable report narrative.",
349
350
  "Preserve settled source values, identities, dissent, and user responses.",
350
351
  "Do not invent a value when a source is missing or contradictory.",
351
- "Write only the narrative, pointer, and audit artifacts named by the dispatch.",
352
+ "Write only the narrative, pointer, audit artifacts, and any comparison notes path explicitly supplied by the dispatch.",
353
+ *comparison_authoring_instructions(self.implementation_comparison),
352
354
  *_INTERNAL_IDENTIFIER_INSTRUCTION,
353
355
  *_READER_PROSE_INSTRUCTION,
354
356
  *self._schema_instructions(),
@@ -370,6 +372,9 @@ class ReportSynthesisPacket:
370
372
  "accountingSnapshot": self.accounting_snapshot,
371
373
  "sources": [source.to_dict() for source in self.sources],
372
374
  }
375
+ if self.implementation_comparison is not None:
376
+ payload["authoringContract"]["implementationComparison"] = self.implementation_comparison
377
+ return payload
373
378
 
374
379
  def to_markdown(self) -> str:
375
380
  lines = [
@@ -395,7 +400,12 @@ class ReportSynthesisPacket:
395
400
  lines.extend(f"- {text}" for text in self._schema_instructions())
396
401
  lines.extend(f"- {text}" for text in self._task_instructions())
397
402
  lines.extend(f"- {text}" for text in self._carry_instructions())
403
+ lines.extend(f"- {text}" for text in comparison_authoring_instructions(self.implementation_comparison))
398
404
  sections = [("Authoring Contract", "\n".join(lines[1:]).rstrip() + "\n")]
405
+ if self.implementation_comparison is not None:
406
+ sections.append(("Implementation Comparison", "```json\n" + json.dumps(
407
+ self.implementation_comparison, ensure_ascii=False, indent=2,
408
+ ) + "\n```\n"))
399
409
  sections.extend(
400
410
  (source.label, "\n".join(_source_markdown(
401
411
  source, self.task_type, self.sources, self.authoring_format,
@@ -1055,6 +1065,23 @@ def _read_sources(
1055
1065
  return tuple(sources)
1056
1066
 
1057
1067
 
1068
+ def comparison_authoring_instructions(comparison: Mapping[str, Any] | None) -> list[str]:
1069
+ if comparison is None:
1070
+ return []
1071
+ instructions = [
1072
+ "The implementation comparison context is supplementary; preserve its limitations and actual runner evidence.",
1073
+ "Use only supplied recordIds and preserved source references. Do not author command results, hashes, or verification facts in notes.",
1074
+ ]
1075
+ if comparison.get("notesPath") and comparison.get("notesGuide"):
1076
+ instructions.append(
1077
+ f"Write optional comparison notes only to `{comparison['notesPath']}` using schemaVersion 1.0, "
1078
+ "the supplied owner, baselineRef, targetRef, and changes. Keep the report narrative complete without notes."
1079
+ )
1080
+ elif comparison.get("notesPath"):
1081
+ instructions.append("The comparison notes guide is unavailable; leave supplementary notes unwritten and preserve that limitation.")
1082
+ return instructions
1083
+
1084
+
1058
1085
  def build_report_synthesis_packet(
1059
1086
  *,
1060
1087
  project_root: Path,
@@ -1062,6 +1089,7 @@ def build_report_synthesis_packet(
1062
1089
  active_context: Mapping[str, Any],
1063
1090
  team_state: Mapping[str, Any],
1064
1091
  narrative_path: Path,
1092
+ implementation_comparison: Mapping[str, Any] | None = None,
1065
1093
  ) -> ReportSynthesisPacket:
1066
1094
  authoring_format = report_authoring_format(manifest)
1067
1095
  report_synthesis_packet_paths(narrative_path, authoring_format)
@@ -1119,6 +1147,7 @@ def build_report_synthesis_packet(
1119
1147
  participating_analysers=participating_analysers,
1120
1148
  incremental_decision=carried.incremental_decision if carried else None,
1121
1149
  prior_plan_carry=carried.prior_plan if carried else None,
1150
+ implementation_comparison=copy.deepcopy(dict(implementation_comparison)) if implementation_comparison is not None else None,
1122
1151
  )
1123
1152
 
1124
1153
 
@@ -1204,6 +1233,7 @@ def materialize_report_synthesis_packet(
1204
1233
  active_context: Mapping[str, Any],
1205
1234
  team_state: Mapping[str, Any],
1206
1235
  narrative_path: Path,
1236
+ manifest_path: Path | None = None,
1207
1237
  ) -> tuple[Path, Path]:
1208
1238
  packet = build_report_synthesis_packet(
1209
1239
  project_root=project_root,
@@ -1212,6 +1242,10 @@ def materialize_report_synthesis_packet(
1212
1242
  team_state=team_state,
1213
1243
  narrative_path=narrative_path,
1214
1244
  )
1245
+ if manifest_path is not None:
1246
+ from .implementation_comparison.run_integration import prepare_run_comparison
1247
+
1248
+ packet = replace(packet, implementation_comparison=prepare_run_comparison(project_root, manifest_path))
1215
1249
  data_path, markdown_path = report_synthesis_packet_paths(
1216
1250
  narrative_path, packet.authoring_format,
1217
1251
  )
@@ -2,10 +2,22 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  from pathlib import Path
5
+ from collections.abc import Mapping
6
+ from typing import Any
5
7
 
6
8
  from .json_boundary import JsonBoundaryError, load_owned_object
7
9
 
8
10
 
11
+ def manifest_category_sequence(manifest: Mapping[str, Any], category: str) -> str:
12
+ sequences = manifest.get("runSequencesByCategory")
13
+ if not isinstance(sequences, Mapping):
14
+ raise ValueError("run manifest has no runSequencesByCategory object")
15
+ value = sequences.get(category)
16
+ if not isinstance(value, str) or not value.strip():
17
+ raise ValueError(f"missing required string field: {category}")
18
+ return value
19
+
20
+
9
21
  def html_view_path(report_path: Path) -> Path:
10
22
  """Return the HTML sibling for a final-report Markdown or data path."""
11
23
  if report_path.name.endswith(".data.json"):
@@ -141,6 +141,15 @@ class _HeadTree:
141
141
  return len(content.stdout.decode("utf-8").splitlines())
142
142
 
143
143
 
144
+ def binding_lines(body: str) -> list[str]:
145
+ """Body lines without surrounding whitespace, for matching copied binding lines.
146
+
147
+ Reviewers often end a copied binding line with two spaces, a Markdown line
148
+ break, which does not change the value it carries.
149
+ """
150
+ return [line.strip() for line in body.splitlines()]
151
+
152
+
144
153
  def _head_tree(project_root: Path, head: str) -> _HeadTree:
145
154
  resolved = subprocess.run(
146
155
  ["git", "-C", str(project_root), "rev-parse", "--verify", "--quiet",
@@ -4445,6 +4445,7 @@ def prepare_task_bundle(inp: PrepareInputs) -> PrepareOutputs:
4445
4445
  report_authoring_format="json-v1",
4446
4446
  usage_accounting_policy="advisory",
4447
4447
  )
4448
+ comparison_new_run = not Path(ctx["RUN_MANIFEST_PATH"]).exists()
4448
4449
 
4449
4450
  ctx.update({
4450
4451
  "TERMINAL_BACKEND": terminal_backend,
@@ -4611,7 +4612,22 @@ def prepare_task_bundle(inp: PrepareInputs) -> PrepareOutputs:
4611
4612
  )
4612
4613
  # ---- run-inputs persistence ----
4613
4614
  _persist_run_inputs(inp, ctx, models, selected_reviewers, brief_relative)
4615
+ if inp.task_type == "implementation":
4616
+ from .implementation_comparison.preparation import declare_implementation_comparison
4617
+
4618
+ declare_implementation_comparison(
4619
+ ctx, Path(worktree.path or project_root), stage_run_claim.stage, new_run=comparison_new_run,
4620
+ )
4614
4621
  _persist_pre_dispatch_run_manifest(ctx)
4622
+ if inp.task_type == "implementation":
4623
+ from .implementation_comparison.preparation import capture_implementation_comparison
4624
+ from .worktree_registry import get_implementation_base
4625
+
4626
+ capture_implementation_comparison(
4627
+ ctx, stage_base=stage_run_claim.worktree_base_ref or stage_run_claim.started_head_commit,
4628
+ task_base=get_implementation_base(inp.project_id, inp.task_group, inp.task_id) or "",
4629
+ new_run=comparison_new_run,
4630
+ )
4615
4631
 
4616
4632
  # ---- lead prompt publication (manifest is now the external authority) ----
4617
4633
  prompt_text = _render_lead_prompt_and_snapshot(
@@ -102,7 +102,7 @@ def _supersede(target: Path, rows: list[dict], stage: int) -> Path:
102
102
  def done_stage(
103
103
  project_root: Path, task_key: str, stage: int, carry_file: Path, report: Path,
104
104
  ) -> dict:
105
- """Write the stage's carry sidecar at its canonical path and append the `done` row."""
105
+ """Persist completion before refreshing the optional derived task comparison."""
106
106
  identity, plan_run_root = resolve_planned_stage(project_root, task_key, stage)
107
107
  carry = _read_carry(carry_file, stage)
108
108
  head = carry_head_commit(carry)
@@ -149,6 +149,9 @@ def done_stage(
149
149
  report_path=report_rel,
150
150
  completed_at=datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
151
151
  )
152
+ from .implementation_comparison.run_integration import finalize_task_comparison
153
+
154
+ comparison = finalize_task_comparison(project_root, task_root, identity["taskKey"])
152
155
  return {
153
156
  "taskKey": identity["taskKey"],
154
157
  "stage": stage,
@@ -158,6 +161,7 @@ def done_stage(
158
161
  "reportPath": report_rel,
159
162
  "consumersPath": str(plan_run_root / "consumers.jsonl"),
160
163
  "fileSizeCap": file_size_cap,
164
+ "comparison": comparison,
161
165
  }
162
166
 
163
167
 
@@ -175,13 +179,17 @@ Refuses a carry for another stage, a failed carry, a stage already done at
175
179
  another head, and a carry whose stageCommitRange diff adds a source or test file
176
180
  over the 500-line limit or takes one past it (`okstra correction file-size`); a
177
181
  file already over 500 at the stage base may grow. Re-running with the
178
- same carry writes nothing new.
182
+ same carry preserves its carry and completion row; changed comparison inputs may
183
+ produce a new optional report revision.
179
184
 
180
185
  Input-4.0 runs also require the latest accepted report for this task/stage and
181
186
  matching base/head, current sealed verifier results and complete design coverage.
182
187
 
188
+ After the done row is saved, refresh the optional whole-task comparison from stored
189
+ records. Comparison failure is returned separately and does not withdraw completion.
190
+
183
191
  Output: JSON { ok, taskKey, stage, headCommit, carryPath, supersededCarryPath,
184
- reportPath, consumersPath, fileSizeCap }. Exit 1 on a refusal, 2 when
192
+ reportPath, consumersPath, fileSizeCap, comparison }. Exit 1 on a refusal, 2 when
185
193
  PROJECT_ROOT cannot be resolved.
186
194
  """
187
195
 
@@ -62,7 +62,7 @@ def build_stage_ledger(task_root: Path) -> dict[str, Any] | None:
62
62
  records = lifecycle.ledger_records()
63
63
 
64
64
  built_from, divergence = _built_from(task_root, latest)
65
- divergence += _renumbering_divergence(
65
+ divergence += renumbering_divergence(
66
66
  latest, built_from, state.done_stages
67
67
  )
68
68
  ledger: dict[str, Any] = {
@@ -112,7 +112,7 @@ def _built_from(task_root: Path, latest: Any):
112
112
  ]
113
113
 
114
114
 
115
- def _renumbering_divergence(
115
+ def renumbering_divergence(
116
116
  latest: Any,
117
117
  built_from: Any,
118
118
  done_stages: set[int],
@@ -378,8 +378,8 @@ def stage_row_is_cancelled(
378
378
  return status == "cancelled"
379
379
 
380
380
 
381
- def _parse_schema_v2_stage_map(
382
- data: dict[str, Any], source_plan_path: str,
381
+ def parse_stage_map_data(
382
+ data: dict[str, Any], *, source_plan_path: str = "",
383
383
  ) -> list[StageMapStage]:
384
384
  planning = data.get("implementationPlanning")
385
385
  stage_map = planning.get("stageMap") if isinstance(planning, dict) else None
@@ -416,7 +416,7 @@ def parse_stage_map_file(plan_path: Path) -> list[StageMapStage]:
416
416
  raise StageMapError(
417
417
  "stage_map", "structured report must be an object", str(resolved)
418
418
  )
419
- return _parse_schema_v2_stage_map(data, str(resolved))
419
+ return parse_stage_map_data(data, source_plan_path=str(resolved))
420
420
  return _parse_stage_map_markdown(resolved)
421
421
 
422
422
 
@@ -34,6 +34,7 @@ STEP_OPERATIONS = {
34
34
  "analysis-review": "trace-scope-review",
35
35
  "spec-review": "trace-scope-review",
36
36
  "interface-review": "trace-interface-review",
37
+ "tests-review": "trace-tests-review",
37
38
  }
38
39
  _DIGEST_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
39
40
  _VERDICT_RE = re.compile(r"^Trace review verdict: (pass|fail)[ \t]*$", re.MULTILINE)