knowledgevault 0.17.0__tar.gz → 0.17.3__tar.gz

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 (96) hide show
  1. {knowledgevault-0.17.0/knowledgevault.egg-info → knowledgevault-0.17.3}/PKG-INFO +4 -1
  2. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/README.md +3 -0
  3. {knowledgevault-0.17.0 → knowledgevault-0.17.3/knowledgevault.egg-info}/PKG-INFO +4 -1
  4. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/_version.py +1 -1
  5. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/check.py +32 -23
  6. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/operations.py +7 -3
  7. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/search.py +40 -27
  8. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/mcp/server.py +337 -95
  9. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/templates/AGENTS.md +5 -5
  10. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/pyproject.toml +1 -1
  11. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_check.py +23 -1
  12. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_mcp_surface.py +88 -0
  13. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_search_precision.py +51 -0
  14. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/LICENSE +0 -0
  15. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/MANIFEST.in +0 -0
  16. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/knowledgevault.egg-info/SOURCES.txt +0 -0
  17. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/knowledgevault.egg-info/dependency_links.txt +0 -0
  18. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/knowledgevault.egg-info/entry_points.txt +0 -0
  19. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/knowledgevault.egg-info/requires.txt +0 -0
  20. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/knowledgevault.egg-info/top_level.txt +0 -0
  21. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/__init__.py +0 -0
  22. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/__init__.py +0 -0
  23. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/_helpers.py +0 -0
  24. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/check.py +0 -0
  25. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/doctor.py +0 -0
  26. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/entity.py +0 -0
  27. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/events.py +0 -0
  28. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/journal.py +0 -0
  29. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/main.py +0 -0
  30. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/plan.py +0 -0
  31. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/render.py +0 -0
  32. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/search.py +0 -0
  33. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/summary.py +0 -0
  34. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/cli/validate.py +0 -0
  35. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/__init__.py +0 -0
  36. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/conventions.py +0 -0
  37. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/daily_artifacts.py +0 -0
  38. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/decisions.py +0 -0
  39. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/duplicates.py +0 -0
  40. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/events.py +0 -0
  41. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/frontmatter.py +0 -0
  42. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/locks.py +0 -0
  43. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/notes.py +0 -0
  44. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/observability.py +0 -0
  45. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/oplog.py +0 -0
  46. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/paths.py +0 -0
  47. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/plan.py +0 -0
  48. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/references.py +0 -0
  49. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/research.py +0 -0
  50. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/storage.py +0 -0
  51. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/structure.py +0 -0
  52. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/summary_quality.py +0 -0
  53. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/core/validation.py +0 -0
  54. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/mcp/__init__.py +0 -0
  55. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/py.typed +0 -0
  56. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/templates/__init__.py +0 -0
  57. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/templates/category_summary.md +0 -0
  58. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/templates/journal_entry.md +0 -0
  59. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/kvault/templates/root_summary.md +0 -0
  60. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/setup.cfg +0 -0
  61. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_api_exports.py +0 -0
  62. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_bounded_reads.py +0 -0
  63. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_check_filters.py +0 -0
  64. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_check_structure.py +0 -0
  65. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_cli_commands.py +0 -0
  66. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_cli_write_workflow.py +0 -0
  67. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_confirm_destructive.py +0 -0
  68. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_daily_artifacts.py +0 -0
  69. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_decisions.py +0 -0
  70. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_duplicates.py +0 -0
  71. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_e2e_workflows.py +0 -0
  72. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_events.py +0 -0
  73. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_frontmatter.py +0 -0
  74. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_log_cli.py +0 -0
  75. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_loose_visibility.py +0 -0
  76. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_mcp_server.py +0 -0
  77. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_mcp_structure.py +0 -0
  78. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_move_batch.py +0 -0
  79. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_naming_and_validate_kb.py +0 -0
  80. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_notes.py +0 -0
  81. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_operations.py +0 -0
  82. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_oplog.py +0 -0
  83. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_output_channels.py +0 -0
  84. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_patches.py +0 -0
  85. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_path_safety_and_locks.py +0 -0
  86. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_paths_and_digest_guards.py +0 -0
  87. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_plan.py +0 -0
  88. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_references.py +0 -0
  89. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_research.py +0 -0
  90. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_stale.py +0 -0
  91. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_storage.py +0 -0
  92. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_structure.py +0 -0
  93. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_summary_quality.py +0 -0
  94. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_work_reporting.py +0 -0
  95. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_write_guards.py +0 -0
  96. {knowledgevault-0.17.0 → knowledgevault-0.17.3}/tests/test_write_integrity.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: knowledgevault
3
- Version: 0.17.0
3
+ Version: 0.17.3
4
4
  Summary: CLI-first personal knowledge base for AI agents — structured, navigable, zero extra cost
5
5
  Author: Eddie Landesberg
6
6
  License-Expression: MIT
@@ -387,6 +387,9 @@ ancestor's path, title, and first line, where `parents="all"` attaches every anc
387
387
  document to every hit (capped by `total_max_chars`).
388
388
  `kvault_read_nodes` reads up to 25 picked hits in one call under one budget that counts whole
389
389
  nodes (3,500 characters by default over MCP; raise it when the client can take more).
390
+ `kvault_status` and `kvault_search` keep their results under `max_chars` the same way (0.17.1);
391
+ `kvault_check` returns `findings` once, without the CLI document's per-category copies, and
392
+ `kvault_validate_kb` carries each issue type's message and fix once.
390
393
 
391
394
  ## It's just files
392
395
 
@@ -350,6 +350,9 @@ ancestor's path, title, and first line, where `parents="all"` attaches every anc
350
350
  document to every hit (capped by `total_max_chars`).
351
351
  `kvault_read_nodes` reads up to 25 picked hits in one call under one budget that counts whole
352
352
  nodes (3,500 characters by default over MCP; raise it when the client can take more).
353
+ `kvault_status` and `kvault_search` keep their results under `max_chars` the same way (0.17.1);
354
+ `kvault_check` returns `findings` once, without the CLI document's per-category copies, and
355
+ `kvault_validate_kb` carries each issue type's message and fix once.
353
356
 
354
357
  ## It's just files
355
358
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: knowledgevault
3
- Version: 0.17.0
3
+ Version: 0.17.3
4
4
  Summary: CLI-first personal knowledge base for AI agents — structured, navigable, zero extra cost
5
5
  Author: Eddie Landesberg
6
6
  License-Expression: MIT
@@ -387,6 +387,9 @@ ancestor's path, title, and first line, where `parents="all"` attaches every anc
387
387
  document to every hit (capped by `total_max_chars`).
388
388
  `kvault_read_nodes` reads up to 25 picked hits in one call under one budget that counts whole
389
389
  nodes (3,500 characters by default over MCP; raise it when the client can take more).
390
+ `kvault_status` and `kvault_search` keep their results under `max_chars` the same way (0.17.1);
391
+ `kvault_check` returns `findings` once, without the CLI document's per-category copies, and
392
+ `kvault_validate_kb` carries each issue type's message and fix once.
390
393
 
391
394
  ## It's just files
392
395
 
@@ -13,6 +13,6 @@ try:
13
13
  __version__ = _distribution_version("knowledgevault")
14
14
  except PackageNotFoundError:
15
15
  # Uninstalled source tree only; keep in sync with pyproject.toml.
16
- __version__ = "0.17.0"
16
+ __version__ = "0.17.3"
17
17
 
18
18
  __all__ = ["__version__"]
@@ -146,20 +146,20 @@ def _get_updated_date(path: Path) -> Optional[date]:
146
146
  return None
147
147
 
148
148
 
149
- def _find_entities(kb_root: Path) -> List[Path]:
150
- """All entity ``_summary.md`` files (leaf nodes at depth >= 3)."""
149
+ def _find_entities(kb_root: Path, ignore: Optional[Sequence[str]] = None) -> List[Path]:
150
+ """Entity ``_summary.md`` files: leaf nodes at least two levels down.
151
+
152
+ Managed directories only (0.17.1): paths in ``.kvaultignore`` and the
153
+ reserved names (``journal/``, ``deep_context/``) are skipped, as every
154
+ other check skips them.
155
+ """
156
+ patterns = list(ignore) if ignore is not None else st.load_ignore(kb_root)
151
157
  entities = []
152
- for summary in kb_root.rglob(st.SUMMARY_NAME):
153
- parent_dir = summary.parent
154
- rel_path = summary.relative_to(kb_root)
155
- if parent_dir == kb_root or len(rel_path.parts) < 3:
158
+ for node_dir in st.walk_dirs(kb_root, patterns):
159
+ summary = node_dir / st.SUMMARY_NAME
160
+ if not summary.is_file() or len(summary.relative_to(kb_root).parts) < 3:
156
161
  continue
157
- has_child_summaries = any(
158
- (child / st.SUMMARY_NAME).exists()
159
- for child in parent_dir.iterdir()
160
- if child.is_dir() and not child.name.startswith(".")
161
- )
162
- if not has_child_summaries:
162
+ if not any(st.has_summary(c) for c in st.child_dirs(node_dir, kb_root, patterns)):
163
163
  entities.append(summary)
164
164
  return entities
165
165
 
@@ -174,9 +174,17 @@ def _node_dirs(kb_root: Path, ignore: Sequence[str]) -> List[Path]:
174
174
  # -- hard findings -----------------------------------------------------------
175
175
 
176
176
 
177
- def propagation_findings(kb_root: Path, threshold_minutes: int) -> List[Finding]:
177
+ def propagation_findings(
178
+ kb_root: Path, threshold_minutes: int, ignore: Optional[Sequence[str]] = None
179
+ ) -> List[Finding]:
178
180
  """Parents should be at least as recent as their children.
179
181
 
182
+ Managed directories only (0.17.1): a path in ``.kvaultignore`` or under
183
+ a reserved name (``journal/``, ``deep_context/``) is neither a parent
184
+ nor a child here, as in every other check. The walk used to cover every
185
+ summary file, so a custom journal layout the owner had ignored was still
186
+ reported, and a node's own ``deep_context/`` notes counted as a child.
187
+
180
188
  Frontmatter ``updated`` dates first (they survive git); mtime with the
181
189
  threshold as the fallback when either side has no date. Equal days use
182
190
  mtime too, because ``updated`` has day granularity: a child edited after
@@ -188,14 +196,15 @@ def propagation_findings(kb_root: Path, threshold_minutes: int) -> List[Finding]
188
196
  """
189
197
  findings: List[Finding] = []
190
198
  threshold = timedelta(minutes=threshold_minutes)
191
- for summary in kb_root.rglob(st.SUMMARY_NAME):
192
- parent_dir = summary.parent
199
+ patterns = list(ignore) if ignore is not None else st.load_ignore(kb_root)
200
+ for parent_dir in _node_dirs(kb_root, patterns):
201
+ summary = parent_dir / st.SUMMARY_NAME
202
+ if not summary.is_file():
203
+ continue # the root without a summary: nothing to compare against
193
204
  children = [
194
205
  child_dir / st.SUMMARY_NAME
195
- for child_dir in parent_dir.iterdir()
196
- if child_dir.is_dir()
197
- and not child_dir.name.startswith(".")
198
- and (child_dir / st.SUMMARY_NAME).exists()
206
+ for child_dir in st.child_dirs(parent_dir, kb_root, patterns)
207
+ if st.has_summary(child_dir)
199
208
  ]
200
209
  if not children:
201
210
  continue
@@ -237,10 +246,10 @@ def propagation_findings(kb_root: Path, threshold_minutes: int) -> List[Finding]
237
246
  return findings
238
247
 
239
248
 
240
- def journal_findings(kb_root: Path) -> List[Finding]:
249
+ def journal_findings(kb_root: Path, ignore: Optional[Sequence[str]] = None) -> List[Finding]:
241
250
  """Entities modified today need a journal entry today."""
242
251
  today = date.today()
243
- modified = [e for e in _find_entities(kb_root) if _get_mtime(e).date() == today]
252
+ modified = [e for e in _find_entities(kb_root, ignore) if _get_mtime(e).date() == today]
244
253
  if not modified:
245
254
  return []
246
255
  journal_file = kb_root / "journal" / today.strftime("%Y-%m") / "log.md"
@@ -769,9 +778,9 @@ def run_checks(
769
778
 
770
779
  hard: List[Finding] = []
771
780
  if wanted("PROPAGATE"):
772
- hard.extend(propagation_findings(root, threshold_minutes))
781
+ hard.extend(propagation_findings(root, threshold_minutes, ignore))
773
782
  if wanted("LOG"):
774
- hard.extend(journal_findings(root))
783
+ hard.extend(journal_findings(root, ignore))
775
784
  if wanted("WRITE"):
776
785
  hard.extend(frontmatter_findings(root))
777
786
  if wanted("BRANCH"):
@@ -969,12 +969,16 @@ def _join_path(parent: str, name: str) -> str:
969
969
  # ---------------------------------------------------------------------------
970
970
 
971
971
 
972
- def get_kb_info(kg_root: Path, include_root_summary: bool = False) -> Dict[str, Any]:
972
+ def get_kb_info(
973
+ kg_root: Path, include_root_summary: bool = False, hierarchy: bool = True
974
+ ) -> Dict[str, Any]:
973
975
  """Return version, hierarchy, entity count, and (opt-in) root summary.
974
976
 
975
977
  ``root_summary`` is opt-in since 0.14.0: on a mature KB it was ~97% of a
976
978
  56 KB status payload that agents read at session start. The size is
977
- always reported so a caller can decide whether to fetch it.
979
+ always reported so a caller can decide whether to fetch it. With
980
+ *hierarchy* False the outline is left empty for the caller to render
981
+ under its own budget (the MCP status tool, 0.17.1).
978
982
  """
979
983
  root_summary_path = kg_root / "_summary.md"
980
984
  root_summary = (
@@ -982,7 +986,7 @@ def get_kb_info(kg_root: Path, include_root_summary: bool = False) -> Dict[str,
982
986
  if root_summary_path.exists() and st.inside_root(root_summary_path, kg_root)
983
987
  else ""
984
988
  )
985
- outline = build_outline(kg_root, depth=2)
989
+ outline = build_outline(kg_root, depth=2) if hierarchy else None
986
990
  info: Dict[str, Any] = {
987
991
  "version": __version__,
988
992
  "kg_root": str(kg_root),
@@ -226,7 +226,7 @@ def search_nodes(
226
226
  title=doc.title,
227
227
  score=round(score, 3),
228
228
  matched_fields=sorted(matched_fields),
229
- snippet=_snippet(doc, query, query_tokens, max_chars=snippet_max),
229
+ snippet=_snippet(doc, query_tokens, max_chars=snippet_max),
230
230
  summary_path=doc.summary_path,
231
231
  last_updated=doc.last_updated,
232
232
  content=content,
@@ -651,39 +651,52 @@ def _idf(documents: Sequence[SearchDocument], query_tokens: Sequence[str]) -> Di
651
651
 
652
652
  def _snippet(
653
653
  doc: SearchDocument,
654
- query: str,
655
654
  query_tokens: Sequence[str],
656
655
  max_chars: int = _SNIPPET_MAX_CHARS,
657
656
  ) -> str:
658
- text = re.sub(r"\s+", " ", doc.content).strip()
659
657
  if max_chars <= 0:
660
658
  return ""
661
- if not text:
662
- return doc.title[:max_chars]
663
- haystack = text.lower()
664
- needle = query.lower().strip()
665
- idx = haystack.find(needle) if needle else -1
666
- if idx < 0:
667
- token_positions = [
668
- haystack.find(token) for token in query_tokens if haystack.find(token) >= 0
669
- ]
670
- idx = min(token_positions) if token_positions else 0
671
-
659
+ text = re.sub(r"\s+", " ", doc.content.strip() or doc.title).strip()
672
660
  if len(text) <= max_chars:
673
661
  return text
674
- if max_chars < 8:
675
- return text[:max_chars]
676
- # The "..." markers count toward max_chars: a 120-character snippet is 120.
677
- width = max_chars - 6
678
- start = max(0, idx - width // 3)
679
- end = min(len(text), start + width)
680
- start = max(0, end - width)
681
- snippet = text[start:end].strip()
682
- if start > 0:
683
- snippet = "..." + snippet
684
- if end < len(text):
685
- snippet += "..."
686
- return snippet
662
+ marker = "..."
663
+ if max_chars <= len(marker):
664
+ return marker[:max_chars]
665
+
666
+ # Match the same ASCII tokens and intervening punctuation as the scorer.
667
+ # A raw substring would anchor "paid invoice" inside "unpaid invoice".
668
+ def match_tokens(pattern: str) -> Optional[re.Match[str]]:
669
+ return re.search(r"(?<![a-z0-9])(?:" + pattern + r")(?![a-z0-9])", text, re.I | re.ASCII)
670
+
671
+ match = match_tokens(r"[^a-z0-9]+".join(query_tokens))
672
+ if match is None and len(query_tokens) > 1:
673
+ match = match_tokens("|".join(query_tokens))
674
+ first, last = match.span() if match else (0, 0)
675
+ if match:
676
+ # Keep punctuation attached to the final matching word in the budget.
677
+ after_word = text.find(" ", last)
678
+ last = len(text) if after_word < 0 else after_word
679
+
680
+ # Start around a third of a window before the match. Keep whole source
681
+ # words, including a hyphen or sign attached to them, at both cut edges.
682
+ width = max(1, max_chars - 2 * len(marker))
683
+ preferred = max(0, min(first - width // 3, len(text) - width))
684
+ start = text.rfind(" ", 0, preferred + 1) + 1
685
+ # A long preceding word or phrase may otherwise push the match offscreen.
686
+ earliest = max(0, min(first, last - width))
687
+ if start < earliest:
688
+ boundary = text.find(" ", earliest - 1, first)
689
+ if boundary >= 0:
690
+ start = boundary + 1
691
+ prefix = marker if start else ""
692
+ end = start + max_chars - len(prefix)
693
+ if end >= len(text):
694
+ return prefix + text[start:]
695
+ end -= len(marker)
696
+ end = text.rfind(" ", start, end + 1)
697
+ if end <= start:
698
+ return marker
699
+ return prefix + text[start:end] + marker
687
700
 
688
701
 
689
702
  def _truncate(text: str, max_chars: int) -> Tuple[str, bool]: