okstra 0.226.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 (103) hide show
  1. package/README.md +2 -1
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/execute/wizard.mjs +12 -15
  5. package/dist/commands/execute/wizard.mjs.map +1 -1
  6. package/docs/architecture/storage-model.md +77 -0
  7. package/docs/cli.md +43 -7
  8. package/docs/project-structure-overview.md +13 -3
  9. package/package.json +1 -1
  10. package/runtime/BUILD.json +2 -2
  11. package/runtime/agents/operations/code-review.json +1 -1
  12. package/runtime/prompts/duties/code-reviewer.json +1 -0
  13. package/runtime/prompts/lead/convergence.md +5 -19
  14. package/runtime/prompts/lead/okstra-lead-contract.md +2 -2
  15. package/runtime/prompts/profiles/_coding-conventions-preflight.md +1 -1
  16. package/runtime/prompts/wizard/prompts.ko.json +44 -0
  17. package/runtime/python/okstra_ctl/adapters/verification_inputs.py +22 -0
  18. package/runtime/python/okstra_ctl/adapters/worker_defaults.py +63 -0
  19. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +3 -0
  20. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +5 -0
  21. package/runtime/python/okstra_ctl/analysis_packet.py +52 -21
  22. package/runtime/python/okstra_ctl/approval_decisions.py +30 -1
  23. package/runtime/python/okstra_ctl/approved_plan_stage_extract.py +100 -66
  24. package/runtime/python/okstra_ctl/brief_sources.py +162 -44
  25. package/runtime/python/okstra_ctl/code_review_coverage.py +81 -19
  26. package/runtime/python/okstra_ctl/code_review_scope.py +157 -0
  27. package/runtime/python/okstra_ctl/code_review_target.py +115 -55
  28. package/runtime/python/okstra_ctl/conformance.py +9 -3
  29. package/runtime/python/okstra_ctl/correction_cli.py +6 -5
  30. package/runtime/python/okstra_ctl/correction_round.py +1 -1
  31. package/runtime/python/okstra_ctl/design_surfaces.py +51 -19
  32. package/runtime/python/okstra_ctl/domain/worker_defaults.py +106 -0
  33. package/runtime/python/okstra_ctl/file_size_cap.py +56 -6
  34. package/runtime/python/okstra_ctl/final_report_schema.py +37 -30
  35. package/runtime/python/okstra_ctl/fixed_text.py +31 -9
  36. package/runtime/python/okstra_ctl/implementation_direction.py +18 -0
  37. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +59 -21
  38. package/runtime/python/okstra_ctl/json_registry.py +3 -18
  39. package/runtime/python/okstra_ctl/manager_split.py +201 -84
  40. package/runtime/python/okstra_ctl/model_io/references.py +31 -1
  41. package/runtime/python/okstra_ctl/model_io/renderers.py +30 -1
  42. package/runtime/python/okstra_ctl/model_io_cli.py +9 -0
  43. package/runtime/python/okstra_ctl/path_hints.py +13 -1
  44. package/runtime/python/okstra_ctl/paths.py +4 -0
  45. package/runtime/python/okstra_ctl/phases/final_verification/prior_blockers.py +87 -45
  46. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +2 -2
  47. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +10 -2
  48. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +19 -11
  49. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +2 -2
  50. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +4 -2
  51. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +1 -1
  52. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +5 -3
  53. package/runtime/python/okstra_ctl/phases/implementation/spec.md +14 -0
  54. package/runtime/python/okstra_ctl/phases/implementation_option_selection/authoring.py +2 -1
  55. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  56. package/runtime/python/okstra_ctl/phases/implementation_option_selection/validation.py +53 -37
  57. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +22 -0
  58. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +1 -1
  59. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  60. package/runtime/python/okstra_ctl/plan_items.py +9 -11
  61. package/runtime/python/okstra_ctl/ports/verification_inputs.py +17 -0
  62. package/runtime/python/okstra_ctl/ports/worker_defaults.py +25 -0
  63. package/runtime/python/okstra_ctl/prior_planning.py +6 -17
  64. package/runtime/python/okstra_ctl/prior_run_summary.py +35 -0
  65. package/runtime/python/okstra_ctl/qa_commands.py +66 -1
  66. package/runtime/python/okstra_ctl/qa_commands_cli.py +67 -0
  67. package/runtime/python/okstra_ctl/qa_procedures.py +235 -0
  68. package/runtime/python/okstra_ctl/registry/verification_inputs_store.py +8 -0
  69. package/runtime/python/okstra_ctl/registry/worker_defaults_store.py +8 -0
  70. package/runtime/python/okstra_ctl/render.py +10 -0
  71. package/runtime/python/okstra_ctl/report_assembly.py +12 -12
  72. package/runtime/python/okstra_ctl/run.py +123 -6
  73. package/runtime/python/okstra_ctl/stage_done.py +5 -4
  74. package/runtime/python/okstra_ctl/verification_input_ref.py +80 -0
  75. package/runtime/python/okstra_ctl/verification_input_types.py +32 -0
  76. package/runtime/python/okstra_ctl/verification_inputs.py +162 -0
  77. package/runtime/python/okstra_ctl/verification_plan.py +116 -0
  78. package/runtime/python/okstra_ctl/wizard/cli.py +16 -4
  79. package/runtime/python/okstra_ctl/wizard/confirmation.py +21 -0
  80. package/runtime/python/okstra_ctl/wizard/engine.py +25 -3
  81. package/runtime/python/okstra_ctl/wizard/ids.py +23 -0
  82. package/runtime/python/okstra_ctl/wizard/render.py +2 -2
  83. package/runtime/python/okstra_ctl/wizard/roles.py +73 -23
  84. package/runtime/python/okstra_ctl/wizard/state.py +55 -14
  85. package/runtime/python/okstra_ctl/wizard/steps_roles.py +5 -3
  86. package/runtime/python/okstra_ctl/wizard/worker_settings.py +334 -0
  87. package/runtime/python/okstra_ctl/worker_defaults.py +135 -0
  88. package/runtime/python/okstra_ctl/worker_prompt_body.py +12 -6
  89. package/runtime/python/okstra_ctl/worker_prompt_contract.py +5 -1
  90. package/runtime/python/okstra_ctl/worker_prompt_headers.py +50 -1
  91. package/runtime/python/okstra_ctl/write_policy.py +33 -18
  92. package/runtime/python/okstra_project/dirs.py +22 -0
  93. package/runtime/python/okstra_project/resolver.py +10 -0
  94. package/runtime/schemas/final-report-v3.0.schema.json +5 -1
  95. package/runtime/skills/okstra-brief-gen/SKILL.md +10 -4
  96. package/runtime/skills/okstra-code-review/SKILL.md +59 -63
  97. package/runtime/skills/okstra-code-review/references/census-rules.md +14 -2
  98. package/runtime/skills/okstra-code-review/references/review-calibration.md +32 -9
  99. package/runtime/skills/okstra-manager/SKILL.md +2 -2
  100. package/runtime/skills/okstra-run/SKILL.md +21 -1
  101. package/runtime/skills/okstra-setup/SKILL.md +2 -0
  102. package/runtime/skills/okstra-setup/references/project-config.md +2 -0
  103. package/runtime/validators/validate-brief.py +21 -5
@@ -56,9 +56,15 @@ def normalize_conformance_script(
56
56
  호출부가 있다.
57
57
  """
58
58
  prefix = "<task_root>/"
59
- value = script[len(prefix):] if script.startswith(prefix) else script
60
- while value.startswith("./"):
61
- value = value[2:]
59
+ start = 0
60
+ while True:
61
+ if script.startswith(prefix, start):
62
+ start += len(prefix)
63
+ elif script.startswith("./", start):
64
+ start += 2
65
+ else:
66
+ break
67
+ value = script[start:]
62
68
  if task_root is not None and value.startswith(".okstra/"):
63
69
  for parent in task_root.resolve().parents:
64
70
  if parent.name == ".okstra" and task_root.resolve().is_relative_to(
@@ -21,12 +21,13 @@ _CLI_EPILOG = r"""Usage:
21
21
  Findings are read from the convergence record that preceded the round: the run's
22
22
  initial one for round 1, round N-1's re-convergence (`convergence-correction-r<N-1>-…`)
23
23
  for round N; --stage-base adds the file-size
24
- findings of `<stage-base>..<base>` (the 400-line limit only). Exit 1 on a refusal.
24
+ findings of `<stage-base>..<base>` (the 500-line limit only). Exit 1 on a refusal.
25
25
 
26
- `file-size` prints one `FILE-SIZE:<path>:401` line per file the stage diff leaves over
27
- the 400-line limit (blocking) and one `FILE-SIZE-ADVISORY:<path>:301` line per file it
28
- leaves over only the 300-line target, then `QA-RESULT: PASS|FAIL`; only a limit line
29
- fails. Exit 1 on FAIL, 2 when git cannot read the range.
26
+ `file-size` prints one `FILE-SIZE:<path>:501` line per file the stage diff adds over the
27
+ 500-line limit or takes past it (blocking) and one `FILE-SIZE-ADVISORY:<path>:301` line per
28
+ file it adds over, takes past or grows over the 300-line target without such a limit
29
+ breach, a file already over 500 at the stage base included, then `QA-RESULT: PASS|FAIL`;
30
+ only a limit line fails. Exit 1 on FAIL, 2 when git cannot read the range.
30
31
  """
31
32
 
32
33
 
@@ -177,7 +177,7 @@ def correction_instruction(
177
177
  if not finding_ids and not size_violations:
178
178
  raise CorrectionRoundError(
179
179
  "name at least one --finding, or pass --stage-base for a stage whose diff "
180
- "breaks the 400-line file-size limit"
180
+ f"breaks the {FILE_LINE_LIMIT}-line file-size limit"
181
181
  )
182
182
  if not base.strip():
183
183
  raise CorrectionRoundError("--base is required: the stage HEAD before this round")
@@ -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
@@ -0,0 +1,106 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from collections.abc import Set as AbstractSet
5
+ from dataclasses import dataclass
6
+ from typing import Literal, TypedDict
7
+
8
+ WorkerScope = Literal["global", "project"]
9
+ WorkerDefaultScopes = TypedDict(
10
+ "WorkerDefaultScopes",
11
+ {"global": dict[str, object], "project": dict[str, object]},
12
+ total=False,
13
+ )
14
+ WorkerDefaultUpdates = dict[str, list[str] | None]
15
+
16
+
17
+ class WorkerDefaultError(ValueError):
18
+ pass
19
+
20
+
21
+ class WorkerDefaultsConflict(WorkerDefaultError):
22
+ def __init__(self, role: str) -> None:
23
+ self.role = role
24
+ super().__init__(f"worker defaults changed during editing: {role}")
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class WorkerDefault:
29
+ models: tuple[str, ...]
30
+ scope: WorkerScope
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class WorkerCountRange:
35
+ minimum: int
36
+ maximum: int
37
+ recommended: int
38
+
39
+
40
+ def intersect_worker_count_ranges(
41
+ previous: WorkerCountRange,
42
+ current: WorkerCountRange,
43
+ ) -> WorkerCountRange:
44
+ minimum = max(previous.minimum, current.minimum)
45
+ maximum = min(previous.maximum, current.maximum)
46
+ return WorkerCountRange(
47
+ minimum,
48
+ maximum,
49
+ max(minimum, min(maximum, current.recommended)),
50
+ )
51
+
52
+
53
+ def role_uses_worker_defaults(
54
+ role: str, dynamic: bool, explicit: AbstractSet[str]
55
+ ) -> bool:
56
+ return not dynamic and role != "leader" and role not in explicit
57
+
58
+
59
+ def merge_worker_default_updates(
60
+ current: Mapping[str, object],
61
+ before: Mapping[str, object],
62
+ updates: WorkerDefaultUpdates,
63
+ ) -> dict[str, object]:
64
+ values = dict(current)
65
+ missing = object()
66
+ for role, models in updates.items():
67
+ if values.get(role, missing) != before.get(role, missing):
68
+ raise WorkerDefaultsConflict(role)
69
+ if models is None:
70
+ values.pop(role, None)
71
+ else:
72
+ values[role] = models
73
+ return values
74
+
75
+
76
+ def select_worker_default(
77
+ role: str,
78
+ project: Mapping[str, object],
79
+ global_: Mapping[str, object],
80
+ ) -> tuple[object, WorkerScope] | None:
81
+ scopes: tuple[tuple[WorkerScope, Mapping[str, object]], ...] = (
82
+ ("project", project),
83
+ ("global", global_),
84
+ )
85
+ for scope, values in scopes:
86
+ if role in values:
87
+ return values[role], scope
88
+ return None
89
+
90
+
91
+ def validate_worker_models(
92
+ raw: object,
93
+ minimum: int,
94
+ maximum: int,
95
+ ) -> tuple[str, ...]:
96
+ if not isinstance(raw, list) or not all(
97
+ isinstance(model, str) and model for model in raw
98
+ ):
99
+ raise WorkerDefaultError("workerDefaults must be a modelRef array")
100
+ if not minimum <= len(raw) <= maximum:
101
+ raise WorkerDefaultError(
102
+ f"worker count must be in {minimum}..{maximum}: {len(raw)}"
103
+ )
104
+ if len(set(raw)) != len(raw):
105
+ raise WorkerDefaultError("duplicate worker model references")
106
+ return tuple(raw)
@@ -3,7 +3,7 @@
3
3
  Every later agent that touches a file loads all of it into context, so a stage that
4
4
  grows one file past a few hundred lines makes every following run pay for it. Both
5
5
  thresholds are measured on the stage diff: 300 lines is the target, reported as an
6
- advisory finding, and 400 lines is the limit, a blocking finding the correction round
6
+ advisory finding, and 500 lines is the limit, a blocking finding the correction round
7
7
  fixes by splitting the file (`_implementation-deliverable.md` §"Correction round").
8
8
 
9
9
  A line is a physical line, as `wc -l` and an editor's line numbers count it, plus an
@@ -15,17 +15,24 @@ the languages okstra's coding preflight has rules for. Lockfiles, JSON / YAML da
15
15
  snapshots, Markdown, SQL and config fall outside by extension. Inside that set, vendored,
16
16
  fixture, snapshot, generated and `.okstra` paths are exempt, and so is a file whose head
17
17
  declares itself generated.
18
+
19
+ A plan cannot be checked against the limit: it does not say how many lines a step adds,
20
+ and a file it creates does not exist yet. `planned_file_headroom` reports what can be
21
+ measured before implementation, the existing files a stage plans to write that sit
22
+ between the target and the limit, so the plan's reviewers see how few lines are left.
18
23
  """
19
24
  from __future__ import annotations
20
25
 
21
26
  import subprocess
22
27
  from dataclasses import dataclass
23
28
  from pathlib import Path, PurePosixPath
29
+ from typing import Any, Mapping
24
30
 
25
31
  from .self_mock_signals import EXT_TO_LANG
32
+ from .write_policy import planned_path_entries
26
33
 
27
34
  FILE_LINE_TARGET = 300
28
- FILE_LINE_LIMIT = 400
35
+ FILE_LINE_LIMIT = 500
29
36
 
30
37
  _EXEMPT_SEGMENTS = frozenset({
31
38
  ".okstra", "node_modules", "vendor", "fixtures", "__fixtures__", "__snapshots__",
@@ -114,16 +121,21 @@ def _breach(before: int | None, after: int, threshold: int) -> str:
114
121
  return f"new file over {threshold}"
115
122
  if before <= threshold:
116
123
  return f"crossed {threshold}"
124
+ if threshold == FILE_LINE_LIMIT:
125
+ # stage base 에서 이미 한도를 넘던 파일은 이 stage 가 만든 것이 아니고, 계획이 그 줄의
126
+ # 이동을 금지할 수 있다. 그래서 성장은 차단하지 않고 권고(목표치)로 넘긴다.
127
+ return ""
117
128
  return f"grew a file over {threshold}" if after > before else ""
118
129
 
119
130
 
120
131
  def file_size_violations(repo: Path, base: str, head: str = "HEAD") -> list[FileSizeViolation]:
121
132
  """Files the `base..head` diff leaves over a threshold, in diff order.
122
133
 
123
- A new file over a threshold, an existing file the diff takes over it, and a file
124
- already over it that the diff grows. A file already over it that the diff leaves the
125
- same size or shrinks is not this stage's to split. A file that breaks the limit is
126
- reported once, as blocking; one that breaks only the target is advisory.
134
+ A new file over a threshold and an existing file the diff takes over it. A file
135
+ already over the target that the diff grows breaks the target too, and so does a file
136
+ already over the limit: the limit blocks only what this stage took past it. A file the
137
+ diff leaves the same size or shrinks is not this stage's to split. A file that breaks
138
+ the limit is reported once, as blocking; one that breaks only the target is advisory.
127
139
  """
128
140
  violations: list[FileSizeViolation] = []
129
141
  for _status, old_path, path in _changed(repo, base, head):
@@ -140,3 +152,41 @@ def file_size_violations(repo: Path, base: str, head: str = "HEAD") -> list[File
140
152
  violations.append(FileSizeViolation(path, before, after, kind, threshold))
141
153
  break
142
154
  return violations
155
+
156
+
157
+ def _planned_files(planning: Mapping[str, Any], project_root: Path) -> dict[str, tuple[Path, list[Any]]]:
158
+ """Each capped planned path, keyed as the stage diff would name it, with its stages in order."""
159
+ files: dict[str, tuple[Path, list[Any]]] = {}
160
+ for entry in planned_path_entries(planning):
161
+ absolute = entry.path if entry.path.is_absolute() else project_root / entry.path
162
+ try:
163
+ rel = absolute.relative_to(project_root).as_posix()
164
+ except ValueError:
165
+ rel = entry.path.as_posix()
166
+ if not capped_path(rel):
167
+ continue
168
+ stages = files.setdefault(rel, (absolute, []))[1]
169
+ if entry.stage.get("stage") not in stages:
170
+ stages.append(entry.stage.get("stage"))
171
+ return files
172
+
173
+
174
+ def planned_file_headroom(planning: Mapping[str, Any], project_root: Path) -> list[dict[str, Any]]:
175
+ """Existing capped planned files with more than the target and at most the limit, one row
176
+ per file with every stage that writes it and the lines left before the limit."""
177
+ rows: list[dict[str, Any]] = []
178
+ for rel, (absolute, stages) in _planned_files(planning, project_root).items():
179
+ if not absolute.is_file():
180
+ continue
181
+ data = absolute.read_bytes()
182
+ lines = physical_lines(data)
183
+ if FILE_LINE_TARGET < lines <= FILE_LINE_LIMIT and not _declares_generated(data):
184
+ rows.append({"path": rel, "stages": stages, "lines": lines,
185
+ "headroom": FILE_LINE_LIMIT - lines})
186
+ return rows
187
+
188
+
189
+ def headroom_text(row: Mapping[str, Any]) -> str:
190
+ stages = ", ".join(str(stage) for stage in row.get("stages") or [])
191
+ return (f"{row.get('path')}: {row.get('lines')} lines, {row.get('headroom')} left before "
192
+ f"the {FILE_LINE_LIMIT}-line limit (stages {stages})")
@@ -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(