okstra 0.227.0 → 0.228.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 (74) 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/duties/code-reviewer.json +1 -0
  10. package/runtime/prompts/lead/convergence.md +5 -19
  11. package/runtime/prompts/lead/okstra-lead-contract.md +1 -1
  12. package/runtime/prompts/profiles/_coding-conventions-preflight.md +1 -1
  13. package/runtime/python/okstra_ctl/adapters/verification_inputs.py +22 -0
  14. package/runtime/python/okstra_ctl/adapters/worker_defaults.py +2 -2
  15. package/runtime/python/okstra_ctl/analysis_packet.py +52 -21
  16. package/runtime/python/okstra_ctl/approval_decisions.py +30 -1
  17. package/runtime/python/okstra_ctl/approved_plan_stage_extract.py +100 -66
  18. package/runtime/python/okstra_ctl/brief_sources.py +162 -44
  19. package/runtime/python/okstra_ctl/code_review_coverage.py +11 -1
  20. package/runtime/python/okstra_ctl/code_review_scope.py +157 -0
  21. package/runtime/python/okstra_ctl/code_review_target.py +46 -10
  22. package/runtime/python/okstra_ctl/conformance.py +9 -3
  23. package/runtime/python/okstra_ctl/design_surfaces.py +51 -19
  24. package/runtime/python/okstra_ctl/final_report_schema.py +37 -30
  25. package/runtime/python/okstra_ctl/fixed_text.py +31 -9
  26. package/runtime/python/okstra_ctl/implementation_direction.py +18 -0
  27. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +59 -21
  28. package/runtime/python/okstra_ctl/json_registry.py +3 -18
  29. package/runtime/python/okstra_ctl/manager_split.py +201 -84
  30. package/runtime/python/okstra_ctl/model_io/references.py +31 -1
  31. package/runtime/python/okstra_ctl/model_io/renderers.py +30 -1
  32. package/runtime/python/okstra_ctl/model_io_cli.py +9 -0
  33. package/runtime/python/okstra_ctl/path_hints.py +13 -1
  34. package/runtime/python/okstra_ctl/paths.py +4 -0
  35. package/runtime/python/okstra_ctl/phases/final_verification/prior_blockers.py +87 -45
  36. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +2 -2
  37. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +10 -2
  38. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +19 -11
  39. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +3 -1
  40. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +3 -1
  41. package/runtime/python/okstra_ctl/phases/implementation/spec.md +14 -0
  42. package/runtime/python/okstra_ctl/phases/implementation_option_selection/authoring.py +2 -1
  43. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  44. package/runtime/python/okstra_ctl/phases/implementation_option_selection/validation.py +53 -37
  45. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  46. package/runtime/python/okstra_ctl/plan_items.py +9 -11
  47. package/runtime/python/okstra_ctl/ports/verification_inputs.py +17 -0
  48. package/runtime/python/okstra_ctl/prior_planning.py +6 -17
  49. package/runtime/python/okstra_ctl/prior_run_summary.py +35 -0
  50. package/runtime/python/okstra_ctl/qa_commands.py +66 -1
  51. package/runtime/python/okstra_ctl/qa_commands_cli.py +67 -0
  52. package/runtime/python/okstra_ctl/qa_procedures.py +235 -0
  53. package/runtime/python/okstra_ctl/registry/verification_inputs_store.py +8 -0
  54. package/runtime/python/okstra_ctl/render.py +10 -0
  55. package/runtime/python/okstra_ctl/report_assembly.py +12 -12
  56. package/runtime/python/okstra_ctl/run.py +108 -5
  57. package/runtime/python/okstra_ctl/verification_input_ref.py +80 -0
  58. package/runtime/python/okstra_ctl/verification_input_types.py +32 -0
  59. package/runtime/python/okstra_ctl/verification_inputs.py +162 -0
  60. package/runtime/python/okstra_ctl/verification_plan.py +116 -0
  61. package/runtime/python/okstra_ctl/worker_prompt_body.py +12 -6
  62. package/runtime/python/okstra_ctl/worker_prompt_contract.py +5 -1
  63. package/runtime/python/okstra_ctl/worker_prompt_headers.py +50 -1
  64. package/runtime/python/okstra_project/dirs.py +22 -0
  65. package/runtime/python/okstra_project/resolver.py +10 -0
  66. package/runtime/schemas/final-report-v3.0.schema.json +5 -1
  67. package/runtime/skills/okstra-brief-gen/SKILL.md +10 -4
  68. package/runtime/skills/okstra-code-review/SKILL.md +39 -45
  69. package/runtime/skills/okstra-code-review/references/census-rules.md +14 -2
  70. package/runtime/skills/okstra-code-review/references/review-calibration.md +31 -8
  71. package/runtime/skills/okstra-manager/SKILL.md +2 -2
  72. package/runtime/skills/okstra-setup/SKILL.md +2 -0
  73. package/runtime/skills/okstra-setup/references/project-config.md +2 -0
  74. package/runtime/validators/validate-brief.py +21 -5
@@ -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:
@@ -12,13 +12,21 @@ from __future__ import annotations
12
12
  import importlib.util
13
13
  import re
14
14
  import tempfile
15
+ from collections.abc import Mapping, Sequence
16
+ from itertools import permutations
15
17
  from pathlib import Path
16
18
  from types import ModuleType
19
+ from typing import Any, TypedDict
17
20
 
18
21
  from okstra_ctl.json_boundary import JsonBoundaryError, load_owned_object
19
22
  from okstra_ctl.jsonl import append_jsonl
20
23
 
21
- from .analysis_packet import BY_REFERENCE_FORMAT, _fence_mask
24
+ from .analysis_packet import _fence_mask, project_relative_ref
25
+ from .brief_sources import (
26
+ TOO_LARGE_REASON,
27
+ by_reference_source_entry,
28
+ too_large_to_cite,
29
+ )
22
30
  from .ids import slugify_task_segment
23
31
  from .manager_paths import children_json_path, events_jsonl_path, split_plan_path, task_manifest_path
24
32
  from .manager_store import (
@@ -38,6 +46,7 @@ RECOMMENDED_PHASES = ("requirements-discovery", "error-analysis", "improvement-d
38
46
  DEFAULT_PHASE = "requirements-discovery"
39
47
  GENERATOR = "okstra-manager"
40
48
  SOURCE_TYPE = "linear"
49
+ SPLIT_FETCHED_VIA = "okstra manager task split"
41
50
  # 브리프 계약의 필수 서술 필드. 비어 있으면 검증기가 거절하므로 계획 단계에서 먼저 막는다.
42
51
  _REQUIRED_TEXT_FIELDS = ("context", "problem", "desiredOutcome")
43
52
  _LIST_FIELDS = (
@@ -59,6 +68,34 @@ _NONE = "_(none)_"
59
68
  _CREATED = re.compile(r"^created: (\d{4}-\d{2}-\d{2})$", re.M)
60
69
  # 다른 이슈나 같은 이슈의 다른 프로젝트가 늘 때 바뀌는 생성 절. 기존 브리프에서는 이 절의 바뀐 줄만 고친다.
61
70
  _REFRESHED_SECTIONS = ("### Out of scope", "## Related Artifacts", "## Related Task Graph")
71
+ _OUTSIDE_REFRESHED = (
72
+ "this plan changes it outside the Out of scope, Related Artifacts and "
73
+ "Related Task Graph sections"
74
+ )
75
+
76
+
77
+ class _SplitInputs(TypedDict):
78
+ issue: dict
79
+ assignment: dict
80
+ stem: str
81
+ taskKey: str
82
+ projectId: str
83
+ childTaskId: str
84
+ projectRoot: str
85
+ briefPath: Path
86
+ localSources: list[str]
87
+ graph: list[tuple[str, ...]]
88
+ siblings: list[tuple[str, dict, Path]]
89
+
90
+
91
+ # `total=False` instead of `NotRequired`, which Python 3.10 (the package minimum) lacks.
92
+ class SplitItem(_SplitInputs, total=False):
93
+ """One (issue, project) pair of a split plan and the brief rendered for it."""
94
+
95
+ current: str | None
96
+ text: str
97
+ base: str | None
98
+ briefStatus: str
62
99
 
63
100
 
64
101
  def brief_file_title(title: str) -> str:
@@ -251,36 +288,26 @@ def _source_block(index: int, ref: str, fetched_via: str, fetched_at: str, body:
251
288
  ]
252
289
 
253
290
 
254
- def _local_source_block(index: int, ref: str, fetched_at: str) -> list[str]:
255
- return [
256
- f"### Source {index} — file",
257
- "",
258
- f"- ref: {ref}",
259
- "- fetched-via: okstra manager task split",
260
- f"- fetched-at: {fetched_at}",
261
- f"- format: {BY_REFERENCE_FORMAT}",
262
- "",
263
- "```",
264
- "```",
265
- "",
266
- ]
267
-
268
-
269
291
  def _local_source_refs(assignment: dict, project_root: Path, where: str, errors: list[str]) -> list[str]:
270
292
  """계획의 `localSources` 를 프로젝트 루트 기준 상대 경로로 바꾼다. 루트 밖이나 없는 파일은 거절한다."""
271
293
  root = project_root.resolve()
272
294
  refs: list[str] = []
273
295
  for index, raw in enumerate(assignment["localSources"], 1):
274
- candidate = Path(raw).expanduser()
275
- path = (candidate if candidate.is_absolute() else root / candidate).resolve()
276
- try:
277
- relative = path.relative_to(root).as_posix()
278
- except ValueError:
279
- errors.append(f"{where}.localSources[{index}] {raw!r} is outside project root {str(root)!r}")
296
+ relative = project_relative_ref(raw, root)
297
+ if relative is None:
298
+ errors.append(
299
+ f"{where}.localSources[{index}] {raw!r} does not resolve under project "
300
+ f"root {str(root)!r}"
301
+ )
280
302
  continue
281
- if not path.is_file():
303
+ if not (root / relative).is_file():
282
304
  errors.append(f"{where}.localSources[{index}] {raw!r} is not a file under {str(root)!r}")
283
305
  continue
306
+ if too_large_to_cite(root, relative):
307
+ errors.append(
308
+ f"{where}.localSources[{index}] {raw!r} is {TOO_LARGE_REASON}"
309
+ )
310
+ continue
284
311
  refs.append(relative)
285
312
  return list(dict.fromkeys(refs))
286
313
 
@@ -365,7 +392,7 @@ def _render_brief(
365
392
  first_local = 2 if _source_is_issue(source, issue) else 3
366
393
  for index, ref in enumerate(local_sources, first_local):
367
394
  # 같은 계획을 다시 돌려도 브리프가 같도록 날짜만 쓴다.
368
- lines.extend(_local_source_block(index, ref, created))
395
+ lines.extend(by_reference_source_entry(index, ref, SPLIT_FETCHED_VIA, created))
369
396
  lines.extend(
370
397
  [
371
398
  "## Context",
@@ -421,7 +448,9 @@ def _render_brief(
421
448
  return "\n".join(lines)
422
449
 
423
450
 
424
- def _validate_rendered(items: list[dict], validator: ModuleType, group_segment: str) -> list[str]:
451
+ def _validate_rendered(
452
+ items: Sequence[Mapping[str, Any]], validator: ModuleType, group_segment: str,
453
+ ) -> list[str]:
425
454
  errors: list[str] = []
426
455
  with tempfile.TemporaryDirectory(prefix="okstra-split-") as scratch:
427
456
  for index, item in enumerate(items):
@@ -440,10 +469,10 @@ def _validate_rendered(items: list[dict], validator: ModuleType, group_segment:
440
469
 
441
470
  def _plan_items(
442
471
  projects: dict, task_group: str, group_segment: str, source: dict, issues: list[dict], validator: ModuleType,
443
- ) -> tuple[list[dict], list[str]]:
472
+ ) -> tuple[list[SplitItem], list[str]]:
444
473
  """(이슈, 프로젝트) 쌍마다 렌더링 입력을 만든다. 본문은 `created` 가 정해진 뒤 `_render_item` 이 쓴다."""
445
474
  keys: dict[tuple[str, str], str] = {}
446
- items: list[dict] = []
475
+ items: list[SplitItem] = []
447
476
  for issue in issues:
448
477
  ticket = issue["ticketId"]
449
478
  stem = "-".join(part for part in (ticket, brief_file_title(issue["title"])) if part)
@@ -453,9 +482,11 @@ def _plan_items(
453
482
  key = f"{project_id}:{task_group}:{child_task_id}"
454
483
  keys[(ticket, project_id)] = key
455
484
  root = Path(str(projects[project_id].get("projectRoot") or ""))
485
+ brief_dir = root / ".okstra" / "briefs" / group_segment
456
486
  items.append({"issue": issue, "assignment": assignment, "stem": stem, "taskKey": key,
457
487
  "projectId": project_id, "childTaskId": child_task_id, "projectRoot": str(root),
458
- "briefPath": root / ".okstra" / "briefs" / group_segment / f"{stem}.md"})
488
+ "briefPath": brief_dir / f"{stem}.md",
489
+ "localSources": [], "graph": [], "siblings": []})
459
490
  errors: list[str] = []
460
491
  for item in items:
461
492
  item["localSources"] = _local_source_refs(item["assignment"], Path(item["projectRoot"]),
@@ -468,7 +499,9 @@ def _plan_items(
468
499
  return items, errors
469
500
 
470
501
 
471
- def _render_item(item: dict, source: dict, task_group: str, manager_task: str, created: str) -> str:
502
+ def _render_item(
503
+ item: SplitItem, source: dict, task_group: str, manager_task: str, created: str,
504
+ ) -> str:
472
505
  return _render_brief(source=source, issue=item["issue"], assignment=item["assignment"],
473
506
  task_group=task_group, manager_task=manager_task,
474
507
  child_task_id=item["childTaskId"], stem=item["stem"],
@@ -479,18 +512,22 @@ def _render_item(item: dict, source: dict, task_group: str, manager_task: str, c
479
512
  def _previous_items(
480
513
  home: Path, manager_id: str, task_group: str, task_id: str, projects: dict, group_segment: str,
481
514
  validator: ModuleType,
482
- ) -> tuple[dict, dict]:
483
- """지난 분할이 남긴 계획의 렌더링 입력을 브리프 경로별로 돌려준다. 지금 프로젝트 목록으로 검증되지 않으면 비운다."""
515
+ ) -> tuple[dict[Path, SplitItem], dict, str]:
516
+ """The kept plan's items by brief path, its source, and why none can be compared.
517
+
518
+ The reason is empty when the kept plan exists and validates against the projects.
519
+ """
484
520
  path = split_plan_path(home, manager_id, task_group, task_id)
485
521
  if not path.is_file():
486
- return {}, {}
522
+ return {}, {}, "there is no kept split plan to compare it with"
487
523
  source, issues, errors = normalize_plan(_load_plan(path), set(projects), set(validator.TASK_RELATIONS))
524
+ if not errors:
525
+ items, errors = _plan_items(
526
+ projects, task_group, group_segment, source, issues, validator,
527
+ )
488
528
  if errors:
489
- return {}, {}
490
- items, errors = _plan_items(projects, task_group, group_segment, source, issues, validator)
491
- if errors:
492
- return {}, {}
493
- return {item["briefPath"]: item for item in items}, source
529
+ return {}, {}, "the kept split plan no longer validates: " + "; ".join(errors)
530
+ return {item["briefPath"]: item for item in items}, source, ""
494
531
 
495
532
 
496
533
  def _existing_created(text: str) -> str:
@@ -502,13 +539,26 @@ def _section_spans(lines: list[str]) -> dict[str, tuple[int, int]]:
502
539
  """펜스 밖 제목 줄마다 본문 범위 (시작, 끝). Source Material 본문 속 `#` 줄은 제목이 아니다."""
503
540
  headings = [index for index, (line, fenced) in enumerate(zip(lines, _fence_mask(lines)))
504
541
  if not fenced and line.startswith("#")]
542
+ # A hand-added subheading stays inside its section, as validate-brief reads it:
543
+ # a heading closes every open heading of the same or a deeper level.
544
+ ends: dict[int, int] = {}
545
+ open_headings: list[tuple[int, int]] = []
546
+ for start in headings:
547
+ level = _heading_level(lines[start])
548
+ while open_headings and open_headings[-1][1] >= level:
549
+ ends[open_headings.pop()[0]] = start
550
+ open_headings.append((start, level))
551
+ ends.update((start, len(lines)) for start, _ in open_headings)
505
552
  spans: dict[str, tuple[int, int]] = {}
506
- for position, start in enumerate(headings):
507
- end = headings[position + 1] if position + 1 < len(headings) else len(lines)
508
- spans.setdefault(lines[start], (start + 1, end))
553
+ for start in headings:
554
+ spans.setdefault(lines[start], (start + 1, ends[start]))
509
555
  return spans
510
556
 
511
557
 
558
+ def _heading_level(line: str) -> int:
559
+ return len(line) - len(line.lstrip("#"))
560
+
561
+
512
562
  def _outside_refreshed(lines: list[str], spans: dict[str, tuple[int, int]]) -> list[str]:
513
563
  kept = list(lines)
514
564
  for start, end in sorted((spans[heading] for heading in _REFRESHED_SECTIONS), reverse=True):
@@ -519,7 +569,8 @@ def _outside_refreshed(lines: list[str], spans: dict[str, tuple[int, int]]) -> l
519
569
  def _merge_section(ours: list[str], base: list[str], new: list[str]) -> list[str]:
520
570
  """지난 렌더링에서 이번 렌더링으로 바뀐 줄만 기존 절에 반영한다. 손으로 더한 줄은 남는다."""
521
571
  removed = set(base) - set(new)
522
- added = [line for line in new if line.strip() and line not in base]
572
+ added = [line for line in new
573
+ if line.strip() and line not in base and line not in ours]
523
574
  merged = [line for line in ours if not (line.strip() and line in removed)]
524
575
  if any(line != _NONE for line in added):
525
576
  merged = [line for line in merged if line != _NONE]
@@ -532,20 +583,117 @@ def _merge_section(ours: list[str], base: list[str], new: list[str]) -> list[str
532
583
  return merged
533
584
 
534
585
 
535
- def _refresh(current: str, base: str, new: str) -> str | None:
536
- """`base` 와 `new` 가 생성 갱신 절에서만 다르면 그 차이를 `current` 에 반영한 본문, 아니면 None."""
586
+ def _nested_refreshed_reason(spans: dict[str, tuple[int, int]]) -> str:
587
+ """Why a refreshed heading lies inside another refreshed section, or ""."""
588
+ # Merging an outer section would discard the merge already applied to a nested one.
589
+ for outer, inner in permutations(_REFRESHED_SECTIONS, 2):
590
+ start, end = spans[outer]
591
+ inner_heading_line = spans[inner][0] - 1
592
+ if start <= inner_heading_line < end:
593
+ return f"`{inner}` is inside `{outer}`"
594
+ return ""
595
+
596
+
597
+ def _refresh(current: str, base: str, new: str) -> tuple[str | None, str]:
598
+ """`current` with the changes from `base` to `new` applied, or None and why not.
599
+
600
+ Only a difference confined to `_REFRESHED_SECTIONS` can be applied.
601
+ """
537
602
  ours, old, fresh = current.split("\n"), base.split("\n"), new.split("\n")
538
603
  ours_spans, old_spans, fresh_spans = _section_spans(ours), _section_spans(old), _section_spans(fresh)
539
- if any(heading not in spans for spans in (ours_spans, old_spans, fresh_spans) for heading in _REFRESHED_SECTIONS):
540
- return None
604
+ missing = [heading for heading in _REFRESHED_SECTIONS if heading not in ours_spans]
605
+ if missing:
606
+ names = ", ".join(f"`{heading}`" for heading in missing)
607
+ return None, f"it has no {names} heading to refresh"
608
+ nested_reason = _nested_refreshed_reason(ours_spans)
609
+ if nested_reason:
610
+ return None, nested_reason
541
611
  if _outside_refreshed(old, old_spans) != _outside_refreshed(fresh, fresh_spans):
542
- return None
612
+ return None, _OUTSIDE_REFRESHED
543
613
  result = list(ours)
544
614
  for heading in sorted(_REFRESHED_SECTIONS, key=lambda heading: ours_spans[heading][0], reverse=True):
545
615
  start, end = ours_spans[heading]
546
616
  result[start:end] = _merge_section(ours[start:end], old[slice(*old_spans[heading])],
547
617
  fresh[slice(*fresh_spans[heading])])
548
- return "\n".join(result)
618
+ return "\n".join(result), ""
619
+
620
+
621
+ def _brief_status(item: SplitItem, previous_reason: str) -> tuple[str, str, str]:
622
+ """The brief status, the text to write, and why an `overwritten` one was not merged.
623
+
624
+ The text is the merged brief for `refreshed` and the new rendering otherwise.
625
+ """
626
+ current, base, text = item["current"], item["base"], item["text"]
627
+ if current is None:
628
+ return "created", text, ""
629
+ if current == text or base == text:
630
+ return "unchanged", text, ""
631
+ if base is None:
632
+ reason = previous_reason or "the kept split plan does not list this brief"
633
+ return "overwritten", text, reason
634
+ refreshed, reason = _refresh(current, base, text)
635
+ if refreshed == current:
636
+ return "unchanged", text, ""
637
+ if refreshed is None:
638
+ return "overwritten", text, reason
639
+ return "refreshed", refreshed, ""
640
+
641
+
642
+ def _settle_statuses(
643
+ items: list[SplitItem],
644
+ previous_reason: str,
645
+ overwrite: bool,
646
+ validator: ModuleType,
647
+ group_segment: str,
648
+ ) -> None:
649
+ """Set each item's `briefStatus` and the `text` to write.
650
+
651
+ Raises on unresolved conflicts and on refreshed briefs that fail validation.
652
+ """
653
+ conflicts = []
654
+ for item in items:
655
+ item["briefStatus"], item["text"], reason = _brief_status(item, previous_reason)
656
+ if reason:
657
+ conflicts.append(f"{item['briefPath']}: {reason}")
658
+ if conflicts and not overwrite:
659
+ raise ManagerError(
660
+ "briefs already exist with content this plan would change; "
661
+ "pass --overwrite to replace them:\n- " + "\n- ".join(conflicts)
662
+ )
663
+ refreshed_items = [item for item in items if item["briefStatus"] == "refreshed"]
664
+ errors = _validate_rendered(refreshed_items, validator, group_segment)
665
+ if errors:
666
+ raise ManagerError(
667
+ "refreshed briefs failed validate-brief:\n- " + "\n- ".join(errors)
668
+ )
669
+
670
+
671
+ def _register_children(
672
+ home: Path,
673
+ manager_id: str,
674
+ task_group: str,
675
+ task_id: str,
676
+ items: list[SplitItem],
677
+ title: str,
678
+ when: str,
679
+ ) -> None:
680
+ existing = task_manifest_path(home, manager_id, task_group, task_id).is_file()
681
+ members = [{"projectId": item["projectId"], "taskId": item["childTaskId"]}
682
+ for item in items]
683
+ create_task(home, manager_id, task_group, task_id, members,
684
+ objective="" if existing else title, now=when)
685
+ children_path = children_json_path(home, manager_id, task_group, task_id)
686
+ children = _read_json(children_path)
687
+ by_key = {child.get("taskKey"): child for child in children.get("children", [])
688
+ if isinstance(child, dict)}
689
+ for item in items:
690
+ by_key[item["taskKey"]].update({
691
+ "ticketId": item["issue"]["ticketId"],
692
+ "briefPath": str(item["briefPath"]),
693
+ "scope": list(item["assignment"]["scope"]),
694
+ "recommendedPhase": item["assignment"]["recommendedPhase"],
695
+ })
696
+ _write_json(children_path, children)
549
697
 
550
698
 
551
699
  def split_task(
@@ -574,8 +722,9 @@ def split_task(
574
722
  items, errors = _plan_items(projects, task_group, group_segment, source, issues, validator)
575
723
  if errors:
576
724
  raise ManagerError("split plan rejected:\n- " + "\n- ".join(errors))
577
- previous, previous_source = _previous_items(home, manager_id, task_group, task_id, projects, group_segment,
578
- validator)
725
+ previous, previous_source, previous_reason = _previous_items(
726
+ home, manager_id, task_group, task_id, projects, group_segment, validator,
727
+ )
579
728
  for item in items:
580
729
  path = item["briefPath"]
581
730
  item["current"] = path.read_text(encoding="utf-8") if path.is_file() else None
@@ -587,45 +736,13 @@ def split_task(
587
736
  errors = _validate_rendered(items, validator, group_segment)
588
737
  if errors:
589
738
  raise ManagerError("rendered briefs failed validate-brief:\n- " + "\n- ".join(errors))
590
- for item in items:
591
- current, base = item["current"], item["base"]
592
- refreshed = _refresh(current, base, item["text"]) if current is not None and base is not None else None
593
- if current is None:
594
- item["briefStatus"] = "created"
595
- elif current == item["text"] or base == item["text"] or refreshed == current:
596
- item["briefStatus"] = "unchanged"
597
- elif refreshed is not None:
598
- item["briefStatus"] = "refreshed"
599
- item["text"] = refreshed
600
- else:
601
- item["briefStatus"] = "overwritten"
602
- conflicts = [str(item["briefPath"]) for item in items if item["briefStatus"] == "overwritten"]
603
- if conflicts and not overwrite:
604
- raise ManagerError(
605
- "briefs already exist with content this plan would change outside the Related Task Graph, "
606
- "Out of scope and Related Artifacts sections; pass --overwrite to replace them:\n- "
607
- + "\n- ".join(conflicts)
608
- )
609
- errors = _validate_rendered([item for item in items if item["briefStatus"] == "refreshed"], validator,
610
- group_segment)
611
- if errors:
612
- raise ManagerError("refreshed briefs failed validate-brief:\n- " + "\n- ".join(errors))
739
+ _settle_statuses(items, previous_reason, overwrite, validator, group_segment)
613
740
  for item in items:
614
741
  if item["briefStatus"] != "unchanged":
615
742
  item["briefPath"].parent.mkdir(parents=True, exist_ok=True)
616
743
  item["briefPath"].write_text(item["text"], encoding="utf-8")
617
- existing = task_manifest_path(home, manager_id, task_group, task_id).is_file()
618
- create_task(home, manager_id, task_group, task_id,
619
- [{"projectId": item["projectId"], "taskId": item["childTaskId"]} for item in items],
620
- objective="" if existing else source["title"], now=when)
621
- children_path = children_json_path(home, manager_id, task_group, task_id)
622
- children = _read_json(children_path)
623
- by_key = {child.get("taskKey"): child for child in children.get("children", []) if isinstance(child, dict)}
624
- for item in items:
625
- by_key[item["taskKey"]].update({"ticketId": item["issue"]["ticketId"], "briefPath": str(item["briefPath"]),
626
- "scope": list(item["assignment"]["scope"]),
627
- "recommendedPhase": item["assignment"]["recommendedPhase"]})
628
- _write_json(children_path, children)
744
+ _register_children(home, manager_id, task_group, task_id, items, source["title"],
745
+ when)
629
746
  _write_json(split_plan_path(home, manager_id, task_group, task_id), plan)
630
747
  briefs = [{"taskKey": item["taskKey"], "projectId": item["projectId"], "ticketId": item["issue"]["ticketId"],
631
748
  "briefPath": str(item["briefPath"]), "briefStatus": item["briefStatus"]} for item in items]