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
@@ -102,7 +102,7 @@ Every `okstra` command the lead documents cite, grouped by phase, each spelled w
102
102
  | `okstra lead-progress append --project-root <dir> --run-manifest <path> --phase <phase-id>` | Every `PROGRESS` checkpoint the command performing that step does not record itself; print the `progressLine` it returns. `--phase` accepts only the listed phase ids; use `--worker`, `--field NAME=VALUE`, and `--detail <text>` for the rest | this contract "Progress reporting" |
103
103
  | `okstra agent-activity append --project-root <dir> --run-manifest <path> --kind <kind> --agent <agent> --outcome <outcome> --summary <text>` | Before each activity boundary when the run manifest declares `activityContractVersion: 1`, except a `worker-dispatched` / `worker-completed` row the dispatching command already appended (see "Progress reporting") | launch prompt "Progress reporting" |
104
104
  | `okstra error-log append-observed --out <errors-path> --task-key <key> --phase <phase> --agent <provider-worker> --agent-role <role> --model <model> --error-type <type> --command-kind <kind> --command <command> --message <text>` | Record an observed failure. `--agent` takes the provider worker id (`codex-worker`); an execution label goes in `--execution-label` | this contract "Errors log path wiring"; `team-contract` "Worker error-log command" |
105
- | `okstra approval-decision open --ledger <path> --task-key <key> --task-type <type> --run-seq <seq> --clarification-id <C-NNN> --ticket-id <id> --statement <text> --expected-form <form> --classification <class> --origin <origin> --user-confirmation <text> --unblock-condition <text> --recommended-disposition <disposition> [--supersedes <C-NNN>]` | Open an approval blocker after the user confirmed it | this contract "User confirmation before an approval blocker" |
105
+ | `okstra approval-decision open --ledger <path> --task-key <key> --task-type <type> --run-seq <seq> --clarification-id <C-NNN> --ticket-id <id> --statement <text> --expected-form <form> --classification <class> --origin <origin> --user-confirmation <text> --unblock-condition <text> --recommended-disposition <disposition> [--supersedes <C-NNN>] [--candidate-ref <IO-NNN>]` | Open an approval blocker after the user confirmed it; `--candidate-ref` names the implementation option a split-vote decision accepts | this contract "User confirmation before an approval blocker" |
106
106
  | `okstra approval-decision carry --ledger <path> --clarification-id <C-NNN> --from-responses <path>` | Carry a decision answered in an earlier run | `report-writer` "Role-owned inputs" |
107
107
  | `okstra approval-decision resolve --ledger <path> --clarification-id <C-NNN> --disposition <disposition> --user-text <text> --user-response-ref <ref>` | Record the user's disposition of an approval row; it touches no verdict | `plan-body-verification` "Round protocol" |
108
108
  | `okstra user-response show --report <path>` | Not a lead step: the `okstra-user-response` skill reads approval rows through it, so an `origin` outside the schema enum breaks every later read | `plan-body-verification` "Round protocol" |
@@ -180,7 +180,7 @@ Every `okstra` command the lead documents cite, grouped by phase, each spelled w
180
180
  |---|---|---|
181
181
  | `okstra report-finalize --project-root <dir> --run-manifest <path> [--report <path>]` | Run the whole Phase 7 sequence; do not run its steps separately. `--report` defaults to the manifest's `expectedReportRecordPath`. Without `--only` it records `phase-7-persist` first; emit its `progressLines` | `report-writer` "Phase 6 → Phase 7 execution sequence" |
182
182
  | `okstra handoff record-verified --plan-run-root <dir> --stage <N> --report-path <path> --data-json <path>` | Record an accepted final-verification against its stage. `report-finalize` runs it in its `record-verified` step; run it by hand only to repair a registry after that step failed | `report-writer` "Phase 6 → Phase 7 execution sequence" |
183
- | `okstra correction prompt --run-manifest <path> --round <N> --role <executor\|verifier> --base <sha> --stage-base <sha> --finding <F-id>` | Write a correction-round instruction body; materialize it with dispatch kind `correction-r<N>`. `--stage-base` adds the stage's 400-line file-size findings | `_implementation-deliverable.md` "Correction round" |
183
+ | `okstra correction prompt --run-manifest <path> --round <N> --role <executor\|verifier> --base <sha> --stage-base <sha> --finding <F-id>` | Write a correction-round instruction body; materialize it with dispatch kind `correction-r<N>`. `--stage-base` adds the stage's 500-line file-size limit findings | `_implementation-deliverable.md` "Correction round" |
184
184
  | `okstra stage-done <task-key> --stage <N> --carry <carry.json> --report <path>` | Settle an implementation stage whose synthesised verdict is not FAIL: writes the flat `runs/implementation/carry/stage-<N>.json` sidecar and appends the `done` row — never write either by hand | `_implementation-deliverable.md` "Lead post-stage persistence" |
185
185
  | `okstra stage-fail <task-key> --stage <N> --head-commit <sha> --report <path> --reason <why>` | Record an implementation stage whose synthesised verdict is FAIL, or that ended with no verifier result, as `failed` — never call `append_consumer` from python | `_implementation-deliverable.md` "Lead post-stage persistence" |
186
186
  | `okstra team teardown --project-root <dir> --run-manifest <path>` | Close every recorded pane at the end of the run | cmux adapter "Semantic operation mapping" |
@@ -16,7 +16,7 @@ prompt through `prepare_agent_invocation()` before `worker-dispatch`.
16
16
  Load the applicable coding conventions for every language the diff will touch, then state in ONE line which conventions apply (e.g. `Applying TS + hexagonal overlay; domain at src/domains/*/domain/`). Lint/test green is necessary but NOT sufficient — self-mocked tests, interaction-only assertions, and untruthful names all pass a green pipeline; this gate is what keeps them out of the diff.
17
17
 
18
18
  - **Resource selection — read the routed pack, never inline it here.** Use this worker prompt's `**Coding preflight pack:**` anchor header as the absolute path to the installed routed pack. Detect each touched file's language and framework from its extension or project manifest (`package.json`, `Cargo.toml`, `pyproject.toml`, `pom.xml`, `build.gradle*`, `prisma/schema.prisma`), then read that pack's resources via the Read tool by absolute path. Always read `overview.md` (the router) + `clean-code.md`, then select per the router's three ordered stages — Stage 1 language → `languages/<lang>.md`, Stage 2 framework → `frameworks/<fw>.md` (e.g. `frameworks/node-server.md` for server-side Node), Stage 3 architecture → `architectures/<arch>.md` (e.g. `architectures/hexagonal.md` for ports-and-adapters / NestJS-hex). Each stage is a list of rules; include EVERY matching resource (a change set can touch multiple languages/frameworks/architectures) — do not stop at the first match. These files are runtime resources, not Skill-tool skills, so always read them by path.
19
- - **Project policy projection:** before selecting resources, run `okstra model-io project-context --project-root <PROJECT_ROOT> --task-ref <TASK_KEY>` (the full `Task key` your dispatch prompt names). Consume its `Architecture style`, `Project Review Rule Packs`, and `Project QA Commands` sections; do not open Okstra-owned JSON storage.
19
+ - **Project policy projection:** before selecting resources, run `okstra model-io project-context --project-root <PROJECT_ROOT> --task-ref <TASK_KEY>` (the full `Task key` your dispatch prompt names). Consume its `Architecture style` and `Project Review Rule Packs` sections. Follow the `**Verification inputs:**` declaration-source rule when that header is present; use the named `okstra model-io verification-input --run-manifest <run-manifest>` projection for frozen declarations. The legacy lookup uses the projection's `Project QA Commands` only for an unfrozen baseline. Consume fixed text projections; do not open Okstra-owned JSON storage.
20
20
  - **Declared architecture style — an authoritative Stage 3 input, and it binds.** A projected `hexagonal` selects `architectures/hexagonal.md` even when none of Stage 3's layout signals matched, so the declaration — not the directory shape — decides. A projected `layered` has no pack resource; its invariant applies from this line: dependencies run one direction only — an upper layer may import a lower one, never the reverse — and a variation point is extracted onto a layer boundary. A declared style makes this overlay binding rather than advisory, and which rule binds follows the style: under `hexagonal` the overlay's otherwise-advisory concrete-adapter item is blocking, so a service dependency you add or modify goes through a port instead of a concrete implementation and that placement violation is fixed before the write rather than recorded as a note; under `layered` what binds is the direction invariant just stated — your own judgement over the import list of every file the diff touches, plus extracting a variation point onto a layer boundary — while the concrete-adapter item stays advisory, since `layered` has no ports to route it through. An absent or `none` projected style leaves Stage 3 detection-driven and its overlay advisory. The verifier re-grades the same diff under the same declaration (`_implementation-verifier.md` → Static design & test-quality review), so a placement violation missed here returns as a verdict `FAIL`.
21
21
  - **Project review rule packs:** a pack applies when either source names it — the task brief's `Source Material` / `Reporter Confirmations` cites its exact `SKILL.md` path, or the project-context projection lists it as a standing standard. The two sources are a union. Read only those files and the `references/*.md` files they directly name; a declared path that will not open is recorded as `project-review-rules: declared <path> unreadable`, never silently dropped. Do not search parent directories or host skill catalogs. Apply those rules during implementation as a prevention pass, not a PR-comment generation workflow: do not dispatch reviewer subagents from the executor. For Fonts Ninja-style PR review packs, the executor must avoid newly introduced duplicate helper stacks, tautological tests that merely re-call the delegated helper, self-mocking, domain rules in adapters/ports, domain objects outside `domain/`, dead APIs, weak public names, and functions that fail the plain-English read.
22
22
  - **Language-agnostic principles that ALWAYS bind (the TDD loop MUST satisfy them):** (1) no self-mocking of the SUT — stub/spy only injected collaborators, never the subject's own methods; (2) behavioral assertions on outcomes (return value, state, persisted rows, events, boundary calls) — never `toHaveBeenCalled*` on an internal helper as the only/primary assertion; (3) truthful names — a `get*` / `find*` that writes/inserts, or a name encoding the caller's use-case (`*ForInit`) or hiding a domain rule (`findValid*`), is a defect; (4) single-purpose functions ≤50 effective lines, plain-English readability. Self-mocking (1) — Enforced by `validators/detect_self_mock.py` (static), which the implementation **verifier** runs; it is never delegated to the executor (`_implementation-verifier.md` §"Self-mock detection"). Naming the enforcement here says who will check your diff, not that you should run the check: the executor's half is satisfying principle (1) in the code it writes, and it MUST NOT invoke the detector or write `<task_root>/qa/self-mock-*.json`. **Enforced:** that sidecar is not among the paths an executor attempt's `writePolicy.artifactPolicy.allowedPaths` carries, so writing it closes an otherwise-passing stage as `error` with `artifact-root change exceeds batch policy union` (`scripts/okstra_ctl/execution_mutation_audit.py`). The sidecar's absence BLOCKS at `validate-run.py` on the verifier's report.
@@ -617,5 +617,49 @@
617
617
  "reverify_scope_user_stages": " reverify-scope: stage {stages} 재검증 지정 (사용자 지정 — 하위 stage 포함, 나머지는 직전 판정 이월)",
618
618
  "stage_whole_task": "전체 task",
619
619
  "handoff_scope_stages": "stage {stages} (stage 당 PR 1건)"
620
+ },
621
+ "worker_settings": {
622
+ "source_global": "전역",
623
+ "source_project": "프로젝트",
624
+ "source_once": "이번 실행",
625
+ "source_previous": "직전 실행",
626
+ "role_analyser": "분석자",
627
+ "role_designer": "설계자",
628
+ "role_planner": "계획자",
629
+ "role_implementer": "구현자",
630
+ "role_verifier": "검증자",
631
+ "role_critic": "판정자",
632
+ "role_report-writer": "보고서 작성자",
633
+ "unset": "미설정 · 실행 시 질문",
634
+ "invalid_models": "{source} · 잘못된 모델 목록: {models}",
635
+ "configured": "{count}명 · {models} · {source}",
636
+ "disabled": "사용 안 함",
637
+ "summary_header": "워커 설정 · {scope} · {path}",
638
+ "role_summary": "- {label} ({role}): {value}",
639
+ "changes": "변경 내용:",
640
+ "before": "- {role} 이전: {value}",
641
+ "after": "- {role} 저장 후: {value}",
642
+ "inherit": "전역 설정 상속",
643
+ "clear": "설정 해제",
644
+ "cancel": "취소",
645
+ "scope_label": "워커 설정 범위",
646
+ "scope_global": "전역 기본값",
647
+ "scope_project": "이 프로젝트 덮어쓰기",
648
+ "save": "저장",
649
+ "edit": "계속 수정",
650
+ "review": "변경 검토",
651
+ "models_label": "{role} · 허용 {minimum}..{maximum}명\n선택한 모델 하나당 1명입니다. 상속·해제·사용 안 함은 단독으로 선택하세요.\n검증자 기본값은 시작 역할에만 적용하며 동적 검증자는 원본 배정을 따릅니다.",
652
+ "exclusive": "상속·해제·사용 안 함은 다른 모델과 함께 선택할 수 없습니다.",
653
+ "conflict": "{path}: {role} 설정이 이 편집을 시작한 뒤 바뀌었습니다. 설정을 다시 여세요.",
654
+ "choose_scope": "설정 범위를 선택하세요.",
655
+ "choose_role": "변경할 역할을 선택하세요.",
656
+ "choose_save": "저장 또는 계속 수정을 선택하세요.",
657
+ "cancelled": "워커 설정 취소",
658
+ "saved": "워커 설정 저장 완료",
659
+ "editing": "워커 설정 편집 중",
660
+ "run_invalid": "{error}\n이번 실행의 구성을 다시 선택하세요.\n{label}",
661
+ "run_source": " {role}: {count}명 · 설정 출처: {source}",
662
+ "run_disabled": " {role}: 0명 · 사용 안 함 · 설정 출처: {source}",
663
+ "issue": "{value} · 오류: {error}"
620
664
  }
621
665
  }
@@ -0,0 +1,22 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from ..paths import RunRef
6
+ from ..verification_input_ref import VerificationInputReference
7
+ from ..verification_input_types import VerificationInputs
8
+ from ..verification_inputs import prepare_verification_inputs, read_verification_inputs
9
+
10
+
11
+ class JsonVerificationInputStore:
12
+ def freeze(
13
+ self, project: Path, source: Path, ref: RunRef,
14
+ *, approved_plan: Path | None,
15
+ ) -> VerificationInputReference:
16
+ path, digest = prepare_verification_inputs(
17
+ project, source, ref, approved_plan=approved_plan,
18
+ )
19
+ return VerificationInputReference(path.relative_to(project).as_posix(), digest)
20
+
21
+ def read(self, path: Path, digest: str) -> VerificationInputs:
22
+ return read_verification_inputs(path, digest)
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from pathlib import Path
5
+
6
+ from okstra_project import project_json_path
7
+ from okstra_project.dirs import json_lock_path, okstra_home
8
+
9
+ from ..domain.worker_defaults import (
10
+ WorkerDefaultError,
11
+ WorkerDefaultScopes,
12
+ WorkerDefaultUpdates,
13
+ WorkerScope,
14
+ merge_worker_default_updates,
15
+ )
16
+ from ..json_boundary import load_owned_object, write_owned_object_atomic
17
+ from ..json_registry import registry_lock
18
+
19
+
20
+ def _read_worker_config(path: Path) -> tuple[dict[str, object], dict[str, object]]:
21
+ config = (
22
+ load_owned_object(path, artifact="worker settings") if path.exists() else {}
23
+ )
24
+ values = config.get("workerDefaults", {})
25
+ if not isinstance(values, dict):
26
+ raise WorkerDefaultError(f"{path}: workerDefaults must be an object")
27
+ return config, values
28
+
29
+
30
+ class JsonWorkerDefaultsStore:
31
+ def scope_path(self, scope: WorkerScope, project_root: Path | None) -> Path:
32
+ if scope == "global":
33
+ return okstra_home() / "config.json"
34
+ if scope != "project" or project_root is None:
35
+ raise WorkerDefaultError(
36
+ "project worker settings require an okstra project"
37
+ )
38
+ return project_json_path(project_root)
39
+
40
+ def load_scopes(self, project_root: Path | None) -> WorkerDefaultScopes:
41
+ scopes: WorkerDefaultScopes = {
42
+ "global": _read_worker_config(self.scope_path("global", project_root))[1],
43
+ }
44
+ if project_root is not None:
45
+ scopes["project"] = _read_worker_config(
46
+ self.scope_path("project", project_root)
47
+ )[1]
48
+ return scopes
49
+
50
+ def save_scope(
51
+ self,
52
+ scope: WorkerScope,
53
+ project_root: Path | None,
54
+ updates: WorkerDefaultUpdates,
55
+ before: Mapping[str, object],
56
+ ) -> dict[str, object]:
57
+ path = self.scope_path(scope, project_root)
58
+ with registry_lock(json_lock_path(path)):
59
+ config, current = _read_worker_config(path)
60
+ values = merge_worker_default_updates(current, before, updates)
61
+ config["workerDefaults"] = values
62
+ write_owned_object_atomic(path, config, artifact="worker settings")
63
+ return values
@@ -13,6 +13,7 @@ import sys
13
13
  from ..invocation import AgentInvocationError
14
14
  from ...worker_prompt_headers import WorkerPromptHeaderError
15
15
  from ...error_log_write import record_runtime_failure
16
+ from ...file_size_cap import headroom_text
16
17
  from ...dispatch_state import BACKEND_CLI_WRAPPER, BACKEND_CMUX_PANE, DispatchError
17
18
  from .emit import _emit, _prepared_payload
18
19
  from .inputs import AgentPromptCliError
@@ -407,6 +408,8 @@ def main(argv: list[str] | None = None) -> int:
407
408
  else:
408
409
  for defect in payload["defects"]:
409
410
  print(defect, file=sys.stderr)
411
+ for row in payload["fileSizeHeadroom"]:
412
+ print(f"File-size headroom: {headroom_text(row)}")
410
413
  print("ok" if payload["ok"] else "defects: " + str(len(payload["defects"])))
411
414
  return 0 if payload["ok"] else 1
412
415
  if args.command == "apply-corrections":
@@ -23,6 +23,7 @@ from ..activity import (
23
23
  agent_activity_rows,
24
24
  record_activity,
25
25
  )
26
+ from ...file_size_cap import planned_file_headroom
26
27
  from ...final_report_schema import load_schema_version
27
28
  from ...json_boundary import load_owned_object
28
29
  from ...phases.implementation_option_selection.validation import validate_implementation_option_selection
@@ -156,6 +157,7 @@ def corrections_payload(
156
157
  check: CorrectionsCheck, *, project_root: Path, corrections_path: Path,
157
158
  ) -> dict[str, Any]:
158
159
  """`check-corrections --json` 의 출력."""
160
+ planning = (check.scratch or {}).get("implementationPlanning")
159
161
  return {
160
162
  "ok": check.ok,
161
163
  "correctionsPath": _relative(project_root, corrections_path),
@@ -169,6 +171,9 @@ def corrections_payload(
169
171
  for item in check.corrections
170
172
  ],
171
173
  "defects": list(check.defects),
174
+ "fileSizeHeadroom": (
175
+ planned_file_headroom(planning, project_root) if isinstance(planning, Mapping) else []
176
+ ),
172
177
  }
173
178
 
174
179
 
@@ -181,8 +181,7 @@ def build_analysis_packet(
181
181
  )
182
182
  )
183
183
  # The directive overrides the brief and the plan text below it, so it comes
184
- # before them. As the last section of a 4,865-line packet (dev-11562), an
185
- # executor stopped on a plan/brief conflict the directive had resolved.
184
+ # before them: a reader that stops early must already have seen it.
186
185
  parts.extend(_directive_block(directive))
187
186
  # 짧은 포인터 절이라 46KB 에서 잘리는 읽기에서도 도착하도록 브리프보다 앞에 둔다.
188
187
  if technical_evidence_text:
@@ -227,6 +226,9 @@ def build_analysis_packet(
227
226
 
228
227
  _HEADING_RE = re.compile(r"\A#{1,2} \S")
229
228
  _FENCE_RE = re.compile(r"\A\s*(?P<marker>`{3,}|~{3,})(?P<info>.*)\Z")
229
+ # One page size for every packet read instruction: the section index, the worker
230
+ # prompt's read-scope header and the worker preamble must not disagree.
231
+ PACKET_PAGE_LINES = 200
230
232
  # 목차 자신이 차지하는 줄 수 중 표제 행을 뺀 나머지. 행 수는 표제 개수로
231
233
  # 정해지므로 삽입 전에 전체 이동량을 계산할 수 있다.
232
234
  _INDEX_PREAMBLE_LINES = 5
@@ -317,7 +319,8 @@ def _with_section_index(body: str) -> str:
317
319
  " `sed -n '<start>,<end>p'` rather than opening the whole file: a"
318
320
  " whole-file read is truncated by some worker CLIs without reporting"
319
321
  " it, and the sections that describe current state are last. Page a"
320
- " range longer than 200 lines in 200-line reads.",
322
+ f" range longer than {PACKET_PAGE_LINES} lines"
323
+ f" in {PACKET_PAGE_LINES}-line reads.",
321
324
  "",
322
325
  *rows,
323
326
  ]
@@ -516,35 +519,35 @@ def _group_memory_block(
516
519
  return lines
517
520
 
518
521
 
519
-
520
522
  def cited_documents_block(brief_text: str, project_root: Path) -> str:
521
523
  """브리프 Source Material 이 참조로 인용한 로컬 파일을 패킷 절로 싣는다.
522
524
 
523
525
  `- format: by-reference` 인 `### Source N — file` 항목은 본문 대신 파일을
524
- 가리킨다. task worktree 는 체크아웃이라 프로젝트 루트의 untracked 파일
525
- (`.project-docs/` 스펙)이 없고, 설계자들은 그 스펙이 이미 정한 점에
526
- `uncertain` 을 던졌다(fontradar dev-11562). prepare 는 Source Material 이
527
- 인용한 경로만 프로젝트 루트에서 읽기 전용으로 읽고, 루트 밖 경로는 읽지
528
- 않는다(artifact-home 규칙).
526
+ 가리킨다. The task worktree is a checkout, so it lacks untracked files in
527
+ the project root (such as `.project-docs/` specs); prepare reads only the
528
+ cited paths, read-only, from the project root, and never a path outside it
529
+ (artifact-home rule).
529
530
  """
530
531
  root = project_root.resolve()
531
532
  entries: list[str] = []
532
533
  for ref in _by_reference_file_refs(_section_map(brief_text).get("Source Material", "")):
533
- candidate = Path(ref).expanduser()
534
- path = (candidate if candidate.is_absolute() else root / candidate).resolve()
535
- try:
536
- relative = path.relative_to(root).as_posix()
537
- except ValueError:
538
- entries.append(f"### `{ref}`\n\n- not read: outside the project root")
534
+ relative = project_relative_ref(ref, root)
535
+ if relative is None:
536
+ entries.append(
537
+ f"### `{ref}`\n\n"
538
+ "- not read: does not resolve to a path under the project root"
539
+ )
539
540
  continue
541
+ path = root / relative
540
542
  if not path.is_file():
541
543
  entries.append(f"### `{relative}`\n\n- not read: no such file under the project root")
542
544
  continue
543
- content = path.read_bytes()
544
- if len(content) > MAX_CITED_DOCUMENT_BYTES:
545
+ with path.open("rb") as handle:
546
+ content = handle.read(MAX_CITED_DOCUMENT_BYTES + 1)
547
+ if exceeds_cited_document_limit(len(content)):
545
548
  entries.append(
546
- f"### `{relative}`\n\n- not read: {len(content)} bytes exceeds "
547
- f"{MAX_CITED_DOCUMENT_BYTES}; paste the cited part into Source Material"
549
+ f"### `{relative}`\n\n- not read: exceeds {MAX_CITED_DOCUMENT_BYTES} "
550
+ "bytes; paste the cited part into Source Material"
548
551
  )
549
552
  continue
550
553
  text = content.decode("utf-8", errors="replace").rstrip("\n")
@@ -567,6 +570,30 @@ def cited_documents_block(brief_text: str, project_root: Path) -> str:
567
570
  ])
568
571
 
569
572
 
573
+ def exceeds_cited_document_limit(size: int) -> bool:
574
+ """Whether prepare refuses to copy a cited file of `size` bytes into the packet."""
575
+ return size > MAX_CITED_DOCUMENT_BYTES
576
+
577
+
578
+ def project_relative_ref(ref: str, root: Path) -> str | None:
579
+ """The posix path of a Source Material `ref` relative to the resolved `root`.
580
+
581
+ None when the ref resolves outside the root, or names the home directory of
582
+ a user this machine does not know (`~200` in prose). Every reader and
583
+ writer of a `### Source N — file` ref goes through here so they agree on
584
+ which file it names.
585
+ """
586
+ try:
587
+ candidate = Path(ref).expanduser()
588
+ except RuntimeError:
589
+ return None
590
+ path = (candidate if candidate.is_absolute() else root / candidate).resolve()
591
+ try:
592
+ return path.relative_to(root).as_posix()
593
+ except ValueError:
594
+ return None
595
+
596
+
570
597
  def _by_reference_file_refs(source_material: str) -> list[str]:
571
598
  refs = [ref for ref, fmt in file_source_entries(source_material) if fmt == BY_REFERENCE_FORMAT]
572
599
  return list(dict.fromkeys(refs))
@@ -591,10 +618,14 @@ def file_source_entries(source_material: str) -> list[tuple[str, str]]:
591
618
  match.groups() for line in block[1:]
592
619
  if (match := _SOURCE_FIELD_RE.match(line))
593
620
  )
594
- if fields.get("ref", "").strip():
595
- entries.append((fields["ref"].strip(), fields.get("format", "").strip()))
621
+ # A ref written as inline code (`` `docs/spec.md` ``) names the path
622
+ # inside the backticks.
623
+ ref = fields.get("ref", "").strip().strip("`").strip()
624
+ if ref:
625
+ entries.append((ref, fields.get("format", "").strip()))
596
626
  return entries
597
627
 
628
+
598
629
  def _brief_block(brief_text: str) -> list[str]:
599
630
  return [
600
631
  "",
@@ -39,6 +39,17 @@ def _schema_enum(definition: str) -> frozenset[str]:
39
39
  return frozenset(str(value) for value in values)
40
40
 
41
41
 
42
+ @lru_cache(maxsize=None)
43
+ def _schema_pattern(definition: str) -> str:
44
+ schema = load_schema_version(CURRENT_REPORT_SCHEMA_VERSION)
45
+ pattern = (schema.get("$defs") or {}).get(definition, {}).get("pattern")
46
+ if not isinstance(pattern, str) or not pattern:
47
+ raise ApprovalDecisionError(
48
+ f"report schema has no pattern for {definition!r}"
49
+ )
50
+ return pattern
51
+
52
+
42
53
  DISPOSITIONS = frozenset({"select", "accept-risk", "request-revision", "reject"})
43
54
  REACHES = frozenset({"in-repo", "cross-repo"})
44
55
  SCOPE_EFFECTS = frozenset({"new-schema", "deferrable"})
@@ -223,6 +234,7 @@ def open_decision(
223
234
  classification: str, origin: str, user_confirmation: str,
224
235
  unblock_condition: str, recommended_disposition: str,
225
236
  options: Sequence[DecisionOption], supersedes: Sequence[str] = (),
237
+ candidate_ref: str = "",
226
238
  ) -> None:
227
239
  row = _decision_row(
228
240
  clarification_id=clarification_id, ticket_id=ticket_id,
@@ -239,10 +251,19 @@ def open_decision(
239
251
  raise ApprovalDecisionError(f"duplicate active clarification: {clarification_id}")
240
252
  if supersedes:
241
253
  row["supersedes"] = _superseded_carried_ids(ledger, supersedes)
254
+ if candidate_ref:
255
+ row["candidateRef"] = _candidate_ref(candidate_ref)
242
256
  active.append(row)
243
257
  write_json_atomic(ledger_path, ledger)
244
258
 
245
259
 
260
+ def _candidate_ref(value: str) -> str:
261
+ ref = value.strip()
262
+ if re.search(_schema_pattern("ImplementationOptionId"), ref) is None:
263
+ raise ApprovalDecisionError(f"candidate_ref must be an option id (IO-NNN): {value!r}")
264
+ return ref
265
+
266
+
246
267
  def _superseded_carried_ids(
247
268
  ledger: Mapping[str, Any], supersedes: Sequence[str],
248
269
  ) -> list[str]:
@@ -442,6 +463,14 @@ def _add_open_arguments(parser: argparse.ArgumentParser) -> None:
442
463
  "Repeat for several ids."
443
464
  ),
444
465
  )
466
+ parser.add_argument(
467
+ "--candidate-ref",
468
+ default="",
469
+ help=(
470
+ "the implementation option (IO-NNN) this decision is about. A "
471
+ "candidate's splitAcceptance may cite only a decision opened for it."
472
+ ),
473
+ )
445
474
 
446
475
 
447
476
  _CLI_EPILOG = r"""Usage:
@@ -523,7 +552,7 @@ def _open_from_args(args: argparse.Namespace) -> None:
523
552
  # 행이고, 이월 행은 `answered` 로 실린다.
524
553
  _QUESTION_FIELDS = (
525
554
  "id", "ticketId", "kind", "statement", "expectedForm", "blocks", "origin",
526
- "options",
555
+ "options", "candidateRef",
527
556
  )
528
557
 
529
558