okstra 0.235.0 → 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 (68) hide show
  1. package/dist/lib/host-registry-client.d.mts +9 -2
  2. package/dist/lib/host-registry-client.mjs +29 -3
  3. package/dist/lib/host-registry-client.mjs.map +1 -1
  4. package/dist/lib/runtime-payload.mjs +1 -0
  5. package/dist/lib/runtime-payload.mjs.map +1 -1
  6. package/docs/architecture.md +1 -1
  7. package/docs/cli.md +6 -0
  8. package/package.json +1 -1
  9. package/runtime/BUILD.json +2 -2
  10. package/runtime/bin/lib/okstra/usage.sh +8 -8
  11. package/runtime/bin/okstra-qwen-exec.sh +5 -0
  12. package/runtime/prompts/lead/convergence.md +4 -1
  13. package/runtime/prompts/lead/okstra-lead-contract.md +3 -3
  14. package/runtime/prompts/profiles/_common-contract.md +10 -1
  15. package/runtime/prompts/wizard/prompts.ko.json +16 -4
  16. package/runtime/python/okstra_ctl/adapters/providers/antigravity/adapter.py +10 -2
  17. package/runtime/python/okstra_ctl/adapters/providers/claude/adapter.py +16 -1
  18. package/runtime/python/okstra_ctl/adapters/providers/codex/adapter.py +20 -5
  19. package/runtime/python/okstra_ctl/adapters/providers/kimi/adapter.py +17 -9
  20. package/runtime/python/okstra_ctl/adapters/providers/qwen/adapter.py +88 -0
  21. package/runtime/python/okstra_ctl/adapters/providers/qwen/manifest.json +1 -0
  22. package/runtime/python/okstra_ctl/adapters/providers/qwen/settings.json +12 -0
  23. package/runtime/python/okstra_ctl/adapters/providers/zai/adapter.py +8 -2
  24. package/runtime/python/okstra_ctl/business_flow/contracts.py +11 -0
  25. package/runtime/python/okstra_ctl/business_flow/engine.py +90 -32
  26. package/runtime/python/okstra_ctl/business_flow/hooks.py +4 -2
  27. package/runtime/python/okstra_ctl/business_flow/source.py +39 -7
  28. package/runtime/python/okstra_ctl/business_flow/store.py +94 -28
  29. package/runtime/python/okstra_ctl/convergence.py +95 -5
  30. package/runtime/python/okstra_ctl/convergence_critic_verify_prompt.py +11 -10
  31. package/runtime/python/okstra_ctl/convergence_engine.py +30 -15
  32. package/runtime/python/okstra_ctl/convergence_reverify_prompt.py +9 -2
  33. package/runtime/python/okstra_ctl/coverage_census.py +75 -12
  34. package/runtime/python/okstra_ctl/entrypoints/hosts.py +1 -1
  35. package/runtime/python/okstra_ctl/lead_progress.py +1 -1
  36. package/runtime/python/okstra_ctl/model_discovery.py +1 -1
  37. package/runtime/python/okstra_ctl/models.py +2 -2
  38. package/runtime/python/okstra_ctl/phases/discussion/profile.md +2 -2
  39. package/runtime/python/okstra_ctl/phases/error_analysis/profile.md +1 -1
  40. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  41. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +2 -1
  42. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +1 -1
  43. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +3 -3
  44. package/runtime/python/okstra_ctl/phases/requirements_discovery/profile.md +5 -5
  45. package/runtime/python/okstra_ctl/registry/provider_registry.py +1 -1
  46. package/runtime/python/okstra_ctl/render_final_report.py +1 -1
  47. package/runtime/python/okstra_ctl/run.py +1 -1
  48. package/runtime/python/okstra_ctl/run_context.py +18 -3
  49. package/runtime/python/okstra_ctl/schema_excerpt.py +14 -9
  50. package/runtime/python/okstra_ctl/verdict_blocks.py +7 -2
  51. package/runtime/python/okstra_ctl/wizard/engine.py +28 -1
  52. package/runtime/python/okstra_ctl/wizard/ids.py +8 -0
  53. package/runtime/python/okstra_ctl/wizard/picker_navigation.py +64 -2
  54. package/runtime/python/okstra_ctl/wizard/roles.py +194 -45
  55. package/runtime/python/okstra_ctl/wizard/sources.py +10 -1
  56. package/runtime/python/okstra_ctl/wizard/state.py +67 -20
  57. package/runtime/python/okstra_ctl/wizard/steps_roles.py +6 -3
  58. package/runtime/python/okstra_ctl/wizard/worker_settings.py +129 -25
  59. package/runtime/python/okstra_ctl/worker_audit_ledger.py +44 -8
  60. package/runtime/python/okstra_ctl/worker_prompt_body.py +26 -2
  61. package/runtime/python/okstra_ctl/worker_prompt_headers.py +12 -9
  62. package/runtime/python/okstra_token_usage/claude.py +5 -1
  63. package/runtime/python/okstra_token_usage/collect.py +3 -3
  64. package/runtime/python/okstra_token_usage/pricing.py +1 -0
  65. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  66. package/runtime/skills/okstra-discussion/SKILL.md +1 -1
  67. package/runtime/skills/okstra-run/SKILL.md +2 -2
  68. package/runtime/templates/worker-prompt-preamble.md +12 -2
@@ -0,0 +1,12 @@
1
+ {
2
+ "modelProviders": {
3
+ "openai": [
4
+ {
5
+ "id": "qwen4-max",
6
+ "envKey": "OKSTRA_QWEN_API_KEY",
7
+ "baseUrl": "${OKSTRA_QWEN_ENDPOINT}"
8
+ }
9
+ ]
10
+ },
11
+ "$version": 4
12
+ }
@@ -25,6 +25,8 @@ ZAI_MODELS = {
25
25
  for name, label, pricing in (
26
26
  ("glm-5.3", "GLM-5.3", (1.40, 0.26, 4.40)),
27
27
  ("glm-5.3-flash", "GLM-5.3 Flash", (0.15, 0.03, 0.50)),
28
+ ("glm-5.3-flashx", "GLM-5.3 FlashX", (0.37, 0.075, 1.25)),
29
+ ("glm-5.3-flashx-legal", "GLM-5.3 FlashX Legal", (0.37, 0.075, 1.25)),
28
30
  )
29
31
  }
30
32
 
@@ -88,10 +90,14 @@ class ZaiExecution:
88
90
  command = ClaudeExecution().build_command(
89
91
  replace(request, reasoning_effort="")
90
92
  )
93
+ argv = list(command.argv)
94
+ index = argv.index("--setting-sources")
95
+ # No setting source at all, so a settings file's env cannot override the
96
+ # child environment below.
97
+ argv[index + 1] = ""
91
98
  return replace(
92
99
  command,
93
- # 설정 파일의 env 가 자식 환경을 다시 덮어쓰지 않게 한다.
94
- argv=(*command.argv, "--setting-sources", ""),
100
+ argv=tuple(argv),
95
101
  environment={
96
102
  "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic",
97
103
  "ANTHROPIC_AUTH_TOKEN": api_key,
@@ -10,6 +10,7 @@ from typing import Any, Literal, TypedDict
10
10
  from ..report_language import resolve_report_language
11
11
  from ..json_boundary import load_owned_object, write_owned_object_atomic
12
12
  from ..paths import find_asset_root
13
+ from ..schema_excerpt import reachable_defs
13
14
  from ..report_language import is_language_tag
14
15
 
15
16
  OPERATION = "explain-flow"
@@ -267,6 +268,16 @@ def schema_definition(name: str) -> dict[str, Any]:
267
268
  return {"$ref": f"#/$defs/{name}", "$defs": schema["$defs"]}
268
269
 
269
270
 
271
+ def prompt_schema(name: str) -> dict[str, Any]:
272
+ """`schema_definition` with only the definitions `name` reaches through
273
+ `$ref`; the stored records (claims, executions, task links) are not part of
274
+ what a model returns."""
275
+ schema = schema_definition(name)
276
+ defs = schema["$defs"]
277
+ kept = reachable_defs(defs, {"$ref": schema["$ref"]})
278
+ return {**schema, "$defs": {key: defs[key] for key in defs if key in kept}}
279
+
280
+
270
281
  def read_artifact(path: Path, name: str) -> dict[str, Any]:
271
282
  return load_owned_object(
272
283
  path, artifact=f"business flow {name}", schema=schema_definition(name)
@@ -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
  [