okstra 0.234.1 → 0.236.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 (171) hide show
  1. package/dist/cli-registry.mjs +7 -0
  2. package/dist/cli-registry.mjs.map +1 -1
  3. package/dist/commands/implementation-report/implementation-report.d.mts +1 -0
  4. package/dist/commands/implementation-report/implementation-report.mjs +73 -0
  5. package/dist/commands/implementation-report/implementation-report.mjs.map +1 -0
  6. package/dist/commands/trace/comparison.d.mts +39 -0
  7. package/dist/commands/trace/comparison.mjs +138 -0
  8. package/dist/commands/trace/comparison.mjs.map +1 -0
  9. package/dist/commands/trace/document.d.mts +8 -0
  10. package/dist/commands/trace/document.mjs +37 -0
  11. package/dist/commands/trace/document.mjs.map +1 -0
  12. package/dist/commands/trace/line-counts.d.mts +15 -0
  13. package/dist/commands/trace/line-counts.mjs +107 -0
  14. package/dist/commands/trace/line-counts.mjs.map +1 -0
  15. package/dist/commands/trace/model.d.mts +2 -1
  16. package/dist/commands/trace/model.mjs +13 -1
  17. package/dist/commands/trace/model.mjs.map +1 -1
  18. package/dist/commands/trace/progression.mjs +7 -3
  19. package/dist/commands/trace/progression.mjs.map +1 -1
  20. package/dist/commands/trace/task-link.d.mts +3 -0
  21. package/dist/commands/trace/task-link.mjs.map +1 -1
  22. package/dist/commands/trace/trace.mjs +64 -44
  23. package/dist/commands/trace/trace.mjs.map +1 -1
  24. package/dist/lib/host-registry-client.d.mts +9 -2
  25. package/dist/lib/host-registry-client.mjs +29 -3
  26. package/dist/lib/host-registry-client.mjs.map +1 -1
  27. package/dist/lib/python-helper.d.mts +1 -1
  28. package/dist/lib/python-helper.mjs +11 -5
  29. package/dist/lib/python-helper.mjs.map +1 -1
  30. package/dist/lib/runtime-payload.mjs +1 -0
  31. package/dist/lib/runtime-payload.mjs.map +1 -1
  32. package/dist/lib/types.d.mts +1 -0
  33. package/docs/architecture/storage-model.md +50 -0
  34. package/docs/architecture.md +1 -1
  35. package/docs/cli.md +37 -15
  36. package/docs/project-structure-overview.md +6 -1
  37. package/package.json +1 -1
  38. package/runtime/BUILD.json +2 -2
  39. package/runtime/agents/operations/trace-tests-review.json +6 -0
  40. package/runtime/bin/lib/okstra/usage.sh +8 -8
  41. package/runtime/bin/okstra-qwen-exec.sh +5 -0
  42. package/runtime/prompts/duties/test-reviewer.json +32 -0
  43. package/runtime/prompts/lead/convergence.md +4 -1
  44. package/runtime/prompts/lead/okstra-lead-contract.md +3 -3
  45. package/runtime/prompts/lead/report-writer.md +13 -1
  46. package/runtime/prompts/profiles/_common-contract.md +10 -1
  47. package/runtime/prompts/wizard/prompts.ko.json +16 -4
  48. package/runtime/python/okstra_ctl/adapters/providers/antigravity/adapter.py +10 -2
  49. package/runtime/python/okstra_ctl/adapters/providers/claude/adapter.py +16 -1
  50. package/runtime/python/okstra_ctl/adapters/providers/codex/adapter.py +20 -5
  51. package/runtime/python/okstra_ctl/adapters/providers/kimi/adapter.py +17 -9
  52. package/runtime/python/okstra_ctl/adapters/providers/qwen/adapter.py +88 -0
  53. package/runtime/python/okstra_ctl/adapters/providers/qwen/manifest.json +1 -0
  54. package/runtime/python/okstra_ctl/adapters/providers/qwen/settings.json +12 -0
  55. package/runtime/python/okstra_ctl/adapters/providers/zai/adapter.py +8 -2
  56. package/runtime/python/okstra_ctl/agent/invocation.py +109 -56
  57. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +17 -0
  58. package/runtime/python/okstra_ctl/attempt_evidence.py +5 -2
  59. package/runtime/python/okstra_ctl/business_flow/contracts.py +11 -0
  60. package/runtime/python/okstra_ctl/business_flow/engine.py +90 -32
  61. package/runtime/python/okstra_ctl/business_flow/hooks.py +4 -2
  62. package/runtime/python/okstra_ctl/business_flow/source.py +39 -7
  63. package/runtime/python/okstra_ctl/business_flow/store.py +94 -28
  64. package/runtime/python/okstra_ctl/code_review_census.py +38 -0
  65. package/runtime/python/okstra_ctl/code_review_coverage.py +15 -4
  66. package/runtime/python/okstra_ctl/code_review_prepare.py +15 -3
  67. package/runtime/python/okstra_ctl/code_review_scope.py +3 -2
  68. package/runtime/python/okstra_ctl/code_review_target.py +16 -6
  69. package/runtime/python/okstra_ctl/conformance_evidence.py +44 -21
  70. package/runtime/python/okstra_ctl/consumers.py +6 -1
  71. package/runtime/python/okstra_ctl/convergence.py +95 -5
  72. package/runtime/python/okstra_ctl/convergence_critic_verify_prompt.py +11 -10
  73. package/runtime/python/okstra_ctl/convergence_engine.py +30 -15
  74. package/runtime/python/okstra_ctl/convergence_reverify_prompt.py +9 -2
  75. package/runtime/python/okstra_ctl/coverage_census.py +75 -12
  76. package/runtime/python/okstra_ctl/design_review.py +6 -26
  77. package/runtime/python/okstra_ctl/design_review_evidence.py +6 -26
  78. package/runtime/python/okstra_ctl/dispatch_core.py +9 -2
  79. package/runtime/python/okstra_ctl/dispatch_state.py +5 -0
  80. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  81. package/runtime/python/okstra_ctl/entrypoints/hosts.py +1 -1
  82. package/runtime/python/okstra_ctl/execution_manifest.py +8 -0
  83. package/runtime/python/okstra_ctl/implementation_comparison/__init__.py +12 -0
  84. package/runtime/python/okstra_ctl/implementation_comparison/__main__.py +129 -0
  85. package/runtime/python/okstra_ctl/implementation_comparison/assembly.py +340 -0
  86. package/runtime/python/okstra_ctl/implementation_comparison/baseline.py +254 -0
  87. package/runtime/python/okstra_ctl/implementation_comparison/business_reuse.py +118 -0
  88. package/runtime/python/okstra_ctl/implementation_comparison/commit_source.py +113 -0
  89. package/runtime/python/okstra_ctl/implementation_comparison/html.py +49 -0
  90. package/runtime/python/okstra_ctl/implementation_comparison/inputs.py +348 -0
  91. package/runtime/python/okstra_ctl/implementation_comparison/model.py +47 -0
  92. package/runtime/python/okstra_ctl/implementation_comparison/preparation.py +195 -0
  93. package/runtime/python/okstra_ctl/implementation_comparison/publication.py +317 -0
  94. package/runtime/python/okstra_ctl/implementation_comparison/run_evidence.py +208 -0
  95. package/runtime/python/okstra_ctl/implementation_comparison/run_integration.py +198 -0
  96. package/runtime/python/okstra_ctl/implementation_comparison/source.py +342 -0
  97. package/runtime/python/okstra_ctl/implementation_comparison/target.py +144 -0
  98. package/runtime/python/okstra_ctl/implementation_comparison/task_assembly.py +333 -0
  99. package/runtime/python/okstra_ctl/implementation_comparison/task_selection.py +309 -0
  100. package/runtime/python/okstra_ctl/implementation_generation_evidence.py +134 -0
  101. package/runtime/python/okstra_ctl/implementation_outcome.py +2 -2
  102. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +1 -0
  103. package/runtime/python/okstra_ctl/json_boundary.py +28 -8
  104. package/runtime/python/okstra_ctl/lead_progress.py +1 -1
  105. package/runtime/python/okstra_ctl/model_discovery.py +1 -1
  106. package/runtime/python/okstra_ctl/models.py +2 -2
  107. package/runtime/python/okstra_ctl/paths.py +7 -4
  108. package/runtime/python/okstra_ctl/phases/discussion/profile.md +2 -2
  109. package/runtime/python/okstra_ctl/phases/error_analysis/profile.md +1 -1
  110. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  111. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +2 -1
  112. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +1 -1
  113. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +3 -3
  114. package/runtime/python/okstra_ctl/phases/requirements_discovery/profile.md +5 -5
  115. package/runtime/python/okstra_ctl/plan_run_root.py +8 -4
  116. package/runtime/python/okstra_ctl/qa_procedures.py +33 -2
  117. package/runtime/python/okstra_ctl/registry/provider_registry.py +1 -1
  118. package/runtime/python/okstra_ctl/render.py +4 -0
  119. package/runtime/python/okstra_ctl/render_final_report.py +1 -1
  120. package/runtime/python/okstra_ctl/report_execution_evidence.py +88 -15
  121. package/runtime/python/okstra_ctl/report_finalize.py +18 -4
  122. package/runtime/python/okstra_ctl/report_html/render.py +46 -7
  123. package/runtime/python/okstra_ctl/report_html/validation.py +32 -0
  124. package/runtime/python/okstra_ctl/report_synthesis_packet.py +37 -3
  125. package/runtime/python/okstra_ctl/report_view_artifacts.py +12 -0
  126. package/runtime/python/okstra_ctl/review_verdicts.py +9 -0
  127. package/runtime/python/okstra_ctl/run.py +17 -1
  128. package/runtime/python/okstra_ctl/run_context.py +18 -3
  129. package/runtime/python/okstra_ctl/schema_excerpt.py +14 -9
  130. package/runtime/python/okstra_ctl/stage_done.py +11 -3
  131. package/runtime/python/okstra_ctl/stage_ledger.py +2 -2
  132. package/runtime/python/okstra_ctl/stage_map.py +3 -3
  133. package/runtime/python/okstra_ctl/trace_review.py +1 -0
  134. package/runtime/python/okstra_ctl/trace_tasks.py +22 -7
  135. package/runtime/python/okstra_ctl/verdict_blocks.py +7 -2
  136. package/runtime/python/okstra_ctl/verification_dispatch.py +32 -0
  137. package/runtime/python/okstra_ctl/verification_evidence.py +23 -3
  138. package/runtime/python/okstra_ctl/verification_generation.py +3 -2
  139. package/runtime/python/okstra_ctl/verification_inputs.py +3 -2
  140. package/runtime/python/okstra_ctl/verification_invocation.py +7 -3
  141. package/runtime/python/okstra_ctl/wizard/engine.py +28 -1
  142. package/runtime/python/okstra_ctl/wizard/ids.py +8 -0
  143. package/runtime/python/okstra_ctl/wizard/picker_navigation.py +64 -2
  144. package/runtime/python/okstra_ctl/wizard/roles.py +194 -45
  145. package/runtime/python/okstra_ctl/wizard/sources.py +10 -1
  146. package/runtime/python/okstra_ctl/wizard/state.py +67 -20
  147. package/runtime/python/okstra_ctl/wizard/steps_roles.py +6 -3
  148. package/runtime/python/okstra_ctl/wizard/worker_settings.py +129 -25
  149. package/runtime/python/okstra_ctl/worker_audit_ledger.py +44 -8
  150. package/runtime/python/okstra_ctl/worker_prompt_body.py +26 -2
  151. package/runtime/python/okstra_ctl/worker_prompt_headers.py +12 -9
  152. package/runtime/python/okstra_token_usage/claude.py +5 -1
  153. package/runtime/python/okstra_token_usage/collect.py +3 -3
  154. package/runtime/python/okstra_token_usage/pricing.py +1 -0
  155. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +17 -0
  156. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  157. package/runtime/skills/okstra-code-review/SKILL.md +1 -1
  158. package/runtime/skills/okstra-code-review/references/census-rules.md +1 -1
  159. package/runtime/skills/okstra-code-review/references/review-calibration.md +1 -1
  160. package/runtime/skills/okstra-discussion/SKILL.md +1 -1
  161. package/runtime/skills/okstra-run/SKILL.md +33 -2
  162. package/runtime/skills/okstra-tdd/SKILL.md +74 -13
  163. package/runtime/templates/reports/html/assets/implementation-comparison.css +39 -0
  164. package/runtime/templates/reports/html/assets/implementation-comparison.js +55 -0
  165. package/runtime/templates/reports/html/i18n/en.json +113 -0
  166. package/runtime/templates/reports/html/i18n/ko.json +113 -0
  167. package/runtime/templates/reports/html/implementation-comparison.template.html +77 -0
  168. package/runtime/templates/reports/implementation-comparison-notes.md +72 -0
  169. package/runtime/templates/trace/trace.template.md +2 -0
  170. package/runtime/templates/worker-prompt-preamble.md +12 -2
  171. package/runtime/validators/validate-report-views.py +4 -36
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
  import hashlib
4
4
  import json
5
5
  import re
6
+ from collections import Counter
6
7
  from dataclasses import asdict, replace
7
8
  from datetime import datetime, timezone
8
9
  from pathlib import Path
@@ -27,6 +28,7 @@ from .contracts import (
27
28
  SourceSnapshot,
28
29
  artifact_path,
29
30
  now_iso,
31
+ prompt_schema,
30
32
  read_artifact,
31
33
  schema_definition,
32
34
  write_artifact,
@@ -40,11 +42,14 @@ from .source import (
40
42
  validate_evidence,
41
43
  )
42
44
  from .store import (
45
+ conflict_groups,
43
46
  contribute_knowledge,
44
47
  query_knowledge,
45
48
  read_shared_knowledge,
46
49
  record_task_execution,
47
50
  resolve_conflicts,
51
+ split_by_focus,
52
+ task_focus,
48
53
  validate_resolutions,
49
54
  )
50
55
 
@@ -298,7 +303,9 @@ def _validate_fact_evidence(
298
303
  "confirmed business claims require inspected code evidence"
299
304
  )
300
305
  for evidence in fact["evidence"]:
301
- evidence["excerpt"] = validate_evidence(evidence, projects)
306
+ evidence["excerpt"], evidence["line"], evidence["endLine"] = validate_evidence(
307
+ evidence, projects
308
+ )
302
309
  if evidence["projectId"] not in result["inspectedProjects"]:
303
310
  raise BusinessFlowError(
304
311
  "claim evidence references an uninspected candidate"
@@ -379,7 +386,7 @@ def _instructions(
379
386
  request: FlowRequest, execution: FlowExecution, baseline: FlowExecution | None
380
387
  ) -> str:
381
388
  context = _investigation_context(request, execution, baseline)
382
- schema = schema_definition("result")
389
+ schema = prompt_schema("result")
383
390
  return "\n".join(
384
391
  [
385
392
  "# Business Flow Investigation",
@@ -395,12 +402,15 @@ def _instructions(
395
402
  "For post mode, use the supplied project-specific baseline. Never invent missing before-state. Describe the actual delta and distinguish confirmed side effects from risks.",
396
403
  "For contribute mode, extract newly observed business facts from the supplied validated task record and inspect source to confirm them. Empty facts are valid. Do not copy the report narrative as established truth.",
397
404
  "For reconcile mode, reinspect every conflicting source and condition. Return explicit resolutions only with evidence-backed reasoning and original claimIds/acceptedClaimId. Preserve genuinely unresolved policy decisions in questions. Other modes return resolutions=[].",
405
+ "knowledge.conflictGroups lists each active conflict: the claims that disagree on one key at one source version. A resolution's claimIds must be exactly one group's claimIds, never claims of the same key from another group, and acceptedClaimId one of them. Resolve only groups whose freshness is current; a historical group's source has changed since and stays a conflict. Return the accepted claim's key, value and level unchanged as a fact with evidence you reinspected.",
406
+ "Stored knowledge claims cite evidence as projectId:path:line-endLine. knowledge.notShown counts, by business, stored claims that do not mention this task; look one up with `okstra explain-flow knowledge --query <business question>` when it applies.",
398
407
  "Keep fact keys, business identifiers and fact values canonical in English; preserve original business terms in aliases. Do not create conflicts by translating the same fact. Read source evidence before accepting stored knowledge, including other projects' claims.",
399
408
  "execution-verified requires a supplied JSON verificationReceipt with command, startedAt, endedAt, exitCode=0, output and matching projectId-to-digest sourceStates. A final report alone is not an execution receipt.",
409
+ 'Each terms item has exactly two fields: {"term": "<business term>", "meaning": "<what it means here>"}.',
400
410
  f"Write report titles, summaries, terms, steps, relationship data, gaps and questions in {request.report_language}; preserve paths, identifiers and enum values.",
401
411
  "",
402
412
  "## Source Material and Captured Baseline",
403
- json.dumps(context, ensure_ascii=False, indent=2),
413
+ json.dumps(context, ensure_ascii=False, separators=(",", ":")),
404
414
  "",
405
415
  "## Result Schema",
406
416
  json.dumps(schema, ensure_ascii=False, indent=2),
@@ -412,6 +422,7 @@ def _instructions(
412
422
  def _investigation_context(
413
423
  request: FlowRequest, execution: FlowExecution, baseline: FlowExecution | None
414
424
  ) -> dict[str, Any]:
425
+ knowledge = _investigation_knowledge(request)
415
426
  compact = [
416
427
  {
417
428
  "projectId": row["projectId"],
@@ -441,13 +452,65 @@ def _investigation_context(
441
452
  )
442
453
  if baseline
443
454
  else "",
444
- "knowledge": query_knowledge(
445
- request.project_root,
446
- request.question,
447
- request.source_root,
448
- request.project_group,
449
- members_only=request.mode != "reconcile",
450
- ),
455
+ "knowledge": {**knowledge, "claims": [_prompt_claim(row) for row in knowledge["claims"]]},
456
+ }
457
+
458
+
459
+ _PROMPT_CLAIM_FIELDS = ("id", "key", "business", "value", "level", "status", "freshness")
460
+
461
+
462
+ def _prompt_claim(row: dict[str, Any]) -> dict[str, Any]:
463
+ """The investigator re-reads a claim's source before relying on it, so the
464
+ producers, source states and evidence excerpts stay in the store."""
465
+ claim = {field: row[field] for field in _PROMPT_CLAIM_FIELDS}
466
+ claim.update({field: row[field] for field in ("aliases", "relatedKeys") if row.get(field)})
467
+ claim["evidence"] = [
468
+ f"{item['projectId']}:{item['path']}:{item['line']}-{item['endLine']}"
469
+ for item in row["evidence"]
470
+ ]
471
+ return claim
472
+
473
+
474
+ def _investigation_knowledge(request: FlowRequest) -> dict[str, Any]:
475
+ """Stored claims for an investigation.
476
+
477
+ A task's question is its whole brief, whose words select nearly every stored
478
+ claim, so a task investigation keeps the claims that mention the task's
479
+ focus terms and counts the rest by business. A reconcile question names
480
+ its conflict keys and is not narrowed; it also gets the conflict groups,
481
+ because a resolution must cover exactly one and the claims no longer carry
482
+ the source versions that tell the groups apart.
483
+ """
484
+ result = query_knowledge(
485
+ request.project_root,
486
+ request.question,
487
+ request.source_root,
488
+ request.project_group,
489
+ members_only=request.mode != "reconcile",
490
+ )
491
+ claims = result["claims"]
492
+ if request.mode == "reconcile":
493
+ return {
494
+ "claims": claims,
495
+ "conflictGroups": [
496
+ {
497
+ "key": group[0]["key"],
498
+ "freshness": group[0]["freshness"],
499
+ "claimIds": sorted(row["id"] for row in group),
500
+ }
501
+ for group in conflict_groups(claims)
502
+ ],
503
+ "notShown": {},
504
+ "errors": result["errors"],
505
+ }
506
+ focus = task_focus(request.task_key, request.question) if request.task_key else ()
507
+ if not focus:
508
+ return {"claims": claims, "notShown": {}, "errors": result["errors"]}
509
+ focused, others = split_by_focus(claims, focus)
510
+ return {
511
+ "claims": focused,
512
+ "notShown": dict(Counter(row["business"] for row in others).most_common()),
513
+ "errors": result["errors"],
451
514
  }
452
515
 
453
516
 
@@ -456,16 +519,7 @@ def _reinvestigate_conflicts(
456
519
  ) -> None:
457
520
  if request.mode == "reconcile":
458
521
  return
459
- conflict_keys = {
460
- row["key"]
461
- for row in query_knowledge(
462
- request.project_root,
463
- request.question,
464
- request.source_root,
465
- request.project_group,
466
- )["claims"]
467
- if row["status"] == "conflict"
468
- }
522
+ conflict_keys = _conflict_keys(request, execution)
469
523
  if not conflict_keys:
470
524
  return
471
525
  child = explain_flow(
@@ -483,25 +537,29 @@ def _reinvestigate_conflicts(
483
537
  "error": child.get("error", ""),
484
538
  "questions": child.get("result", {}).get("questions", []),
485
539
  }
486
- unresolved = [
487
- row["key"]
488
- for row in query_knowledge(
489
- request.project_root,
490
- request.question,
491
- request.source_root,
492
- request.project_group,
493
- )["claims"]
494
- if row["status"] == "conflict"
495
- ]
540
+ unresolved = _conflict_keys(request, execution)
496
541
  if unresolved:
497
542
  execution["result"]["questions"].append(
498
- "Unresolved shared business conflicts: "
499
- + ", ".join(sorted(set(unresolved)))
543
+ "Unresolved shared business conflicts: " + ", ".join(sorted(unresolved))
500
544
  )
501
545
  execution["status"] = "partial"
502
546
  write_artifact(path, execution, "execution")
503
547
 
504
548
 
549
+ def _conflict_keys(request: FlowRequest, execution: FlowExecution) -> set[str]:
550
+ """Conflicts this explanation answers for: among the claims its investigator
551
+ was shown, and on a key it returned, which is where a conflict it created
552
+ lies even when the claim does not mention the task."""
553
+ returned = {fact["key"] for fact in execution["result"]["facts"]}
554
+ shown = _investigation_knowledge(request)["claims"]
555
+ stored = read_shared_knowledge(request.project_root, request.project_group)["claims"]
556
+ return {
557
+ row["key"]
558
+ for row in [*shown, *(row for row in stored if row["key"] in returned)]
559
+ if row["status"] == "conflict"
560
+ }
561
+
562
+
505
563
  def load_execution(project_root: Path, execution_id: str) -> FlowExecution:
506
564
  if not execution_id or any(
507
565
  char not in "abcdefghijklmnopqrstuvwxyz0123456789-" for char in execution_id
@@ -17,7 +17,7 @@ from .contracts import (
17
17
  from .engine import explain_flow, load_execution
18
18
  from .invocation import FlowExecutor
19
19
  from .source import candidate_projects, capture_projects, changed_projects
20
- from .store import knowledge_packet, read_task_links, record_task_execution
20
+ from .store import knowledge_packet, read_task_links, record_task_execution, task_focus
21
21
 
22
22
 
23
23
  def prepare_task_knowledge(
@@ -58,7 +58,9 @@ def prepare_task_knowledge(
58
58
  _ensure_pre_explanation(project_root, request, executor)
59
59
  except (OSError, ValueError, JsonBoundaryError) as exc:
60
60
  return f"## Shared Business Knowledge\n\nBusiness preparation failed: {exc}\n"
61
- return knowledge_packet(project_root, question, Path(source))
61
+ return knowledge_packet(
62
+ project_root, question, Path(source), task_focus(str(ctx.get("TASK_KEY", "")), question)
63
+ )
62
64
 
63
65
 
64
66
  def _flow_request(
@@ -168,7 +168,12 @@ def capture_projects(candidates: list[ProjectCandidate]) -> list[SourceSnapshot]
168
168
 
169
169
  def validate_evidence(
170
170
  evidence: BusinessEvidence, projects: list[SourceSnapshot]
171
- ) -> str:
171
+ ) -> tuple[str, int, int]:
172
+ """The source lines that hold the excerpt, and their range.
173
+
174
+ The range is the cited one, or the nearest one within two lines that holds
175
+ the excerpt.
176
+ """
172
177
  project = next(
173
178
  (row for row in projects if row["projectId"] == evidence["projectId"]), None
174
179
  )
@@ -190,15 +195,42 @@ def validate_evidence(
190
195
  start, end = evidence["line"], evidence["endLine"]
191
196
  if end < start or end > len(lines):
192
197
  raise BusinessFlowError("evidence line range is invalid")
193
- source = lines[start - 1 : end]
194
- if not _excerpt_matches(evidence["excerpt"], source):
195
- raise BusinessFlowError(
196
- f"evidence excerpt does not match source: {evidence['path']}:{start}"
197
- )
198
- return "\n".join(source)
198
+ if not _excerpt_matches(evidence["excerpt"], lines[start - 1 : end]):
199
+ located = _nearby_range(evidence["excerpt"], lines, start, end)
200
+ if located is None:
201
+ raise BusinessFlowError(
202
+ f"evidence excerpt does not match source: {evidence['path']}:{start}"
203
+ )
204
+ start, end = located
205
+ return "\n".join(lines[start - 1 : end]), start, end
199
206
 
200
207
 
201
208
  _ELISION_MARKERS = {"...", "\u2026"}
209
+ _LINE_DRIFT = 2
210
+
211
+
212
+ def _nearby_range(
213
+ excerpt: str, lines: list[str], start: int, end: int
214
+ ) -> tuple[int, int] | None:
215
+ """The shortest, then closest, range within two lines of the cited one that
216
+ holds the excerpt.
217
+
218
+ Investigators copy the right lines but often count the range a line off. A
219
+ wider range also holds the excerpt, so the shortest one is where it is.
220
+ """
221
+ candidates = sorted(
222
+ (last - first, abs(first - start) + abs(last - end), first, last)
223
+ for first in range(max(1, start - _LINE_DRIFT), start + _LINE_DRIFT + 1)
224
+ for last in range(max(first, end - _LINE_DRIFT), min(len(lines), end + _LINE_DRIFT) + 1)
225
+ )
226
+ return next(
227
+ (
228
+ (first, last)
229
+ for _, _, first, last in candidates
230
+ if _excerpt_matches(excerpt, lines[first - 1 : last])
231
+ ),
232
+ None,
233
+ )
202
234
 
203
235
 
204
236
  def _excerpt_matches(excerpt: str, source: list[str]) -> bool:
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import re
4
4
  from collections import Counter
5
+ from collections.abc import Sequence
5
6
  from pathlib import Path
6
7
  from typing import Any, cast
7
8
 
@@ -29,6 +30,8 @@ from .source import candidate_projects, capture_project, knowledge_projects
29
30
 
30
31
  CONFIRMED_LEVELS = frozenset({"static", "execution-verified"})
31
32
  PACKET_CLAIM_LIMIT = 40
33
+ # Words every brief title or task id carries, which name no business.
34
+ _GENERIC_FOCUS_WORDS = frozenset({"task", "brief", "story", "feature", "with", "from", "that", "this"})
32
35
 
33
36
 
34
37
  def task_link_path(project_root: Path, task_key: str) -> Path:
@@ -141,7 +144,7 @@ def _claim(
141
144
 
142
145
 
143
146
  def _mark_conflicts(claims: list[StoredClaim]) -> None:
144
- groups: dict[str, list[StoredClaim]] = {}
147
+ groups: dict[tuple[str, str], list[StoredClaim]] = {}
145
148
  for claim in claims:
146
149
  if claim["level"] not in CONFIRMED_LEVELS or claim["status"] == "superseded":
147
150
  continue
@@ -149,10 +152,7 @@ def _mark_conflicts(claims: list[StoredClaim]) -> None:
149
152
  not row["digest"] for row in claim["sourceStates"].values()
150
153
  ):
151
154
  continue
152
- state = {key: row["digest"] for key, row in claim["sourceStates"].items()}
153
- groups.setdefault(
154
- fingerprint({"key": claim["key"], "states": state}), []
155
- ).append(claim)
155
+ groups.setdefault((claim["key"], _source_version(claim)), []).append(claim)
156
156
  for rows in groups.values():
157
157
  if len({row["value"] for row in rows}) > 1:
158
158
  for row in rows:
@@ -203,20 +203,16 @@ def validate_resolutions(
203
203
  "conflict resolution references unknown or repeated claims"
204
204
  )
205
205
  rows = _resolution_rows(data["claims"], resolution)
206
- state = fingerprint(
207
- {key: source["digest"] for key, source in rows[0]["sourceStates"].items()}
206
+ expected_ids = next(
207
+ (
208
+ {row["id"] for row in candidate}
209
+ for candidate in conflict_groups(data["claims"])
210
+ if candidate[0]["key"] == rows[0]["key"]
211
+ and _source_version(candidate[0]) == _source_version(rows[0])
212
+ ),
213
+ set(),
208
214
  )
209
- group = {
210
- row["id"]
211
- for row in data["claims"]
212
- if row["key"] == rows[0]["key"]
213
- and row["status"] == "conflict"
214
- and fingerprint(
215
- {key: source["digest"] for key, source in row["sourceStates"].items()}
216
- )
217
- == state
218
- }
219
- if ids != group:
215
+ if ids != expected_ids:
220
216
  raise BusinessFlowError(
221
217
  "conflict resolution must cover the complete active conflict"
222
218
  )
@@ -232,17 +228,24 @@ def _resolution_rows(
232
228
  if not ids.issubset(by_id) or resolution["acceptedClaimId"] not in ids:
233
229
  raise BusinessFlowError("conflict resolution references unknown claims")
234
230
  rows = [by_id[key] for key in ids]
235
- states = {
236
- fingerprint(
237
- {key: state["digest"] for key, state in row["sourceStates"].items()}
238
- )
239
- for row in rows
240
- }
241
- if len({row["key"] for row in rows}) != 1 or len(states) != 1:
231
+ if len({row["key"] for row in rows}) != 1 or len({_source_version(row) for row in rows}) != 1:
242
232
  raise BusinessFlowError("conflict resolution mixes subjects or source versions")
243
233
  return rows
244
234
 
245
235
 
236
+ def conflict_groups(claims: Sequence[StoredClaim]) -> list[list[StoredClaim]]:
237
+ """Claims in conflict on one key at one source version: what one resolution covers."""
238
+ groups: dict[tuple[str, str], dict[str, StoredClaim]] = {}
239
+ for claim in claims:
240
+ if claim["status"] == "conflict":
241
+ groups.setdefault((claim["key"], _source_version(claim)), {})[claim["id"]] = claim
242
+ return [list(group.values()) for group in groups.values()]
243
+
244
+
245
+ def _source_version(claim: StoredClaim) -> str:
246
+ return fingerprint({key: state["digest"] for key, state in claim["sourceStates"].items()})
247
+
248
+
246
249
  def read_shared_knowledge(project_root: Path, project_group: str) -> dict[str, Any]:
247
250
  claims, resolutions, errors = [], [], []
248
251
  candidates = knowledge_projects(
@@ -250,6 +253,9 @@ def read_shared_knowledge(project_root: Path, project_group: str) -> dict[str, A
250
253
  )
251
254
  for candidate in candidates:
252
255
  root = Path(candidate["root"])
256
+ # A project removed after it ran stays in run history; it has no store to read.
257
+ if not root.is_dir():
258
+ continue
253
259
  try:
254
260
  data = read_knowledge(root)
255
261
  claims.extend({**claim, "ownerRoot": str(root)} for claim in data["claims"])
@@ -387,17 +393,69 @@ def source_freshness(
387
393
  return "current" if source_states else "unverified"
388
394
 
389
395
 
396
+ def _words(text: str) -> set[str]:
397
+ return set(re.findall(r"[a-z0-9]+", text.casefold()))
398
+
399
+
400
+ def focus_terms(text: str) -> tuple[str, ...]:
401
+ """The words of a task's identity (task group, brief title) that can name a business."""
402
+ return tuple(sorted(
403
+ word for word in _words(text)
404
+ if len(word) >= 4 and not word.isdigit() and word not in _GENERIC_FOCUS_WORDS
405
+ ))
406
+
407
+
408
+ def task_focus(task_key: str, brief: str) -> tuple[str, ...]:
409
+ """The task group and the brief's title: what this task is about, without the brief's template."""
410
+ group = task_key.split(":")[1:2]
411
+ title = [line for line in brief.splitlines() if line.startswith("# ")][:1]
412
+ return focus_terms(" ".join([*group, *title]))
413
+
414
+
415
+ def _shares_stem(word: str, term: str) -> bool:
416
+ """Same word, its plural, or one a prefix of the other when both are long."""
417
+ if word == term or (min(len(word), len(term)) >= 4 and _singular(word) == _singular(term)):
418
+ return True
419
+ return min(len(word), len(term)) >= 6 and (word.startswith(term) or term.startswith(word))
420
+
421
+
422
+ def _singular(word: str) -> str:
423
+ return word[:-2] if word.endswith("es") and len(word) > 4 else word.removesuffix("s")
424
+
425
+
426
+ def _mentions(row: dict[str, Any], terms: Sequence[str]) -> bool:
427
+ words = _words(" ".join([row["business"], row["key"], row["value"], *row.get("aliases", [])]))
428
+ return any(_shares_stem(word, term) for word in words for term in terms)
429
+
430
+
431
+ def split_by_focus(
432
+ claims: list[dict[str, Any]], focus: Sequence[str]
433
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
434
+ """Claims that mention one of the task's focus terms, and the rest."""
435
+ focused = [row for row in claims if _mentions(row, focus)]
436
+ return focused, [row for row in claims if not _mentions(row, focus)]
437
+
438
+
390
439
  def knowledge_packet(
391
- project_root: Path, question: str, source_root: Path | None = None
440
+ project_root: Path, question: str, source_root: Path | None = None,
441
+ focus: Sequence[str] = (),
392
442
  ) -> str:
443
+ """The packet's knowledge section.
444
+
445
+ `question` is the whole brief, so its words select nearly every stored claim.
446
+ `focus` holds the task's identity terms;
447
+ when given, only claims that mention one of them are shown and the rest are
448
+ left to lookup.
449
+ """
393
450
  try:
394
451
  result = query_knowledge(project_root, question, source_root)
395
452
  except (OSError, BusinessFlowError, JsonBoundaryError) as exc:
396
453
  return f"## Shared Business Knowledge\n\nKnowledge unavailable: {exc}\n"
397
- # 질문이 task-brief 전체라 토큰 매칭이 거의 모든 claim 을 고르므로, 선택 결과는
398
- # 관련도 순위가 아니다. 이 프로젝트가 기록한 claim 을 앞세우고 나머지는 조회로 넘긴다.
399
454
  own = str(project_root.resolve())
400
455
  claims = sorted(result["claims"], key=lambda row: row["ownerRoot"] != own)
456
+ unrelated: list[dict[str, Any]] = []
457
+ if focus:
458
+ claims, unrelated = split_by_focus(claims, focus)
401
459
  shown, omitted = claims[:PACKET_CLAIM_LIMIT], claims[PACKET_CLAIM_LIMIT:]
402
460
  lines = [
403
461
  "## Shared Business Knowledge",
@@ -427,6 +485,14 @@ def knowledge_packet(
427
485
  f"- {len(omitted)} more selected claims are omitted; look them up by business: "
428
486
  + ", ".join(f"`{name}` ({count})" for name, count in counts.most_common())
429
487
  )
488
+ if unrelated:
489
+ counts = Counter(row["business"] for row in unrelated)
490
+ lines.append(
491
+ f"- {len(unrelated)} stored claims do not mention this task's terms ("
492
+ + ", ".join(f"`{term}`" for term in focus)
493
+ + "); look them up by business if one applies: "
494
+ + ", ".join(f"`{name}` ({count})" for name, count in counts.most_common())
495
+ )
430
496
  lines.extend(f"- Knowledge read error: {error}" for error in result["errors"])
431
497
  lines.extend(
432
498
  [
@@ -9,6 +9,7 @@ from dataclasses import dataclass
9
9
  from pathlib import Path, PurePosixPath
10
10
  from collections.abc import Mapping, Sequence
11
11
 
12
+ from .json_boundary import load_owned_object, write_owned_object_atomic
12
13
  from .review_verdicts import _table_fields, parse_review_census, read_review_census
13
14
 
14
15
  _GROUPS = ("structural", "semantic", "state-and-tests", "general")
@@ -114,6 +115,43 @@ def render_rule_catalog(text: str, parent: Path, *, include_architecture: bool =
114
115
  return "\n".join(rows)
115
116
 
116
117
 
118
+ def load_or_create_function_inventory(
119
+ path: Path, base: str, head: str, unresolved: tuple[str, ...],
120
+ ) -> dict[str, object]:
121
+ """The lead's function spans for the files whose boundaries the census cannot read.
122
+
123
+ A missing file is written as a template naming those files, and the call fails
124
+ until the lead fills it.
125
+ """
126
+ if not path.exists():
127
+ write_owned_object_atomic(path, {"base": base, "head": head,
128
+ "files": {name: None for name in unresolved}},
129
+ artifact="function inventory")
130
+ raise ValueError(f"complete the function inventory before dispatch: {path}")
131
+ payload = load_owned_object(path, artifact="function inventory")
132
+ if (set(payload) != {"base", "head", "files"} or payload["base"] != base
133
+ or payload["head"] != head or not isinstance(payload["files"], dict)
134
+ or set(payload["files"]) != set(unresolved)):
135
+ raise ValueError(f"function inventory must match this base, head and unresolved files: {path}")
136
+ return payload["files"]
137
+
138
+
139
+ def build_review_census_with_inventory(
140
+ repo: Path, base: str, head: str, rules_source: Path, changed: dict[str, set[int]],
141
+ inventory_path: Path | None, **inputs: object,
142
+ ) -> tuple[CensusResult, dict[str, object]]:
143
+ """The census, rebuilt with the lead's function inventory when boundaries are unresolved.
144
+
145
+ Returns the census and the inventory it used (empty when none was needed).
146
+ """
147
+ result = build_review_census(repo, base, head, rules_source, changed, **inputs)
148
+ if not result.unresolved or inventory_path is None:
149
+ return result, {}
150
+ inventory = load_or_create_function_inventory(inventory_path, base, head, result.unresolved)
151
+ return build_review_census(repo, base, head, rules_source, changed, inventory=inventory,
152
+ **inputs), inventory
153
+
154
+
117
155
  def _supplement_functions(
118
156
  repo: Path, head: str, path: str, lines: set[int], entry: object,
119
157
  ) -> list[str]:
@@ -6,7 +6,7 @@ from pathlib import Path
6
6
  from .agent.invocation import AgentInvocationError, verify_standalone_completion
7
7
  from .coverage_census import CellVerdicts
8
8
  from .json_boundary import load_owned_object
9
- from .review_verdicts import read_review_census, _head_tree, parse_review_verdicts
9
+ from .review_verdicts import binding_lines, read_review_census, _head_tree, parse_review_verdicts
10
10
 
11
11
 
12
12
  def check_review_coverage(
@@ -20,6 +20,7 @@ def check_review_coverage(
20
20
  if not completions or len(set(completions)) != len(completions):
21
21
  raise ValueError("pass distinct completion paths for one reviewer")
22
22
  bodies: list[str] = []
23
+ skipped = 0
23
24
  assignment: object = None
24
25
  for path in completions:
25
26
  verified = verify_standalone_completion(
@@ -35,9 +36,19 @@ def check_review_coverage(
35
36
  raise AgentInvocationError("coverage cannot mix reviewer model assignments")
36
37
  assignment = current
37
38
  heads = [line.removeprefix("Review head: ")
38
- for line in verified.returned_body.splitlines()
39
+ for line in binding_lines(verified.returned_body)
39
40
  if line.startswith("Review head: ")]
40
41
  if heads and heads != [tree.commit]:
41
- raise ValueError("completion review head differs from --head")
42
+ skipped += 1
43
+ continue
42
44
  bodies.append(verified.returned_body)
43
- return parse_review_verdicts(project_root, census, bodies, tree.commit, base=base)
45
+ if not bodies:
46
+ raise ValueError("completion review head differs from --head")
47
+ result = parse_review_verdicts(project_root, census, bodies, tree.commit, base=base)
48
+ if skipped:
49
+ note = f"; {skipped} completion(s) bound to another review head were left out"
50
+ result = CellVerdicts(result.verdicts,
51
+ {cell: reason + note for cell, reason in result.missing.items()},
52
+ result.unknown)
53
+ return result
54
+
@@ -155,11 +155,18 @@ def gap_fill_requests(
155
155
  continue
156
156
  if row.get("state") != "completed":
157
157
  continue
158
- missing = dict(row["audit"]["missing"])
158
+ after_gap_fill = item["attempt"] > 1 and item.get("kind") == "gap-fill"
159
+ if row["audit"].get("error"):
160
+ if after_gap_fill:
161
+ stopped.append(f"{team}/{axis}")
162
+ continue
163
+ missing = dict.fromkeys(own, f"attempt rejected: {row['audit']['error']}")
164
+ else:
165
+ missing = dict(row["audit"]["missing"])
159
166
  missing.update((cell, "rejected by the lead") for cell in rejects)
160
167
  if not missing:
161
168
  continue
162
- if item["attempt"] > 1 and item.get("kind") == "gap-fill" and len(row["audit"]["missing"]) >= len(own):
169
+ if after_gap_fill and len(row["audit"]["missing"]) >= len(own):
163
170
  stopped.append(f"{team}/{axis}")
164
171
  continue
165
172
  requests.append(AttemptRequest(team, axis, "gap-fill", tuple(sorted(missing)), missing))
@@ -229,6 +236,7 @@ def _prepare_item(
229
236
  from .agent.standalone import StandaloneInvocationRequest, prepare_standalone_invocation
230
237
  from .code_review_invocation import CodeReviewInputs
231
238
  from .registry.provider_registry import default_provider_registry
239
+ from .review_verdicts import read_review_census
232
240
 
233
241
  record, project, root = batch.record, batch.project, batch.root
234
242
  policy = batch.path(record["policy"])
@@ -247,7 +255,11 @@ def _prepare_item(
247
255
  f"- Specialist axis: {axis}\n"
248
256
  f"- Attempt: {attempt} ({kind})\n"
249
257
  f"- Full census (context only): {record['census']}\n"
250
- f"- Assigned census: {_relative(census, project)}\n\n"
258
+ f"- Assigned census: {_relative(census, project)}\n"
259
+ f"- Rules to account for: {', '.join(read_review_census(census).rules[axis])}. Rules of "
260
+ "other groups in the Rules table belong to other specialists: never list them in "
261
+ "Checked, N/A or Findings. Report a suspected issue under another group's rule as an "
262
+ "out-of-scope observation outside the Coverage Verdicts table.\n\n"
251
263
  f"{continuation}"
252
264
  f"## Inspection scope\n\n```text\n{scope}```\n"
253
265
  ))
@@ -11,7 +11,7 @@ from .agent.invocation import verify_standalone_completion
11
11
  from .fixed_text import scalar
12
12
  from .code_review_coverage import check_review_coverage
13
13
  from .review_verdicts import (
14
- ReviewCensus, _HeadTree, _head_tree, _table_fields, read_review_census,
14
+ ReviewCensus, _HeadTree, _head_tree, _table_fields, binding_lines, read_review_census,
15
15
  )
16
16
  from .verification_input_types import FrozenReviewPolicy
17
17
  from .qa_procedures import canonical_json_digest
@@ -92,8 +92,9 @@ def _prior_inputs(
92
92
  body = verify_standalone_completion(
93
93
  completion, project_root=root, expected_purpose="code-review",
94
94
  ).returned_body
95
+ lines = binding_lines(body)
95
96
  for line in baseline.splitlines():
96
- if body.splitlines().count(line) != 1:
97
+ if lines.count(line) != 1:
97
98
  raise ValueError("previous baseline missing or different")
98
99
  for cell, sources in _dependencies(body, census).items():
99
100
  dependencies.setdefault(cell, set()).update(sources)