okstra 0.227.0 → 0.228.1

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 (76) hide show
  1. package/README.md +1 -1
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/docs/architecture/storage-model.md +77 -0
  5. package/docs/cli.md +15 -3
  6. package/docs/project-structure-overview.md +12 -2
  7. package/package.json +1 -1
  8. package/runtime/BUILD.json +2 -2
  9. package/runtime/prompts/coding-preflight/clean-code.md +24 -18
  10. package/runtime/prompts/coding-preflight/overview.md +6 -6
  11. package/runtime/prompts/duties/code-reviewer.json +1 -0
  12. package/runtime/prompts/lead/convergence.md +5 -19
  13. package/runtime/prompts/lead/okstra-lead-contract.md +1 -1
  14. package/runtime/prompts/profiles/_coding-conventions-preflight.md +1 -1
  15. package/runtime/python/okstra_ctl/adapters/verification_inputs.py +22 -0
  16. package/runtime/python/okstra_ctl/adapters/worker_defaults.py +2 -2
  17. package/runtime/python/okstra_ctl/analysis_packet.py +52 -21
  18. package/runtime/python/okstra_ctl/approval_decisions.py +30 -1
  19. package/runtime/python/okstra_ctl/approved_plan_stage_extract.py +100 -66
  20. package/runtime/python/okstra_ctl/brief_sources.py +162 -44
  21. package/runtime/python/okstra_ctl/code_review_coverage.py +11 -1
  22. package/runtime/python/okstra_ctl/code_review_scope.py +157 -0
  23. package/runtime/python/okstra_ctl/code_review_target.py +46 -10
  24. package/runtime/python/okstra_ctl/conformance.py +9 -3
  25. package/runtime/python/okstra_ctl/design_surfaces.py +51 -19
  26. package/runtime/python/okstra_ctl/final_report_schema.py +37 -30
  27. package/runtime/python/okstra_ctl/fixed_text.py +31 -9
  28. package/runtime/python/okstra_ctl/implementation_direction.py +18 -0
  29. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +59 -21
  30. package/runtime/python/okstra_ctl/json_registry.py +3 -18
  31. package/runtime/python/okstra_ctl/manager_split.py +201 -84
  32. package/runtime/python/okstra_ctl/model_io/references.py +31 -1
  33. package/runtime/python/okstra_ctl/model_io/renderers.py +30 -1
  34. package/runtime/python/okstra_ctl/model_io_cli.py +9 -0
  35. package/runtime/python/okstra_ctl/path_hints.py +13 -1
  36. package/runtime/python/okstra_ctl/paths.py +4 -0
  37. package/runtime/python/okstra_ctl/phases/final_verification/prior_blockers.py +87 -45
  38. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +2 -2
  39. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +10 -2
  40. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +19 -11
  41. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +3 -1
  42. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +3 -1
  43. package/runtime/python/okstra_ctl/phases/implementation/spec.md +14 -0
  44. package/runtime/python/okstra_ctl/phases/implementation_option_selection/authoring.py +2 -1
  45. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  46. package/runtime/python/okstra_ctl/phases/implementation_option_selection/validation.py +53 -37
  47. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  48. package/runtime/python/okstra_ctl/plan_items.py +9 -11
  49. package/runtime/python/okstra_ctl/ports/verification_inputs.py +17 -0
  50. package/runtime/python/okstra_ctl/prior_planning.py +6 -17
  51. package/runtime/python/okstra_ctl/prior_run_summary.py +35 -0
  52. package/runtime/python/okstra_ctl/qa_commands.py +66 -1
  53. package/runtime/python/okstra_ctl/qa_commands_cli.py +67 -0
  54. package/runtime/python/okstra_ctl/qa_procedures.py +235 -0
  55. package/runtime/python/okstra_ctl/registry/verification_inputs_store.py +8 -0
  56. package/runtime/python/okstra_ctl/render.py +10 -0
  57. package/runtime/python/okstra_ctl/report_assembly.py +12 -12
  58. package/runtime/python/okstra_ctl/run.py +108 -5
  59. package/runtime/python/okstra_ctl/verification_input_ref.py +80 -0
  60. package/runtime/python/okstra_ctl/verification_input_types.py +32 -0
  61. package/runtime/python/okstra_ctl/verification_inputs.py +162 -0
  62. package/runtime/python/okstra_ctl/verification_plan.py +116 -0
  63. package/runtime/python/okstra_ctl/worker_prompt_body.py +12 -6
  64. package/runtime/python/okstra_ctl/worker_prompt_contract.py +5 -1
  65. package/runtime/python/okstra_ctl/worker_prompt_headers.py +50 -1
  66. package/runtime/python/okstra_project/dirs.py +22 -0
  67. package/runtime/python/okstra_project/resolver.py +10 -0
  68. package/runtime/schemas/final-report-v3.0.schema.json +5 -1
  69. package/runtime/skills/okstra-brief-gen/SKILL.md +10 -4
  70. package/runtime/skills/okstra-code-review/SKILL.md +39 -45
  71. package/runtime/skills/okstra-code-review/references/census-rules.md +14 -2
  72. package/runtime/skills/okstra-code-review/references/review-calibration.md +31 -8
  73. package/runtime/skills/okstra-manager/SKILL.md +2 -2
  74. package/runtime/skills/okstra-setup/SKILL.md +2 -0
  75. package/runtime/skills/okstra-setup/references/project-config.md +2 -0
  76. package/runtime/validators/validate-brief.py +21 -5
@@ -272,8 +272,12 @@ def _files_cell_tokens(cell: str) -> list[str]:
272
272
  return tokens
273
273
 
274
274
 
275
+ # Characters that continue a path: a path is named only where neither side has one.
276
+ PATH_CHARS = r"\w./@-"
277
+
278
+
275
279
  def _cell_covers_path(cell: str, path: str) -> bool:
276
- path_pattern = rf"(?<![\w./@-]){re.escape(path)}(?![\w./@-])"
280
+ path_pattern = rf"(?<![{PATH_CHARS}]){re.escape(path)}(?![{PATH_CHARS}])"
277
281
  if re.search(path_pattern, cell) is not None:
278
282
  return True
279
283
  for token in _files_cell_tokens(cell):
@@ -301,6 +305,27 @@ def _stages_touching_path(
301
305
  return hits
302
306
 
303
307
 
308
+ def _declared_parts(path: str) -> list[str]:
309
+ parts = [
310
+ _LINE_RANGE_SUFFIX.sub("", _normalise(part))
311
+ for part in (_split_declared_paths(path) or [path])
312
+ ]
313
+ return [part for part in parts if part]
314
+
315
+
316
+ def stages_touching_declared_path(
317
+ path: str,
318
+ stages: Mapping[int, Mapping[str, Any]],
319
+ ) -> list[int]:
320
+ """Every stage whose step cells touch a part of a ``fileStructure`` path."""
321
+ matched: list[int] = []
322
+ for part in _declared_parts(path):
323
+ for stage_number in _stages_touching_path(part, stages):
324
+ if stage_number not in matched:
325
+ matched.append(stage_number)
326
+ return matched
327
+
328
+
304
329
  def _stages_for_selected_path(
305
330
  path: str,
306
331
  stages: Mapping[int, Mapping[str, Any]],
@@ -318,32 +343,22 @@ def _stages_for_selected_path(
318
343
  Zero stages is still an error: the recommended option declares a file that
319
344
  no step creates or edits.
320
345
  """
321
- declared = [
322
- _LINE_RANGE_SUFFIX.sub("", _normalise(part))
323
- for part in (_split_declared_paths(path) or [path])
324
- ]
325
- declared = [part for part in declared if part]
346
+ declared = _declared_parts(path)
326
347
  if not declared:
327
348
  raise DesignSurfaceError(
328
349
  f"selected option path {path!r} is not mapped to a stage"
329
350
  )
330
- matched: list[int] = []
331
- seen: set[int] = set()
332
351
  for part in declared:
333
- hits = _stages_touching_path(part, stages)
334
- if not hits and "qa/scripts/" in part:
352
+ if _stages_touching_path(part, stages):
353
+ continue
354
+ if "qa/scripts/" in part:
335
355
  # 적합성 스크립트는 executor 가 역할 권한으로 쓴다(write_policy
336
356
  # `_role_qa_artifact_paths`). 계획 step 의 files·plannedPaths 칸에는 원래 없다.
337
357
  continue
338
- if not hits:
339
- raise DesignSurfaceError(
340
- f"selected option path {part!r} is not mapped to a stage"
341
- )
342
- for stage_number in hits:
343
- if stage_number not in seen:
344
- seen.add(stage_number)
345
- matched.append(stage_number)
346
- return matched
358
+ raise DesignSurfaceError(
359
+ f"selected option path {part!r} is not mapped to a stage"
360
+ )
361
+ return stages_touching_declared_path(path, stages)
347
362
 
348
363
 
349
364
  def detect_design_surfaces(
@@ -385,3 +400,20 @@ def detect_design_surfaces(
385
400
  key=lambda key: (key[0], rule_order[key[1]]),
386
401
  )
387
402
  ]
403
+
404
+
405
+ def detect_design_surfaces_in_unvalidated_plan(
406
+ planning: object,
407
+ ) -> list[DesignSurfaceTrigger]:
408
+ """Detect design surfaces of an unvalidated plan; a plan without stages has none.
409
+
410
+ Every detection failure, including a malformed row the detector trips over,
411
+ becomes one `DesignSurfaceError`, so the draft check and `plan-items prepare`
412
+ reach the same verdict on the same plan.
413
+ """
414
+ if not isinstance(planning, Mapping) or not planning.get("stages"):
415
+ return []
416
+ try:
417
+ return detect_design_surfaces(planning)
418
+ except (DesignSurfaceError, TypeError, AttributeError) as exc:
419
+ raise DesignSurfaceError(f"design-surface detection failed: {exc}") from exc
@@ -62,30 +62,38 @@ def _check_type(value: Any, expected: str) -> bool:
62
62
  return isinstance(value, _TYPE_PYTHON.get(expected, ()))
63
63
 
64
64
 
65
- def _json_schema_equal(left: Any, right: Any) -> bool:
66
- if isinstance(left, bool) or isinstance(right, bool):
67
- return isinstance(left, bool) and isinstance(right, bool) and left == right
68
- if isinstance(left, (int, float)) or isinstance(right, (int, float)):
69
- return (
70
- isinstance(left, (int, float))
71
- and isinstance(right, (int, float))
72
- and left == right
73
- )
74
- if isinstance(left, list) or isinstance(right, list):
75
- return (
76
- isinstance(left, list)
77
- and isinstance(right, list)
78
- and len(left) == len(right)
79
- and all(_json_schema_equal(a, b) for a, b in zip(left, right))
80
- )
81
- if isinstance(left, dict) or isinstance(right, dict):
82
- return (
83
- isinstance(left, dict)
84
- and isinstance(right, dict)
85
- and left.keys() == right.keys()
86
- and all(_json_schema_equal(left[key], right[key]) for key in left)
87
- )
88
- return type(left) is type(right) and left == right
65
+ def json_schema_number_key(value: int | float) -> str:
66
+ if isinstance(value, float) and value.is_integer():
67
+ value = int(value)
68
+ return str(value)
69
+
70
+
71
+ def _intern_json_schema_value(
72
+ value: Any, identities: dict[tuple[type, Any], int],
73
+ ) -> int:
74
+ pending = [(value, False)]
75
+ completed: list[int] = []
76
+ while pending:
77
+ item, expanded = pending.pop()
78
+ if isinstance(item, (dict, list)):
79
+ if not expanded:
80
+ pending.append((item, True))
81
+ values = tuple(item.values()) if isinstance(item, dict) else item
82
+ pending.extend((child, False) for child in reversed(values))
83
+ continue
84
+ start = len(completed) - len(item)
85
+ children = tuple(completed[start:])
86
+ del completed[start:]
87
+ key = ((dict, frozenset(zip(item, children)))
88
+ if isinstance(item, dict) else (list, children))
89
+ elif isinstance(item, bool):
90
+ key = (bool, item)
91
+ elif isinstance(item, (int, float)):
92
+ key = (int, json_schema_number_key(item))
93
+ else:
94
+ key = (type(item), item)
95
+ completed.append(identities.setdefault(key, len(identities)))
96
+ return completed[0]
89
97
 
90
98
 
91
99
  def _resolve_ref(ref: str, root: dict) -> dict:
@@ -263,12 +271,11 @@ class _Validator:
263
271
  max_items = schema.get("maxItems")
264
272
  if max_items is not None and len(instance) > max_items:
265
273
  self._err(path, f"array length {len(instance)} > maxItems {max_items}")
266
- if schema.get("uniqueItems") is True and any(
267
- _json_schema_equal(item, previous)
268
- for index, item in enumerate(instance)
269
- for previous in instance[:index]
270
- ):
271
- self._err(path, "array items are not unique")
274
+ if schema.get("uniqueItems") is True:
275
+ identities: dict[tuple[type, Any], int] = {}
276
+ if len({_intern_json_schema_value(item, identities)
277
+ for item in instance}) != len(instance):
278
+ self._err(path, "array items are not unique")
272
279
  prefix_items = schema.get("prefixItems") or []
273
280
  for i, item_schema in enumerate(prefix_items[: len(instance)]):
274
281
  self.validate(instance[i], item_schema, path + (i,))
@@ -1,7 +1,9 @@
1
1
  """모델용 고정 텍스트 투영의 scalar 줄 형식을 공유한다."""
2
2
  from __future__ import annotations
3
3
 
4
+ import json
4
5
  import re
6
+ from typing import Callable
5
7
 
6
8
 
7
9
  _CONTROL = re.compile(r"[\x00-\x09\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]")
@@ -34,24 +36,44 @@ def block(text: str) -> str:
34
36
  return _one_line(text)
35
37
 
36
38
 
37
- def line(label: str, value: object) -> str:
38
- """한 scalar를 Markdown 목록 한 줄로 렌더한다."""
39
+ def _line_prefix(label: str) -> str:
39
40
  if not re.fullmatch(r"[A-Za-z][A-Za-z0-9 ()/.-]*", label):
40
41
  raise ValueError("fixed text label must be a static single-line label")
41
- return f"- {label}: `{scalar(value)}`\n"
42
+ return f"- {label}: "
43
+
44
+
45
+ def line(label: str, value: object) -> str:
46
+ """한 scalar를 Markdown 목록 한 줄로 렌더한다."""
47
+ return f"{_line_prefix(label)}`{scalar(value)}`\n"
42
48
 
43
49
 
44
50
  def value_lines(label: str, value: object) -> list[str]:
45
51
  """JSON 모양의 복합 값을 이름/순서/값 고정 줄로 손실 없이 펼친다."""
52
+ return _value_lines(label, value, line)
53
+
54
+
55
+ def _quoted_scalar_line(label: str, value: object) -> str:
56
+ return _line_prefix(label) + json.dumps(value, ensure_ascii=True) + "\n"
57
+
58
+
59
+ def quoted_value_lines(label: str, value: object) -> list[str]:
60
+ return _value_lines(label, value, _quoted_scalar_line)
61
+
62
+
63
+ def _value_lines(
64
+ label: str, value: object, render_line: Callable[[str, object], str],
65
+ ) -> list[str]:
46
66
  if isinstance(value, dict):
47
- rows = [line(f"{label} field count", len(value))]
67
+ rows = [render_line(f"{label} field count", len(value))]
48
68
  for index, (name, child) in enumerate(value.items(), 1):
49
- rows.append(line(f"{label} field {index} name", name))
50
- rows.extend(value_lines(f"{label} field {index} value", child))
69
+ rows.append(render_line(f"{label} field {index} name", name))
70
+ rows.extend(_value_lines(
71
+ f"{label} field {index} value", child, render_line,
72
+ ))
51
73
  return rows
52
74
  if isinstance(value, list):
53
- rows = [line(f"{label} item count", len(value))]
75
+ rows = [render_line(f"{label} item count", len(value))]
54
76
  for index, child in enumerate(value, 1):
55
- rows.extend(value_lines(f"{label} item {index}", child))
77
+ rows.extend(_value_lines(f"{label} item {index}", child, render_line))
56
78
  return rows
57
- return [line(label, value)]
79
+ return [render_line(label, value)]
@@ -31,6 +31,10 @@ from .report_views import (
31
31
  direction_candidate_ineligibility,
32
32
  normalize_direction_selection_identity,
33
33
  )
34
+ from .phases.implementation_option_selection.validation import (
35
+ selection_candidates,
36
+ validate_split_acceptance,
37
+ )
34
38
  from .qa_commands import find_denied_tokens
35
39
  from .user_response import UserResponseError, parse_direction_selection
36
40
 
@@ -302,6 +306,11 @@ def _selected_option(
302
306
  )
303
307
  if option is None:
304
308
  raise DirectionSelectionError("selected option is not a ranked candidate")
309
+ # The gate does not run the option-selection validator, which owns id
310
+ # uniqueness; a repeated id would leave which direction was accepted ambiguous.
311
+ same_id = [row for row in selection_candidates(selection) if row.get("id") == option_id]
312
+ if len(same_id) > 1:
313
+ raise DirectionSelectionError("selected option id names more than one candidate")
305
314
  try:
306
315
  report_option_id, report_option_name = normalize_direction_selection_identity(
307
316
  str(option.get("id") or ""), str(option.get("name") or "")
@@ -326,6 +335,14 @@ def _validate_no_blockers(data: Mapping[str, Any]) -> None:
326
335
  )
327
336
 
328
337
 
338
+ def _validate_split_acceptance(data: Mapping[str, Any]) -> None:
339
+ # `blocking_feasibility_facts` trusts any `splitAcceptance` ref, so the gate
340
+ # re-checks the cited answer before it trusts the candidate's validity.
341
+ errors = validate_split_acceptance(data)
342
+ if errors:
343
+ raise DirectionSelectionError("; ".join(errors))
344
+
345
+
329
346
  def _direction_payload(option: Mapping[str, Any]) -> dict[str, Any]:
330
347
  fields = (
331
348
  "goal",
@@ -387,6 +404,7 @@ def resolve_selected_direction(
387
404
  evidence, option_id, note, constraints = _preselected_selection(selection)
388
405
  else:
389
406
  raise DirectionSelectionError(f"unsupported selection mode: {mode}")
407
+ _validate_split_acceptance(data)
390
408
  option, normalized_option_name = _selected_option(selection, option_id)
391
409
  _validate_no_blockers(data)
392
410
  return SelectedDirection(
@@ -39,8 +39,14 @@ from .worker_prompt_body import (
39
39
  report_writer_prompt_body,
40
40
  )
41
41
  from .worker_prompt_contract import PromptRecord, validate_initial_prompt_records
42
- from .worker_prompt_headers import source_worktree_headers, worker_prompt_headers
43
- from .approved_plan_stage_extract import StageExtractError, materialize_stage_extract
42
+ from .worker_prompt_headers import (
43
+ source_worktree_headers, verification_input_headers, worker_prompt_headers,
44
+ )
45
+ from .approved_plan_stage_extract import (
46
+ StageExtractError,
47
+ load_stage_extract,
48
+ write_stage_extract,
49
+ )
44
50
  from .worker_prompt_policy import (
45
51
  APPROVED_PLAN_HEADER,
46
52
  APPROVED_PLAN_STAGE_EXTRACT_HEADER,
@@ -183,6 +189,7 @@ class _PromptItem:
183
189
  clarification_input: tuple[str, Path] | None = None
184
190
  resources: tuple["_PromptResource", ...] = ()
185
191
  temp_path: Path | None = None
192
+ stage_extract: str = ""
186
193
 
187
194
 
188
195
  @dataclass(frozen=True)
@@ -286,6 +293,9 @@ def implementation_anchor_lines(
286
293
  ) -> list[str]:
287
294
  """이 워커의 프롬프트가 싣는 구현 앵커 줄. 구현 audience 가 아니면 빈 목록.
288
295
 
296
+ For an executor this writes the stage extract its anchor line names, so a
297
+ prompt the lead publishes through this path points at an existing file.
298
+
289
299
  executor 의 mutating cwd, 그리고 executor·verifier 공통의
290
300
  `**Approved plan:**` / `**Stage for this implementation run:**` 이다.
291
301
  `okstra agent-prompt jobs` 는 이 두 헤더를 요구하므로, 리드가 회수 경로로
@@ -293,8 +303,9 @@ def implementation_anchor_lines(
293
303
  dev-10860 stage-3: 리드가 헤더 두 줄을 손으로 지시문에 붙여 통과시켰다).
294
304
  """
295
305
  context = _read_side_context(project_root, run_manifest_path, runtime_root)
306
+ plan = _prompt_plan(context.manifest, worker_id)
296
307
  return _implementation_anchor_lines(
297
- context, _prompt_plan(context.manifest, worker_id)
308
+ context, plan, _write_executor_stage_extract(context, plan)
298
309
  )
299
310
 
300
311
 
@@ -462,6 +473,7 @@ def _resolve_prompt_item(
462
473
  plan=plan,
463
474
  existed=existed,
464
475
  clarification_input=clarification_input,
476
+ stage_extract=_write_executor_stage_extract(context, plan),
465
477
  )
466
478
 
467
479
 
@@ -527,6 +539,7 @@ def _prepare_prompt_item(
527
539
  clarification_input=item.clarification_input,
528
540
  resources=resources,
529
541
  temp_path=temp_path,
542
+ stage_extract=item.stage_extract,
530
543
  )
531
544
 
532
545
 
@@ -542,6 +555,7 @@ def _with_prompt_resources(
542
555
  clarification_input=item.clarification_input,
543
556
  resources=resources,
544
557
  temp_path=item.temp_path,
558
+ stage_extract=item.stage_extract,
545
559
  )
546
560
 
547
561
 
@@ -578,7 +592,9 @@ def _render_prompt_parts(
578
592
  anchors.append(
579
593
  f"**Prompt Delivery Mode:** {context.request.delivery_mode.value}"
580
594
  )
581
- anchors.extend(_implementation_anchor_lines(context, item.plan))
595
+ anchors.extend(
596
+ _implementation_anchor_lines(context, item.plan, item.stage_extract)
597
+ )
582
598
  synthesis_packet_path = _materialize_report_writer_packet(
583
599
  context,
584
600
  item.plan,
@@ -589,6 +605,7 @@ def _render_prompt_parts(
589
605
  worker,
590
606
  item.plan,
591
607
  synthesis_packet_path,
608
+ item.stage_extract,
592
609
  )
593
610
  body.extend(_resource_lines(context, item))
594
611
  except InitialPromptMaterializationError:
@@ -702,6 +719,7 @@ def _prompt_body(
702
719
  worker: InitialPromptWorkerRequest,
703
720
  plan: PromptPlan,
704
721
  synthesis_packet_path: str = "",
722
+ stage_extract_path: str = "",
705
723
  ) -> list[str]:
706
724
  if plan.audience == "report-writer":
707
725
  return report_writer_prompt_body(
@@ -722,11 +740,7 @@ def _prompt_body(
722
740
  plan,
723
741
  _optional_approved_plan_path(context) if plan.include_approved_plan else "",
724
742
  _selected_direction_path(context) if plan.include_selected_direction else "",
725
- (
726
- _approved_plan_stage_extract(context)
727
- if plan.audience == "implementation-executor"
728
- else ""
729
- ),
743
+ stage_extract_path,
730
744
  )
731
745
 
732
746
 
@@ -1434,8 +1448,8 @@ def _anchor_predates_this_contract(
1434
1448
  같은 invocation id 위에 덮어쓰고, 이미 디스패치된 프롬프트는 그 경로가
1435
1449
  감사 기록으로 지켜 준다.
1436
1450
 
1437
- 판정은 지금 렌더가 실을 앵커 한 줄이 기존 본문에 있는지로 한다. 작업
1438
- 트리가 없는 run 은 실을 줄이 없으므로 언제나 최신이다.
1451
+ Recovery checks the current worktree anchor and every frozen verification
1452
+ reference line. Runs without those references keep the earlier contract.
1439
1453
  """
1440
1454
  lines = source_worktree_headers(context.active_context) if context.manifest.get("taskType") != "final-verification" else []
1441
1455
  try:
@@ -1445,6 +1459,10 @@ def _anchor_predates_this_contract(
1445
1459
  # 보존해 보고한다(디렉터리, 깨진 UTF-8). 여기서 재발행으로 덮어 그
1446
1460
  # 진단을 지우지 않는다.
1447
1461
  return False
1462
+ if any(line not in text for line in verification_input_headers(
1463
+ context.project_root, context.manifest,
1464
+ )):
1465
+ return True
1448
1466
  if context.manifest.get("executionIdentityVersion") == 2:
1449
1467
  request = _agent_invocation_request(context, item)
1450
1468
  if request is not None and not invocation_dispatch_ids(request):
@@ -1457,6 +1475,7 @@ def _anchor_predates_this_contract(
1457
1475
  def _implementation_anchor_lines(
1458
1476
  context: _MaterializationContext,
1459
1477
  plan: PromptPlan,
1478
+ stage_extract_path: str,
1460
1479
  ) -> list[str]:
1461
1480
  """소스 작업 트리와 산출물 루트를 구분하고 구현 입력을 덧붙인다."""
1462
1481
  if context.manifest.get("taskType") == "final-verification":
@@ -1473,10 +1492,8 @@ def _implementation_anchor_lines(
1473
1492
  lines.append(
1474
1493
  f"{APPROVED_PLAN_HEADER} {_required_approved_plan_path(context)}"
1475
1494
  )
1476
- if plan.audience == "implementation-executor":
1477
- extract = _approved_plan_stage_extract(context)
1478
- if extract:
1479
- lines.append(f"{APPROVED_PLAN_STAGE_EXTRACT_HEADER} {extract}")
1495
+ if stage_extract_path:
1496
+ lines.append(f"{APPROVED_PLAN_STAGE_EXTRACT_HEADER} {stage_extract_path}")
1480
1497
  lines.append(
1481
1498
  f"{IMPLEMENTATION_STAGE_HEADER} {_required_stage_number(context)}"
1482
1499
  )
@@ -1537,10 +1554,18 @@ def _required_approved_plan_path(context: _MaterializationContext) -> str:
1537
1554
  return str(_resolve_input_path(context.project_root, Path(value)))
1538
1555
 
1539
1556
 
1540
- def _approved_plan_stage_extract(context: _MaterializationContext) -> str:
1557
+ def _write_executor_stage_extract(
1558
+ context: _MaterializationContext, plan: PromptPlan
1559
+ ) -> str:
1560
+ if plan.audience != "implementation-executor":
1561
+ return ""
1562
+ return _write_approved_plan_stage_extract(context)
1563
+
1564
+
1565
+ def _write_approved_plan_stage_extract(context: _MaterializationContext) -> str:
1541
1566
  """Write this run's stage extract of the approved plan; its project path.
1542
1567
 
1543
- Empty when the plan is not a report record (see `materialize_stage_extract`),
1568
+ Empty when the plan is not a report record (see `load_stage_extract`),
1544
1569
  and the executor then reads the plan itself.
1545
1570
  """
1546
1571
  stage = _required_stage_number(context)
@@ -1554,17 +1579,30 @@ def _approved_plan_stage_extract(context: _MaterializationContext) -> str:
1554
1579
  Path(_required_string(context.manifest, "activeRunContextPath")),
1555
1580
  )
1556
1581
  suffix = active_context_path.name.removeprefix("active-run-context-")
1557
- output = active_context_path.with_name(f"approved-plan-stage-{stage}-{suffix}")
1582
+ output = _resolve_owned_artifact_path(
1583
+ context.project_root,
1584
+ active_context_path.with_name(f"approved-plan-stage-{stage}-{suffix}"),
1585
+ "approved plan stage extract path",
1586
+ )
1558
1587
  try:
1559
- written = materialize_stage_extract(
1560
- Path(_required_approved_plan_path(context)), int(stage), output
1588
+ payload = load_stage_extract(
1589
+ Path(_required_approved_plan_path(context)), int(stage)
1561
1590
  )
1562
1591
  except (StageExtractError, JsonBoundaryError) as exc:
1563
1592
  raise InitialPromptMaterializationError(
1564
1593
  "required_input_missing",
1565
1594
  f"cannot project the approved plan onto stage {stage}: {exc}",
1566
1595
  ) from exc
1567
- return _project_relative(context.project_root, output) if written else ""
1596
+ if payload is None:
1597
+ return ""
1598
+ try:
1599
+ write_stage_extract(output, payload)
1600
+ except JsonBoundaryError as exc:
1601
+ raise InitialPromptMaterializationError(
1602
+ "publication_failed",
1603
+ f"cannot write the approved plan stage extract for stage {stage}: {exc}",
1604
+ ) from exc
1605
+ return _project_relative(context.project_root, output)
1568
1606
 
1569
1607
 
1570
1608
  def _optional_approved_plan_path(context: _MaterializationContext) -> str:
@@ -1,11 +1,11 @@
1
1
  """Shared flock + atomic JSON persistence for small okstra registries."""
2
2
  from __future__ import annotations
3
3
 
4
- import contextlib
5
- import fcntl
6
- from collections.abc import Callable, Iterator
4
+ from collections.abc import Callable
7
5
  from pathlib import Path
8
6
 
7
+ from okstra_project.dirs import registry_lock
8
+
9
9
  from .json_boundary import (
10
10
  JsonBoundaryError,
11
11
  load_owned_object,
@@ -13,21 +13,6 @@ from .json_boundary import (
13
13
  )
14
14
 
15
15
 
16
- @contextlib.contextmanager
17
- def registry_lock(lock_path: Path) -> Iterator[None]:
18
- """Hold an exclusive flock on ``lock_path``."""
19
- lock_path.parent.mkdir(parents=True, exist_ok=True)
20
- if not lock_path.exists():
21
- lock_path.touch()
22
- handle = lock_path.open("r+")
23
- try:
24
- fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
25
- yield
26
- finally:
27
- fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
28
- handle.close()
29
-
30
-
31
16
  def load_registry_json(path: Path, default_factory: Callable[[], dict]) -> dict:
32
17
  """Load a registry dict, or a fresh default when absent/corrupt."""
33
18
  try: