lexicon-kb 0.1.0__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 (97) hide show
  1. lexicon_kb-0.1.0/LICENSE +21 -0
  2. lexicon_kb-0.1.0/PKG-INFO +99 -0
  3. lexicon_kb-0.1.0/README.md +75 -0
  4. lexicon_kb-0.1.0/pyproject.toml +50 -0
  5. lexicon_kb-0.1.0/setup.cfg +4 -0
  6. lexicon_kb-0.1.0/src/lexicon/__init__.py +8 -0
  7. lexicon_kb-0.1.0/src/lexicon/__main__.py +6 -0
  8. lexicon_kb-0.1.0/src/lexicon/capture/__init__.py +249 -0
  9. lexicon_kb-0.1.0/src/lexicon/capture/formats.py +410 -0
  10. lexicon_kb-0.1.0/src/lexicon/capture/sanitize.py +77 -0
  11. lexicon_kb-0.1.0/src/lexicon/capture/store.py +186 -0
  12. lexicon_kb-0.1.0/src/lexicon/cli.py +73 -0
  13. lexicon_kb-0.1.0/src/lexicon/commands/__init__.py +1 -0
  14. lexicon_kb-0.1.0/src/lexicon/commands/capture.py +69 -0
  15. lexicon_kb-0.1.0/src/lexicon/commands/doctor.py +47 -0
  16. lexicon_kb-0.1.0/src/lexicon/commands/fireflies.py +60 -0
  17. lexicon_kb-0.1.0/src/lexicon/commands/hidock.py +55 -0
  18. lexicon_kb-0.1.0/src/lexicon/commands/index.py +46 -0
  19. lexicon_kb-0.1.0/src/lexicon/commands/info.py +36 -0
  20. lexicon_kb-0.1.0/src/lexicon/commands/init.py +154 -0
  21. lexicon_kb-0.1.0/src/lexicon/commands/lint.py +40 -0
  22. lexicon_kb-0.1.0/src/lexicon/commands/mcp.py +30 -0
  23. lexicon_kb-0.1.0/src/lexicon/commands/read.py +76 -0
  24. lexicon_kb-0.1.0/src/lexicon/commands/search.py +42 -0
  25. lexicon_kb-0.1.0/src/lexicon/commands/setup.py +75 -0
  26. lexicon_kb-0.1.0/src/lexicon/commands/sync.py +447 -0
  27. lexicon_kb-0.1.0/src/lexicon/commands/template.py +44 -0
  28. lexicon_kb-0.1.0/src/lexicon/commands/triage.py +250 -0
  29. lexicon_kb-0.1.0/src/lexicon/config.py +148 -0
  30. lexicon_kb-0.1.0/src/lexicon/doctor.py +524 -0
  31. lexicon_kb-0.1.0/src/lexicon/errors.py +15 -0
  32. lexicon_kb-0.1.0/src/lexicon/index.py +364 -0
  33. lexicon_kb-0.1.0/src/lexicon/lint.py +1007 -0
  34. lexicon_kb-0.1.0/src/lexicon/mcp_server.py +456 -0
  35. lexicon_kb-0.1.0/src/lexicon/note_templates.py +55 -0
  36. lexicon_kb-0.1.0/src/lexicon/obsidian_git.py +149 -0
  37. lexicon_kb-0.1.0/src/lexicon/plugins/__init__.py +22 -0
  38. lexicon_kb-0.1.0/src/lexicon/plugins/fireflies.py +399 -0
  39. lexicon_kb-0.1.0/src/lexicon/plugins/hidock.py +291 -0
  40. lexicon_kb-0.1.0/src/lexicon/qmd_pin.py +16 -0
  41. lexicon_kb-0.1.0/src/lexicon/search.py +338 -0
  42. lexicon_kb-0.1.0/src/lexicon/setup.py +970 -0
  43. lexicon_kb-0.1.0/src/lexicon/sync.py +328 -0
  44. lexicon_kb-0.1.0/src/lexicon/templates/notes/clipping.md +13 -0
  45. lexicon_kb-0.1.0/src/lexicon/templates/notes/decision.md +38 -0
  46. lexicon_kb-0.1.0/src/lexicon/templates/notes/idea.md +12 -0
  47. lexicon_kb-0.1.0/src/lexicon/templates/notes/lens.md +17 -0
  48. lexicon_kb-0.1.0/src/lexicon/templates/notes/meeting.md +44 -0
  49. lexicon_kb-0.1.0/src/lexicon/templates/notes/resources.md +47 -0
  50. lexicon_kb-0.1.0/src/lexicon/templates/notes/synthesis.md +30 -0
  51. lexicon_kb-0.1.0/src/lexicon/templates/vault/evidence_README.md +5 -0
  52. lexicon_kb-0.1.0/src/lexicon/templates/vault/gitignore +9 -0
  53. lexicon_kb-0.1.0/src/lexicon/templates/vault/metadata_README.md +7 -0
  54. lexicon_kb-0.1.0/src/lexicon/templates/vault/objectives.md +11 -0
  55. lexicon_kb-0.1.0/src/lexicon/templates/vault/sources_README.md +11 -0
  56. lexicon_kb-0.1.0/src/lexicon/templates/vault/synthesis_README.md +10 -0
  57. lexicon_kb-0.1.0/src/lexicon/triage/__init__.py +9 -0
  58. lexicon_kb-0.1.0/src/lexicon/triage/apply.py +104 -0
  59. lexicon_kb-0.1.0/src/lexicon/triage/approval.py +460 -0
  60. lexicon_kb-0.1.0/src/lexicon/triage/logs.py +86 -0
  61. lexicon_kb-0.1.0/src/lexicon/triage/plan.py +573 -0
  62. lexicon_kb-0.1.0/src/lexicon/triage/policy.py +13 -0
  63. lexicon_kb-0.1.0/src/lexicon/triage/queue.py +209 -0
  64. lexicon_kb-0.1.0/src/lexicon/triage/records.py +92 -0
  65. lexicon_kb-0.1.0/src/lexicon/triage/submit.py +174 -0
  66. lexicon_kb-0.1.0/src/lexicon/vault.py +328 -0
  67. lexicon_kb-0.1.0/src/lexicon/writes.py +144 -0
  68. lexicon_kb-0.1.0/src/lexicon_kb.egg-info/PKG-INFO +99 -0
  69. lexicon_kb-0.1.0/src/lexicon_kb.egg-info/SOURCES.txt +95 -0
  70. lexicon_kb-0.1.0/src/lexicon_kb.egg-info/dependency_links.txt +1 -0
  71. lexicon_kb-0.1.0/src/lexicon_kb.egg-info/entry_points.txt +2 -0
  72. lexicon_kb-0.1.0/src/lexicon_kb.egg-info/top_level.txt +1 -0
  73. lexicon_kb-0.1.0/tests/test_approval.py +505 -0
  74. lexicon_kb-0.1.0/tests/test_area_resolution.py +142 -0
  75. lexicon_kb-0.1.0/tests/test_capture.py +741 -0
  76. lexicon_kb-0.1.0/tests/test_config.py +150 -0
  77. lexicon_kb-0.1.0/tests/test_docs_commands.py +100 -0
  78. lexicon_kb-0.1.0/tests/test_doctor.py +859 -0
  79. lexicon_kb-0.1.0/tests/test_fixture_vault.py +42 -0
  80. lexicon_kb-0.1.0/tests/test_init.py +165 -0
  81. lexicon_kb-0.1.0/tests/test_install_sh.py +389 -0
  82. lexicon_kb-0.1.0/tests/test_lint.py +687 -0
  83. lexicon_kb-0.1.0/tests/test_mcp.py +741 -0
  84. lexicon_kb-0.1.0/tests/test_plugin_fireflies.py +409 -0
  85. lexicon_kb-0.1.0/tests/test_plugin_hidock.py +203 -0
  86. lexicon_kb-0.1.0/tests/test_read_paths.py +153 -0
  87. lexicon_kb-0.1.0/tests/test_release.py +453 -0
  88. lexicon_kb-0.1.0/tests/test_root.py +254 -0
  89. lexicon_kb-0.1.0/tests/test_search.py +587 -0
  90. lexicon_kb-0.1.0/tests/test_search_qmd.py +109 -0
  91. lexicon_kb-0.1.0/tests/test_setup.py +1616 -0
  92. lexicon_kb-0.1.0/tests/test_sync.py +506 -0
  93. lexicon_kb-0.1.0/tests/test_template.py +101 -0
  94. lexicon_kb-0.1.0/tests/test_timer.py +478 -0
  95. lexicon_kb-0.1.0/tests/test_triage.py +856 -0
  96. lexicon_kb-0.1.0/tests/test_version.py +178 -0
  97. lexicon_kb-0.1.0/tests/test_writes.py +140 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 not-so-fat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: lexicon-kb
3
+ Version: 0.1.0
4
+ Summary: Lexicon engine: local Markdown knowledge base for agents
5
+ Author: not-so-fat
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/not-so-fat/lexicon
8
+ Project-URL: Repository, https://github.com/not-so-fat/lexicon
9
+ Project-URL: Changelog, https://github.com/not-so-fat/lexicon/blob/main/CHANGELOG.md
10
+ Keywords: knowledge-base,markdown,agents,notes,search
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Documentation
19
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ # Lexicon
26
+
27
+ **Knowledge base with AI agents, especially for dynamic knowledge**
28
+
29
+ We come across a lot of knowledge through different activities.
30
+
31
+ - Work with AI agents
32
+ - Our own notes
33
+ - Messages
34
+ - Meetings and chats
35
+ - URLs we or our friends are interested in
36
+
37
+ Our AI agents should help us organize this knowledge, and they should get much stronger with it.
38
+ Especially when we want to clone ourselves as agents, this knowledge is critical input for them to work.
39
+
40
+ The key insight comes from [Zettelkasten](https://zettelkasten.de/overview/), a knowledge management methodology.
41
+
42
+ ## Principles
43
+
44
+ - Dump any data (missing data is more costly).
45
+ - Split source data (the dump) and curated data (for long-term search).
46
+ - Search curated data first. Go back to the source when we need more detail or missed something.
47
+ - Manage knowledge as statements. A statement is one claim or observation we can understand and check on its own.
48
+ - Organize statements into different areas. An area is a named domain of knowledge, such as a project or a recurring subject.
49
+
50
+ Memory = Knowledge (facts about the world) + Operational insights (how to work, records, state, rules). Across agents, share knowledge in Lexicon and how-to-work in Agent Deck playbooks. Everything else stays per-agent. Lexicon is the local Markdown knowledge base. Agent state, operating rules, and work tracking live outside it.
51
+
52
+ ## Solution Idea
53
+
54
+ 1. Data is dumped into the `Sources/` directory.
55
+ - Meeting transcripts
56
+ - Notes by humans and agents
57
+ - Clips from websites
58
+ - Agent chats
59
+ 2. Facts are accumulated in append-only `Evidence/`.
60
+ - Project decisions
61
+ - People
62
+ 3. Periodically, the owner reviews important decisions and adds, modifies, or deletes entries in `Synthesis/`.
63
+ - Directions
64
+ - Objectives
65
+
66
+ ## Key structure
67
+
68
+ | Layer | Path | Purpose |
69
+ | --- | --- | --- |
70
+ | Sources | `Sources/Chats/`, `Sources/Ideas/`, `Sources/Meetings/`, `Sources/Transcripts/`, `Sources/Clippings/` | Keep raw agent chats, ideas to review, meeting notes, transcripts, and web clippings. |
71
+ | Evidence | `Evidence/<area>/` | Append dated statements with links to their sources. Record corrections as new statements. |
72
+ | Synthesis | `Synthesis/<area>.md`, `Synthesis/Direction/<area>.md`, `Synthesis/Objectives.md`, `Synthesis/Objectives.evidence.md`, and supporting notes | Maintain current understanding, directions, and objectives with links to evidence. |
73
+ | Metadata | `Metadata/pending/<id>.json` | Track triage approval items and outcomes in private Git. |
74
+ | Metadata | `Metadata/recap/<area>/YYYY-MM.md` | Track monthly triage recaps by area in private Git. |
75
+ | Metadata | `Metadata/review/YYYY-Www.md` | Track periodic objectives reviews by ISO week in private Git. |
76
+
77
+ Direction and Objectives are Synthesis notes. The owner reviews them, and edits default to `require_approval`. Metadata supports triage and sits outside the knowledge tiers. The three Metadata paths above are Git-tracked. Per-machine diagnostics and the QMD index live in the local user cache outside the vault.
78
+
79
+ ## Sync
80
+
81
+ Lexicon syncs the vault through private Git on a timer, even when Obsidian is closed. Captures and other engine writes sync immediately. Manual edits can take up to one timer interval to sync. If you use Obsidian, turn off the Git plugin's automatic commit, push, and pull, or remove it. Leave Obsidian Sync and other folder sync services disabled for this vault.
82
+
83
+ ## Install
84
+
85
+ ```bash
86
+ curl -fsSL https://raw.githubusercontent.com/not-so-fat/lexicon/main/install.sh | sh -s -- --vault <your-private-vault-git-url> --path "$HOME/vault"
87
+ ```
88
+
89
+ See [Setup](docs/SETUP.md) for requirements, new vaults, and upgrades.
90
+
91
+ ## Commands
92
+
93
+ The engine CLI covers the whole loop: `lexicon setup`, `lexicon doctor`, `lexicon init`, `lexicon capture`, `lexicon search`, `lexicon read`, `lexicon triage`, `lexicon lint`, `lexicon sync`, `lexicon index`, `lexicon info`, `lexicon mcp`, `lexicon fireflies`, and `lexicon hidock`. Start hand-written notes from a packaged template with `lexicon template <kind>` (`lexicon template --list` lists the seven kinds); templates are served by the engine and never copied into the vault.
94
+
95
+ ## More details
96
+
97
+ See [the redesign spec](docs/DESIGN.md) for the engine, search, and triage. [Setup](docs/SETUP.md) covers installing the engine and running your first triage pass; [Updating](docs/UPDATING.md) covers engine upgrades; [Memory model](docs/MEMORY_MODEL.md) covers the tiers and lint rules; [Objectives](docs/OBJECTIVES.md) covers the review ritual. [Publishing](docs/PUBLISHING.md) covers cutting a release, and the [Changelog](CHANGELOG.md) lists what changed. [Adapters](adapters/README.md) are optional harness-side pointers into the engine.
98
+
99
+ [MIT license](LICENSE).
@@ -0,0 +1,75 @@
1
+ # Lexicon
2
+
3
+ **Knowledge base with AI agents, especially for dynamic knowledge**
4
+
5
+ We come across a lot of knowledge through different activities.
6
+
7
+ - Work with AI agents
8
+ - Our own notes
9
+ - Messages
10
+ - Meetings and chats
11
+ - URLs we or our friends are interested in
12
+
13
+ Our AI agents should help us organize this knowledge, and they should get much stronger with it.
14
+ Especially when we want to clone ourselves as agents, this knowledge is critical input for them to work.
15
+
16
+ The key insight comes from [Zettelkasten](https://zettelkasten.de/overview/), a knowledge management methodology.
17
+
18
+ ## Principles
19
+
20
+ - Dump any data (missing data is more costly).
21
+ - Split source data (the dump) and curated data (for long-term search).
22
+ - Search curated data first. Go back to the source when we need more detail or missed something.
23
+ - Manage knowledge as statements. A statement is one claim or observation we can understand and check on its own.
24
+ - Organize statements into different areas. An area is a named domain of knowledge, such as a project or a recurring subject.
25
+
26
+ Memory = Knowledge (facts about the world) + Operational insights (how to work, records, state, rules). Across agents, share knowledge in Lexicon and how-to-work in Agent Deck playbooks. Everything else stays per-agent. Lexicon is the local Markdown knowledge base. Agent state, operating rules, and work tracking live outside it.
27
+
28
+ ## Solution Idea
29
+
30
+ 1. Data is dumped into the `Sources/` directory.
31
+ - Meeting transcripts
32
+ - Notes by humans and agents
33
+ - Clips from websites
34
+ - Agent chats
35
+ 2. Facts are accumulated in append-only `Evidence/`.
36
+ - Project decisions
37
+ - People
38
+ 3. Periodically, the owner reviews important decisions and adds, modifies, or deletes entries in `Synthesis/`.
39
+ - Directions
40
+ - Objectives
41
+
42
+ ## Key structure
43
+
44
+ | Layer | Path | Purpose |
45
+ | --- | --- | --- |
46
+ | Sources | `Sources/Chats/`, `Sources/Ideas/`, `Sources/Meetings/`, `Sources/Transcripts/`, `Sources/Clippings/` | Keep raw agent chats, ideas to review, meeting notes, transcripts, and web clippings. |
47
+ | Evidence | `Evidence/<area>/` | Append dated statements with links to their sources. Record corrections as new statements. |
48
+ | Synthesis | `Synthesis/<area>.md`, `Synthesis/Direction/<area>.md`, `Synthesis/Objectives.md`, `Synthesis/Objectives.evidence.md`, and supporting notes | Maintain current understanding, directions, and objectives with links to evidence. |
49
+ | Metadata | `Metadata/pending/<id>.json` | Track triage approval items and outcomes in private Git. |
50
+ | Metadata | `Metadata/recap/<area>/YYYY-MM.md` | Track monthly triage recaps by area in private Git. |
51
+ | Metadata | `Metadata/review/YYYY-Www.md` | Track periodic objectives reviews by ISO week in private Git. |
52
+
53
+ Direction and Objectives are Synthesis notes. The owner reviews them, and edits default to `require_approval`. Metadata supports triage and sits outside the knowledge tiers. The three Metadata paths above are Git-tracked. Per-machine diagnostics and the QMD index live in the local user cache outside the vault.
54
+
55
+ ## Sync
56
+
57
+ Lexicon syncs the vault through private Git on a timer, even when Obsidian is closed. Captures and other engine writes sync immediately. Manual edits can take up to one timer interval to sync. If you use Obsidian, turn off the Git plugin's automatic commit, push, and pull, or remove it. Leave Obsidian Sync and other folder sync services disabled for this vault.
58
+
59
+ ## Install
60
+
61
+ ```bash
62
+ curl -fsSL https://raw.githubusercontent.com/not-so-fat/lexicon/main/install.sh | sh -s -- --vault <your-private-vault-git-url> --path "$HOME/vault"
63
+ ```
64
+
65
+ See [Setup](docs/SETUP.md) for requirements, new vaults, and upgrades.
66
+
67
+ ## Commands
68
+
69
+ The engine CLI covers the whole loop: `lexicon setup`, `lexicon doctor`, `lexicon init`, `lexicon capture`, `lexicon search`, `lexicon read`, `lexicon triage`, `lexicon lint`, `lexicon sync`, `lexicon index`, `lexicon info`, `lexicon mcp`, `lexicon fireflies`, and `lexicon hidock`. Start hand-written notes from a packaged template with `lexicon template <kind>` (`lexicon template --list` lists the seven kinds); templates are served by the engine and never copied into the vault.
70
+
71
+ ## More details
72
+
73
+ See [the redesign spec](docs/DESIGN.md) for the engine, search, and triage. [Setup](docs/SETUP.md) covers installing the engine and running your first triage pass; [Updating](docs/UPDATING.md) covers engine upgrades; [Memory model](docs/MEMORY_MODEL.md) covers the tiers and lint rules; [Objectives](docs/OBJECTIVES.md) covers the review ritual. [Publishing](docs/PUBLISHING.md) covers cutting a release, and the [Changelog](CHANGELOG.md) lists what changed. [Adapters](adapters/README.md) are optional harness-side pointers into the engine.
74
+
75
+ [MIT license](LICENSE).
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lexicon-kb"
7
+ dynamic = ["version"]
8
+ description = "Lexicon engine: local Markdown knowledge base for agents"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = {text = "MIT"}
12
+ authors = [{name = "not-so-fat"}]
13
+ keywords = ["knowledge-base", "markdown", "agents", "notes", "search"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Documentation",
23
+ "Topic :: Scientific/Engineering :: Information Analysis",
24
+ ]
25
+ dependencies = []
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/not-so-fat/lexicon"
29
+ Repository = "https://github.com/not-so-fat/lexicon"
30
+ Changelog = "https://github.com/not-so-fat/lexicon/blob/main/CHANGELOG.md"
31
+
32
+ [project.scripts]
33
+ lexicon = "lexicon.cli:main"
34
+
35
+ [tool.setuptools]
36
+ package-dir = {"" = "src"}
37
+
38
+ [tool.setuptools.dynamic]
39
+ version = {attr = "lexicon.__version__"}
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
43
+
44
+ [tool.setuptools.package-data]
45
+ lexicon = ["templates/vault/*.md", "templates/vault/gitignore", "templates/notes/*.md"]
46
+
47
+ [tool.pytest.ini_options]
48
+ pythonpath = ["src"]
49
+ testpaths = ["tests"]
50
+ markers = ["qmd: tests that require the real QMD binary"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,8 @@
1
+ """Lexicon engine: path resolution, reads, writes, and tier rules for a vault."""
2
+ from __future__ import annotations
3
+
4
+ from lexicon.errors import LexiconError
5
+
6
+ __all__ = ["LexiconError", "__version__"]
7
+
8
+ __version__ = "0.1.0"
@@ -0,0 +1,6 @@
1
+ """Make ``python3 -m lexicon`` equivalent to the ``lexicon`` script."""
2
+
3
+ from lexicon.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,249 @@
1
+ """``lexicon capture`` engine: parse exports, redact, dedupe, and store notes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from datetime import datetime, timezone
7
+
8
+ from lexicon.capture import formats
9
+ from lexicon.capture.formats import ACCOUNT_RE, ORIGIN_RE
10
+ from lexicon.capture.sanitize import (
11
+ compile_redactions,
12
+ hash_chat,
13
+ hash_transcript,
14
+ normalize_text,
15
+ redact_text,
16
+ )
17
+ from lexicon.capture.store import parse_frontmatter, quote, render_chat_body, render_note
18
+ from lexicon.capture.store import safe_id as _safe_id
19
+ from lexicon.capture.store import scan_existing, tier_dir, transcript_dir
20
+ from lexicon.errors import LexiconError
21
+ from lexicon.vault import Vault
22
+ from lexicon.writes import write_session
23
+
24
+ __all__ = [
25
+ "AUTO_FORMATS",
26
+ "FORMATS",
27
+ "ORIGIN_RE",
28
+ "capture",
29
+ "parse_frontmatter",
30
+ "quote",
31
+ "resolve_format",
32
+ "safe_id",
33
+ ]
34
+
35
+ FORMATS = (
36
+ "auto",
37
+ "record",
38
+ "claude-jsonl",
39
+ "codex-rollout",
40
+ "cursor-stream-json",
41
+ "cursor-markdown",
42
+ )
43
+
44
+ AUTO_FORMATS = {
45
+ "claude-code": "claude-jsonl",
46
+ "codex": "codex-rollout",
47
+ "codex-run": "record",
48
+ "cursor-cli": "cursor-stream-json",
49
+ "cursor-ide": "cursor-markdown",
50
+ }
51
+
52
+
53
+ def safe_id(stable_id: str) -> str:
54
+ return _safe_id(stable_id)
55
+
56
+
57
+ def resolve_format(kind: str, origin: str, fmt: str) -> str:
58
+ """Resolve ``auto`` to a concrete format and check kind compatibility."""
59
+ if fmt not in FORMATS:
60
+ raise LexiconError("invalid_format", f"unknown format: {fmt}")
61
+ if fmt == "auto":
62
+ if kind == "transcript":
63
+ return "record"
64
+ return AUTO_FORMATS.get(origin, "record")
65
+ if fmt != "record" and kind != "chat":
66
+ raise LexiconError(
67
+ "invalid_record", f"format {fmt} only supports --kind chat"
68
+ )
69
+ return fmt
70
+
71
+
72
+ def _utc_now_iso() -> str:
73
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
74
+
75
+
76
+ def capture(
77
+ vault: Vault,
78
+ *,
79
+ kind: str,
80
+ origin: str,
81
+ raw: str,
82
+ fmt: str = "auto",
83
+ stable_id_override: str | None = None,
84
+ area: str | None = None,
85
+ title: str | None = None,
86
+ redact: list[str] | None = None,
87
+ now: str | None = None,
88
+ account: str | None = None,
89
+ ) -> dict:
90
+ """Capture an export into the vault, deduplicating by content hash."""
91
+ if kind not in ("chat", "transcript"):
92
+ raise LexiconError("invalid_kind", f"unknown kind: {kind}")
93
+ if not ORIGIN_RE.fullmatch(origin):
94
+ raise LexiconError("invalid_origin", f"invalid origin: {origin!r}")
95
+ if account is not None:
96
+ if kind == "chat":
97
+ raise LexiconError(
98
+ "invalid_params", "--account only supports --kind transcript"
99
+ )
100
+ if not isinstance(account, str) or not ACCOUNT_RE.fullmatch(account):
101
+ raise LexiconError("invalid_params", f"invalid account: {account!r}")
102
+ resolved = resolve_format(kind, origin, fmt)
103
+
104
+ if resolved == "record":
105
+ parsed = formats.parse_record(raw, kind)
106
+ elif resolved == "claude-jsonl":
107
+ parsed = formats.parse_claude_jsonl(raw)
108
+ elif resolved == "codex-rollout":
109
+ parsed = formats.parse_codex_rollout(raw)
110
+ elif resolved == "cursor-stream-json":
111
+ parsed = formats.parse_cursor_stream_json(raw)
112
+ elif resolved == "cursor-markdown":
113
+ parsed = formats.parse_cursor_markdown(raw)
114
+ else: # pragma: no cover - resolve_format guards this
115
+ raise LexiconError("invalid_format", f"unknown format: {resolved}")
116
+
117
+ if resolved == "record" and parsed.origin is not None and parsed.origin != origin:
118
+ raise LexiconError(
119
+ "invalid_record",
120
+ f"record origin {parsed.origin!r} does not match --origin {origin!r}",
121
+ )
122
+
123
+ if stable_id_override is not None:
124
+ stable_id = stable_id_override.strip()
125
+ if not stable_id:
126
+ raise LexiconError("invalid_record", "--id must be non-empty")
127
+ elif parsed.stable_id is not None:
128
+ stable_id = parsed.stable_id.strip()
129
+ if not stable_id:
130
+ raise LexiconError("invalid_record", "stable ID is empty")
131
+ elif resolved == "cursor-markdown":
132
+ stable_id = f"cap-{uuid.uuid4().hex}"
133
+ else:
134
+ raise LexiconError(
135
+ "invalid_record", f"{resolved} export has no session ID (pass --id)"
136
+ )
137
+
138
+ if title is not None and title.strip():
139
+ final_title = title.strip()
140
+ elif getattr(parsed, "title", None):
141
+ final_title = parsed.title or ""
142
+ else:
143
+ final_title = f"{origin} {stable_id}"
144
+ if not final_title:
145
+ final_title = f"{origin} {stable_id}"
146
+
147
+ if area is not None:
148
+ final_area = area.strip() or None
149
+ else:
150
+ final_area = getattr(parsed, "area", None)
151
+
152
+ extra = compile_redactions(redact)
153
+
154
+ if kind == "chat":
155
+ assert isinstance(parsed, formats.ParsedChat)
156
+ turns: list[tuple[str, str, str | None]] = []
157
+ for turn in parsed.turns:
158
+ text = redact_text(normalize_text(turn.text), extra)
159
+ if text.strip() == "":
160
+ continue
161
+ turns.append((turn.speaker, text, turn.at))
162
+ if not turns:
163
+ raise LexiconError("invalid_record", "no turns left after normalization")
164
+ content_sha256 = hash_chat([[speaker, text] for speaker, text, _ in turns])
165
+ body = render_chat_body(turns)
166
+ else:
167
+ assert isinstance(parsed, formats.ParsedTranscript)
168
+ body_text = redact_text(normalize_text(parsed.body), extra)
169
+ if body_text.strip() == "":
170
+ raise LexiconError("invalid_record", "transcript body is empty")
171
+ content_sha256 = hash_transcript(body_text)
172
+ body = body_text + "\n"
173
+
174
+ captured = now or _utc_now_iso()
175
+ created = parsed.created or captured[:10]
176
+
177
+ safe = _safe_id(stable_id)
178
+ if kind == "transcript":
179
+ assert isinstance(parsed, formats.ParsedTranscript)
180
+ final_account = account if account is not None else parsed.account
181
+ dir_rel = transcript_dir(origin, final_account)
182
+ else:
183
+ dir_rel = f"{tier_dir(kind)}/{origin}"
184
+
185
+ # Scan, dedupe decision, revision allocation, and write all happen inside
186
+ # one serialized write session so concurrent captures cannot pick the
187
+ # same destination or lose a revision.
188
+ with write_session(vault, f"capture {kind} {origin} {stable_id}") as session:
189
+ existing = scan_existing(vault, dir_rel, safe)
190
+ hit = None
191
+ for item in existing:
192
+ if item["content_sha256"] == content_sha256:
193
+ hit = item
194
+ break
195
+ if hit is None:
196
+ if not existing:
197
+ filename = f"{safe}.md"
198
+ revision = 1
199
+ previous = None
200
+ revision_of = None
201
+ else:
202
+ prior = existing[-1]
203
+ revision = prior["sort_revision"] + 1
204
+ if revision < 2:
205
+ revision = 2
206
+ filename = f"{safe}.r{revision}.md"
207
+ previous = f"[[{prior['stem']}]]"
208
+ revision_of = prior["rel"]
209
+ rel = f"{dir_rel}/{filename}"
210
+ note = render_note(
211
+ kind=kind,
212
+ origin=origin,
213
+ stable_id=stable_id,
214
+ title=final_title,
215
+ created=created,
216
+ captured=captured,
217
+ content_sha256=content_sha256,
218
+ revision=revision,
219
+ body=body,
220
+ area=final_area,
221
+ previous=previous,
222
+ )
223
+ session.write_text(rel, note)
224
+ assert session.result is not None
225
+ if hit is not None:
226
+ return {
227
+ "ok": True,
228
+ "path": hit["rel"],
229
+ "created": False,
230
+ "revision": hit["revision"],
231
+ "revision_of": None,
232
+ "origin": origin,
233
+ "stable_id": stable_id,
234
+ "content_sha256": content_sha256,
235
+ "sync": session.result["sync"],
236
+ "index": session.result["index"],
237
+ }
238
+ return {
239
+ "ok": True,
240
+ "path": rel,
241
+ "created": True,
242
+ "revision": revision,
243
+ "revision_of": revision_of,
244
+ "origin": origin,
245
+ "stable_id": stable_id,
246
+ "content_sha256": content_sha256,
247
+ "sync": session.result["sync"],
248
+ "index": session.result["index"],
249
+ }