clinotes 0.1.0__py3-none-any.whl

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.
clinotes/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """Clinotes - CLI-driven memory for AI-assisted development.
2
+
3
+ A simple system for capturing and retrieving decisions and learnings
4
+ during development, optimized for LLM-driven workflows.
5
+ """
6
+ from .api import recall_index, recall_detail, note_decision, note_learned
7
+
8
+ __version__ = "0.1.0"
9
+ __all__ = [
10
+ "recall_index",
11
+ "recall_detail",
12
+ "note_decision",
13
+ "note_learned",
14
+ "__version__",
15
+ ]
clinotes/api.py ADDED
@@ -0,0 +1,211 @@
1
+ """Public API for clinotes memory management.
2
+
3
+ Provides functions to record and recall decisions and learnings. Frontmatter is
4
+ serialized with a real YAML dumper so titles/refs containing colons, quotes,
5
+ brackets, unicode, or trailing spaces round-trip losslessly.
6
+ """
7
+ from datetime import datetime, timezone
8
+ import os
9
+ import re
10
+ from pathlib import Path
11
+
12
+ import yaml
13
+
14
+ from . import storage, ids, index, schema
15
+
16
+ # A valid memory id is a letter-prefix followed by digits (e.g. "d1", "l12").
17
+ # Anything else is rejected so recall_detail cannot be coerced into a path
18
+ # traversal (e.g. "../../secret").
19
+ _ID_RE = re.compile(r"^[A-Za-z]+[0-9]+$")
20
+
21
+
22
+ def _root() -> Path:
23
+ """Return the clinotes memory root directory.
24
+
25
+ Resolves from the ``CLINOTES_ROOT`` environment variable, defaulting to
26
+ ``.clinotes`` in the current working directory.
27
+ """
28
+ return Path(os.environ.get("CLINOTES_ROOT", ".clinotes"))
29
+
30
+
31
+ def _validate_title(title: str) -> str:
32
+ """Validate a memory title.
33
+
34
+ Args:
35
+ title: The proposed title.
36
+
37
+ Returns:
38
+ The title unchanged.
39
+
40
+ Raises:
41
+ ValueError: If the title is empty/blank or contains a line break
42
+ (titles are single-line labels — a newline would corrupt the
43
+ single-line INDEX.md entry).
44
+ """
45
+ if not title or not title.strip():
46
+ raise ValueError("title must not be empty or blank")
47
+ if "\n" in title or "\r" in title:
48
+ raise ValueError("title must be a single line (no line breaks)")
49
+ return title
50
+
51
+
52
+ def recall_index() -> str:
53
+ """L0: return INDEX.md text.
54
+
55
+ Calls :func:`index.ensure_index` first so a fresh project returns the empty
56
+ scaffold rather than raising.
57
+
58
+ Returns:
59
+ The full text of the INDEX.md file.
60
+ """
61
+ root = _root()
62
+ index.ensure_index(root)
63
+ return storage.read_file(root / "INDEX.md")
64
+
65
+
66
+ def recall_detail(id: str) -> str:
67
+ """L2: return full text of ``_root()/detail/{id}.md``.
68
+
69
+ Args:
70
+ id: The memory identifier (e.g., ``"d1"``, ``"l3"``).
71
+
72
+ Returns:
73
+ The full markdown text of the detail file.
74
+
75
+ Raises:
76
+ ValueError: If ``id`` is malformed or no memory exists with that id.
77
+ """
78
+ if not isinstance(id, str) or not _ID_RE.match(id):
79
+ raise ValueError(f"No memory with id={id}")
80
+ detail_path = _root() / "detail" / f"{id}.md"
81
+ if not detail_path.exists():
82
+ raise ValueError(f"No memory with id={id}")
83
+ return storage.read_file(detail_path)
84
+
85
+
86
+ def _render_detail(
87
+ id: str,
88
+ type: str,
89
+ title: str,
90
+ body: str,
91
+ alternatives: list[str],
92
+ refs: list[str],
93
+ ) -> str:
94
+ """Render the full markdown document (YAML frontmatter + body).
95
+
96
+ The frontmatter is produced with :func:`yaml.safe_dump` so any special
97
+ characters (``:``, quotes, ``[``/``{``, ``#``, unicode, trailing spaces)
98
+ are correctly escaped and round-trip via ``frontmatter.loads``.
99
+
100
+ Args:
101
+ id: Unique identifier (e.g., ``"d1"``).
102
+ type: Either ``"decision"`` or ``"learned"``.
103
+ title: Human-readable single-line title.
104
+ body: The "why" for decisions, the "notes" text for learnings.
105
+ alternatives: Alternatives (decisions only; emitted only if non-empty).
106
+ refs: File/URL references (emitted as a YAML list).
107
+
108
+ Returns:
109
+ The complete markdown document.
110
+
111
+ Raises:
112
+ ValueError: If ``type`` is not a known memory type.
113
+ """
114
+ if type not in schema.ALLOWED_TYPES:
115
+ raise ValueError(f"Unknown type: {type}")
116
+
117
+ meta = {
118
+ "id": id,
119
+ "type": type,
120
+ "title": title,
121
+ "created": datetime.now(timezone.utc).isoformat(),
122
+ "refs": list(refs),
123
+ }
124
+ fm = yaml.safe_dump(
125
+ meta, sort_keys=False, allow_unicode=True, default_flow_style=False
126
+ ).strip()
127
+ frontmatter_block = f"---\n{fm}\n---"
128
+
129
+ if type == "decision":
130
+ parts = [frontmatter_block, "", "## Why", "", body]
131
+ if alternatives:
132
+ alt_lines = "\n".join(f"- {alt}" for alt in alternatives)
133
+ parts.extend(["", "## Alternatives", "", alt_lines])
134
+ return "\n".join(parts)
135
+
136
+ # learned
137
+ return "\n".join([frontmatter_block, "", "## Notes", "", body])
138
+
139
+
140
+ def note_decision(
141
+ title: str,
142
+ why: str,
143
+ alternatives: list[str] | None = None,
144
+ refs: list[str] | None = None,
145
+ ) -> str:
146
+ """Record a decision.
147
+
148
+ Args:
149
+ title: Single-line title (must not be empty/blank or contain newlines).
150
+ why: Explanation of the decision.
151
+ alternatives: Optional alternatives considered.
152
+ refs: Optional file/URL references.
153
+
154
+ Returns:
155
+ The new id (e.g., ``"d3"``).
156
+
157
+ Raises:
158
+ ValueError: If the title is invalid.
159
+ """
160
+ _validate_title(title)
161
+ root = _root()
162
+ # Serialize id-assignment + detail-write + index-update so concurrent
163
+ # writers in the same .clinotes dir can't collide on ids or lose entries.
164
+ with storage.lock(root):
165
+ new_id = ids.next_id(root, "d")
166
+ content = _render_detail(
167
+ id=new_id,
168
+ type="decision",
169
+ title=title,
170
+ body=why,
171
+ alternatives=alternatives or [],
172
+ refs=refs or [],
173
+ )
174
+ storage.write_file_atomic(root / "detail" / f"{new_id}.md", content)
175
+ index.update_index(root, "Decisions", new_id, title)
176
+ return new_id
177
+
178
+
179
+ def note_learned(
180
+ title: str,
181
+ body: str,
182
+ refs: list[str] | None = None,
183
+ ) -> str:
184
+ """Record a learning.
185
+
186
+ Args:
187
+ title: Single-line title (must not be empty/blank or contain newlines).
188
+ body: The notes/learning content.
189
+ refs: Optional file/URL references.
190
+
191
+ Returns:
192
+ The new id (e.g., ``"l3"``).
193
+
194
+ Raises:
195
+ ValueError: If the title is invalid.
196
+ """
197
+ _validate_title(title)
198
+ root = _root()
199
+ with storage.lock(root):
200
+ new_id = ids.next_id(root, "l")
201
+ content = _render_detail(
202
+ id=new_id,
203
+ type="learned",
204
+ title=title,
205
+ body=body,
206
+ alternatives=[],
207
+ refs=refs or [],
208
+ )
209
+ storage.write_file_atomic(root / "detail" / f"{new_id}.md", content)
210
+ index.update_index(root, "Learned", new_id, title)
211
+ return new_id
clinotes/cli.py ADDED
@@ -0,0 +1,41 @@
1
+ """Typer CLI for clinotes memory management.
2
+
3
+ Provides commands to initialize, list, and show project memory entries.
4
+ """
5
+ from pathlib import Path
6
+
7
+ import typer
8
+
9
+ from . import api, index
10
+
11
+ app = typer.Typer(
12
+ no_args_is_help=True,
13
+ help="Pyramid memory for LLM-driven CLIs.",
14
+ )
15
+
16
+
17
+ @app.command()
18
+ def init() -> None:
19
+ """Create .clinotes/ in the current directory (idempotent)."""
20
+ root = api._root()
21
+ root.mkdir(parents=True, exist_ok=True)
22
+ (root / "detail").mkdir(parents=True, exist_ok=True)
23
+ index.ensure_index(root)
24
+ typer.echo(f"initialized .clinotes/ at {root.resolve()}")
25
+
26
+
27
+ @app.command()
28
+ def show(id: str) -> None:
29
+ """Print the full detail for a memory id (e.g. clinotes show d2)."""
30
+ try:
31
+ detail = api.recall_detail(id)
32
+ except ValueError:
33
+ typer.echo(f"No memory with id={id}", err=True)
34
+ raise typer.Exit(1)
35
+ typer.echo(detail)
36
+
37
+
38
+ @app.command()
39
+ def ls() -> None:
40
+ """Print the INDEX (all ids grouped by section)."""
41
+ typer.echo(api.recall_index())
clinotes/ids.py ADDED
@@ -0,0 +1,37 @@
1
+ from pathlib import Path
2
+
3
+
4
+ def next_id(root: Path, prefix: str) -> str:
5
+ """Return the next id for a prefix, e.g. 'd3' or 'l7'.
6
+
7
+ Scans root/'detail' for files named '{prefix}{n}.md', finds the max n,
8
+ returns f'{prefix}{max_n + 1}'. Returns f'{prefix}1' when none exist.
9
+ Only counts files whose stem is prefix followed by digits (ignore others).
10
+
11
+ Args:
12
+ root: The project root directory containing the ``.clinotes`` tree.
13
+ prefix: The id prefix character(s), e.g. ``"d"`` or ``"l"``.
14
+
15
+ Returns:
16
+ The next monotonic id string for the given prefix.
17
+ """
18
+ detail = root / "detail"
19
+ max_n = 0
20
+ if detail.exists() and detail.is_dir():
21
+ for item in detail.iterdir():
22
+ if not item.is_file():
23
+ continue
24
+ if item.suffix != ".md":
25
+ continue
26
+ stem = item.stem
27
+ if not stem.startswith(prefix):
28
+ continue
29
+ suffix = stem[len(prefix) :]
30
+ if not suffix.isdigit():
31
+ continue
32
+ n = int(suffix)
33
+ if n > max_n:
34
+ max_n = n
35
+ if max_n == 0:
36
+ return f"{prefix}1"
37
+ return f"{prefix}{max_n + 1}"
clinotes/index.py ADDED
@@ -0,0 +1,103 @@
1
+ """Index management for clinotes memory.
2
+
3
+ Manages the INDEX.md file which provides a flat list of all memory entries
4
+ grouped by section. INDEX.md is always rendered deterministically: a title
5
+ line, then each section in :data:`SECTIONS` order, with a single blank line
6
+ separating a section's entries from the following header and a single
7
+ trailing newline at end-of-file.
8
+ """
9
+ from pathlib import Path
10
+
11
+ from . import storage
12
+
13
+ SECTIONS = ("Decisions", "Learned", "Rejected", "Open")
14
+
15
+ _TITLE = "# Project Memory Index"
16
+
17
+
18
+ def _render(entries: dict[str, list[str]]) -> str:
19
+ """Render the full INDEX.md text from a section -> entry-lines mapping.
20
+
21
+ Args:
22
+ entries: Mapping of each section name in :data:`SECTIONS` to the list
23
+ of its entry lines (e.g. ``["- d1: alpha", "- d2: gamma"]``).
24
+
25
+ Returns:
26
+ The complete INDEX.md document with a single trailing newline. Entries
27
+ within a section are contiguous; exactly one blank line separates the
28
+ last entry of a section from the next ``## `` header.
29
+ """
30
+ blocks = [_TITLE]
31
+ for name in SECTIONS:
32
+ section_entries = entries.get(name, [])
33
+ if section_entries:
34
+ blocks.append(f"## {name}\n\n" + "\n".join(section_entries))
35
+ else:
36
+ blocks.append(f"## {name}")
37
+ return "\n\n".join(blocks) + "\n"
38
+
39
+
40
+ def _parse(content: str) -> dict[str, list[str]]:
41
+ """Parse INDEX.md text into a section -> entry-lines mapping.
42
+
43
+ Recovers entries regardless of the prior blank-line layout, so the file
44
+ can always be re-rendered cleanly.
45
+
46
+ Args:
47
+ content: Raw INDEX.md text.
48
+
49
+ Returns:
50
+ Mapping of each section name in :data:`SECTIONS` to its entry lines.
51
+ """
52
+ entries: dict[str, list[str]] = {name: [] for name in SECTIONS}
53
+ current: str | None = None
54
+ for raw in content.replace("\r\n", "\n").splitlines():
55
+ line = raw.rstrip()
56
+ if line.startswith("## "):
57
+ heading = line[3:].strip()
58
+ current = heading if heading in entries else None
59
+ elif line.startswith("- ") and current is not None:
60
+ entries[current].append(line)
61
+ return entries
62
+
63
+
64
+ def ensure_index(root: Path) -> None:
65
+ """Create ``root/INDEX.md`` with the title and four empty section headers.
66
+
67
+ Idempotent: does nothing if the file already exists. Creates ``root`` if
68
+ needed.
69
+
70
+ Args:
71
+ root: The ``.clinotes`` directory.
72
+ """
73
+ index_path = root / "INDEX.md"
74
+ if index_path.exists():
75
+ return
76
+ root.mkdir(parents=True, exist_ok=True)
77
+ storage.write_file_atomic(index_path, _render({name: [] for name in SECTIONS}))
78
+
79
+
80
+ def update_index(root: Path, section: str, id: str, title: str) -> None:
81
+ """Append ``- {id}: {title}`` under the ``## {section}`` header.
82
+
83
+ Calls :func:`ensure_index` first, parses the existing index, appends the
84
+ new entry as the last line of the target section, then re-renders the whole
85
+ file deterministically.
86
+
87
+ Args:
88
+ root: The ``.clinotes`` directory.
89
+ section: One of :data:`SECTIONS` (e.g. ``"Decisions"``).
90
+ id: The memory id (e.g. ``"d3"``).
91
+ title: The memory title.
92
+
93
+ Raises:
94
+ ValueError: If ``section`` is not in :data:`SECTIONS`.
95
+ """
96
+ if section not in SECTIONS:
97
+ raise ValueError(f"Invalid section: {section!r}. Must be one of {SECTIONS}")
98
+
99
+ ensure_index(root)
100
+ index_path = root / "INDEX.md"
101
+ entries = _parse(storage.read_file(index_path))
102
+ entries[section].append(f"- {id}: {title}")
103
+ storage.write_file_atomic(index_path, _render(entries))
clinotes/schema.py ADDED
@@ -0,0 +1,61 @@
1
+ """Schema definitions for clinotes memory frontmatter validation."""
2
+
3
+ from datetime import datetime
4
+ from pydantic import BaseModel, field_validator
5
+
6
+ ALLOWED_TYPES = ("decision", "learned")
7
+
8
+
9
+ class MemoryDetail(BaseModel):
10
+ """Represents the validated frontmatter for a memory entry.
11
+
12
+ Attributes:
13
+ id: Unique identifier (e.g., 'd1', 'l3').
14
+ type: Either 'decision' or 'learned'.
15
+ title: Human-readable title (non-empty, non-blank).
16
+ created: ISO-8601 datetime with timezone.
17
+ refs: Optional list of file references.
18
+ """
19
+
20
+ id: str
21
+ type: str
22
+ title: str
23
+ created: datetime
24
+ refs: list[str] = []
25
+
26
+ @field_validator("type")
27
+ @classmethod
28
+ def validate_type(cls, v: str) -> str:
29
+ """Ensure type is one of ALLOWED_TYPES."""
30
+ if v not in ALLOWED_TYPES:
31
+ raise ValueError(f"type must be one of {ALLOWED_TYPES}, got '{v}'")
32
+ return v
33
+
34
+ @field_validator("title")
35
+ @classmethod
36
+ def validate_title(cls, v: str) -> str:
37
+ """Ensure title is not empty or blank."""
38
+ if not v or not v.strip():
39
+ raise ValueError("title must not be empty or blank")
40
+ return v
41
+
42
+
43
+ def validate_frontmatter(meta: dict) -> MemoryDetail:
44
+ """Validate a frontmatter dict and return a MemoryDetail.
45
+
46
+ Args:
47
+ meta: Dictionary containing frontmatter keys ('id', 'type', 'title', 'created').
48
+
49
+ Returns:
50
+ A validated MemoryDetail instance.
51
+
52
+ Raises:
53
+ ValueError: If required keys are missing, if type is not in ALLOWED_TYPES,
54
+ or if title is empty/blank.
55
+ """
56
+ required_keys = ("id", "type", "title", "created")
57
+ for key in required_keys:
58
+ if key not in meta:
59
+ raise ValueError(f"missing required frontmatter key: '{key}'")
60
+
61
+ return MemoryDetail(**meta)
clinotes/server.py ADDED
@@ -0,0 +1,107 @@
1
+ """FastMCP server wrapper for clinotes.
2
+
3
+ This module exposes the clinotes memory management tools via MCP protocol.
4
+ Run with: python -m clinotes.server
5
+ """
6
+ from fastmcp import FastMCP
7
+
8
+ from . import api
9
+ from . import __version__
10
+
11
+ app = FastMCP("clinotes", version=__version__)
12
+
13
+
14
+ @app.tool()
15
+ def recall_index() -> str:
16
+ """Read the project memory index (L0).
17
+
18
+ Call this FIRST for any project — it returns the compact INDEX.md file
19
+ listing all decision and learning IDs with their titles. This is cheap
20
+ (~200 tokens) and gives you the map of available memories before diving
21
+ into details.
22
+
23
+ Returns:
24
+ The full text of the INDEX.md file containing all recorded decisions
25
+ and learnings with their IDs and titles.
26
+ """
27
+ return api.recall_index()
28
+
29
+
30
+ @app.tool()
31
+ def recall_detail(id: str) -> str:
32
+ """Read full L2 detail for one memory ID.
33
+
34
+ Use this after recall_index identifies a relevant ID (e.g., 'd2', 'l3').
35
+ It returns the complete markdown document including YAML frontmatter
36
+ (id, type, title, created, refs) and the detailed body (Why for decisions,
37
+ Notes for learnings).
38
+
39
+ Args:
40
+ id: The memory identifier to retrieve, e.g. 'd1', 'd2', 'l1'.
41
+
42
+ Returns:
43
+ The full markdown text of the detail file including frontmatter
44
+ and body sections.
45
+
46
+ Raises:
47
+ ValueError: If no memory exists with the given id.
48
+ """
49
+ return api.recall_detail(id)
50
+
51
+
52
+ @app.tool()
53
+ def note_decision(
54
+ title: str,
55
+ why: str,
56
+ alternatives: list[str] | None = None,
57
+ refs: list[str] | None = None,
58
+ ) -> str:
59
+ """Record a new decision in the project memory.
60
+
61
+ Call this when you make a design choice, architectural decision, or
62
+ any explicit selection among alternatives. The system assigns the
63
+ next available decision ID (d1, d2, ...) and persists the full detail.
64
+
65
+ Args:
66
+ title: A concise title describing the decision (required, non-empty).
67
+ why: The reasoning behind this decision (the 'why' explanation).
68
+ alternatives: Optional list of alternative options that were considered.
69
+ refs: Optional list of file paths or URLs referenced in the decision.
70
+
71
+ Returns:
72
+ The newly assigned decision ID, e.g. 'd3'.
73
+ """
74
+ return api.note_decision(title, why, alternatives, refs)
75
+
76
+
77
+ @app.tool()
78
+ def note_learned(
79
+ title: str,
80
+ body: str,
81
+ refs: list[str] | None = None,
82
+ ) -> str:
83
+ """Record a new learning in the project memory.
84
+
85
+ Call this when you discover something worth remembering — a workaround,
86
+ gotcha, performance insight, or any knowledge gained during development.
87
+ The system assigns the next available learning ID (l1, l2, ...) and
88
+ persists the complete detail.
89
+
90
+ Args:
91
+ title: A concise title describing what was learned (required, non-empty).
92
+ body: The learning or notes content (what was discovered).
93
+ refs: Optional list of file paths or URLs related to this learning.
94
+
95
+ Returns:
96
+ The newly assigned learning ID, e.g. 'l3'.
97
+ """
98
+ return api.note_learned(title, body, refs)
99
+
100
+
101
+ def main() -> None:
102
+ """Run the FastMCP server."""
103
+ app.run()
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
clinotes/storage.py ADDED
@@ -0,0 +1,132 @@
1
+ """Storage layer for clinotes file IO.
2
+
3
+ Provides atomic file writes (readers never see a partial file) and a small
4
+ cross-process advisory lock so concurrent writers in the same ``.clinotes``
5
+ directory don't lose updates or collide on ids.
6
+ """
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+ import os
10
+ import tempfile
11
+ import time
12
+
13
+ # Windows raises these transiently when another process (a second writer, an
14
+ # antivirus scanner, or the search indexer) momentarily holds the target during
15
+ # os.replace. They clear within milliseconds, so we retry rather than fail.
16
+ _WIN_TRANSIENT = (5, 32) # ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION
17
+ _REPLACE_ATTEMPTS = 20
18
+ _REPLACE_BACKOFF = 0.02 # seconds, linear-ish
19
+
20
+
21
+ def read_file(path: Path) -> str:
22
+ """Return file text (utf-8). '' if the file is empty.
23
+
24
+ Retries on transient Windows sharing errors so a reader that lands exactly
25
+ while another process is replacing the file doesn't spuriously fail.
26
+
27
+ Raises:
28
+ FileNotFoundError: If the path does not exist.
29
+ """
30
+ if not path.exists():
31
+ raise FileNotFoundError(f"File not found: {path}")
32
+ last_exc: Exception | None = None
33
+ for attempt in range(_REPLACE_ATTEMPTS):
34
+ try:
35
+ return path.read_text(encoding="utf-8")
36
+ except (PermissionError, OSError) as exc:
37
+ if getattr(exc, "winerror", None) not in _WIN_TRANSIENT:
38
+ raise
39
+ last_exc = exc
40
+ time.sleep(_REPLACE_BACKOFF * (attempt + 1))
41
+ raise last_exc # type: ignore[misc]
42
+
43
+
44
+ def _atomic_replace(temp_path: str, path: Path) -> None:
45
+ """os.replace with bounded retry on transient Windows sharing errors."""
46
+ last_exc: Exception | None = None
47
+ for attempt in range(_REPLACE_ATTEMPTS):
48
+ try:
49
+ os.replace(temp_path, path)
50
+ return
51
+ except (PermissionError, OSError) as exc:
52
+ winerror = getattr(exc, "winerror", None)
53
+ # Only retry the known-transient Windows cases; re-raise anything else.
54
+ if winerror not in _WIN_TRANSIENT:
55
+ raise
56
+ last_exc = exc
57
+ time.sleep(_REPLACE_BACKOFF * (attempt + 1))
58
+ # Exhausted retries — surface the real error.
59
+ raise last_exc # type: ignore[misc]
60
+
61
+
62
+ def write_file_atomic(path: Path, content: str) -> None:
63
+ """Atomically write content (utf-8) to ``path``.
64
+
65
+ Creates parent directories, writes to a uniquely-named temp file in the
66
+ same directory, then ``os.replace`` (retried on transient Windows sharing
67
+ violations) onto the target so readers never see a partial file.
68
+ """
69
+ path.parent.mkdir(parents=True, exist_ok=True)
70
+ fd, temp_path = tempfile.mkstemp(dir=path.parent, suffix=".tmp", text=True)
71
+ try:
72
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
73
+ f.write(content)
74
+ _atomic_replace(temp_path, path)
75
+ except BaseException:
76
+ if os.path.exists(temp_path):
77
+ try:
78
+ os.unlink(temp_path)
79
+ except OSError:
80
+ pass
81
+ raise
82
+
83
+
84
+ @contextmanager
85
+ def lock(root: Path, timeout: float = 15.0, stale: float = 60.0):
86
+ """Cross-process advisory lock for the given ``.clinotes`` root.
87
+
88
+ Serializes the read-modify-write critical section (id assignment + detail
89
+ write + index update) so concurrent writers can't collide on ids or lose
90
+ INDEX.md entries. Uses an exclusive lock file; a lock older than ``stale``
91
+ seconds is assumed orphaned and reclaimed.
92
+
93
+ Args:
94
+ root: The ``.clinotes`` directory.
95
+ timeout: Max seconds to wait for the lock before raising TimeoutError.
96
+ stale: Age in seconds after which an existing lock is treated as orphaned.
97
+
98
+ Raises:
99
+ TimeoutError: If the lock cannot be acquired within ``timeout``.
100
+ """
101
+ root.mkdir(parents=True, exist_ok=True)
102
+ lock_path = root / ".clinotes.lock"
103
+ deadline = time.monotonic() + timeout
104
+ acquired = False
105
+ while True:
106
+ try:
107
+ fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
108
+ try:
109
+ os.write(fd, str(os.getpid()).encode())
110
+ finally:
111
+ os.close(fd)
112
+ acquired = True
113
+ break
114
+ except FileExistsError:
115
+ # Reclaim an orphaned lock left by a crashed process.
116
+ try:
117
+ if time.time() - os.path.getmtime(lock_path) > stale:
118
+ os.unlink(lock_path)
119
+ continue
120
+ except FileNotFoundError:
121
+ continue # released between checks — retry immediately
122
+ if time.monotonic() >= deadline:
123
+ raise TimeoutError(f"Could not acquire clinotes lock at {lock_path}")
124
+ time.sleep(0.02)
125
+ try:
126
+ yield
127
+ finally:
128
+ if acquired:
129
+ try:
130
+ os.unlink(lock_path)
131
+ except FileNotFoundError:
132
+ pass
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: clinotes
3
+ Version: 0.1.0
4
+ Summary: Pyramid memory for LLM-driven CLIs. Git-native, MCP-ready.
5
+ Project-URL: Homepage, https://github.com/karthyick/clinotes
6
+ Project-URL: Repository, https://github.com/karthyick/clinotes
7
+ Author-email: Karthick Raja M <Karthickrajam18@gmail.com>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: agent,cli,llm,mcp,memory
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: fastmcp>=3.0
20
+ Requires-Dist: pydantic>=2
21
+ Requires-Dist: python-frontmatter>=1.0
22
+ Requires-Dist: pyyaml>=6.0
23
+ Requires-Dist: typer>=0.12
24
+ Provides-Extra: dev
25
+ Requires-Dist: black; extra == 'dev'
26
+ Requires-Dist: build; extra == 'dev'
27
+ Requires-Dist: pytest; extra == 'dev'
28
+ Requires-Dist: ruff; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # clinotes
32
+
33
+ > Pyramid memory for LLM-driven CLIs. Git-native, MCP-ready.
34
+ >
35
+ > [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
36
+
37
+ ## What it is
38
+
39
+ clinotes is project memory that lives in your repo. It stores decisions and learnings as plain Markdown with YAML frontmatter inside a `.clinotes/` directory. Because the format is text-first and git-native, any LLM can recall it cheaply without hallucinating your stack.
40
+
41
+ ## Why
42
+
43
+ LLMs forget between sessions. Inline code comments rot. Wikis live outside the repo. clinotes gives your agent a structured, versioned memory layer it can read in ~200 tokens and expand only when needed.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install clinotes
49
+ ```
50
+
51
+ ## Quickstart
52
+
53
+ ```bash
54
+ clinotes init # scaffold .clinotes/
55
+ clinotes ls # show the index (L0)
56
+ clinotes show d1 # show a detail (L2)
57
+ ```
58
+
59
+ ## MCP Setup
60
+
61
+ Add clinotes to your editor so the LLM can recall and record project memory.
62
+
63
+ **Claude Code:**
64
+ ```bash
65
+ claude mcp add clinotes -- uvx clinotes-mcp
66
+ ```
67
+
68
+ **Cursor** (`.cursor/mcp.json`):
69
+ ```json
70
+ {
71
+ "mcpServers": {
72
+ "clinotes": {
73
+ "command": "uvx",
74
+ "args": ["clinotes-mcp"]
75
+ }
76
+ }
77
+ }
78
+ ```
79
+
80
+ ## Python API
81
+
82
+ ```python
83
+ from clinotes import note_decision, recall_index, recall_detail
84
+
85
+ # Record a decision
86
+ note_decision(
87
+ title="postgres over mysql",
88
+ why="client DBA only supports pg",
89
+ alternatives=["mysql", "sqlite"],
90
+ refs=["infra/db.py"]
91
+ )
92
+
93
+ # Recall
94
+ print(recall_index()) # L0 — cheap survey
95
+ print(recall_detail("d1")) # L2 — full detail
96
+ ```
97
+
98
+ ## Format
99
+
100
+ The on-disk layout, ID scheme, and frontmatter specification are defined in [SPEC.md](SPEC.md).
@@ -0,0 +1,13 @@
1
+ clinotes/__init__.py,sha256=o8XzDYfDQM35sttCoozIxJAyQD2geQaFIMMbf_vlnSY,418
2
+ clinotes/api.py,sha256=kGhUPLujd4jMJBwoRJ6V6tPYIHozsuL_4DPY_ldffeo,6443
3
+ clinotes/cli.py,sha256=cqUf3405x04SJfWKr_FBUPmzPnBxFq6XUEkuRzujays,1064
4
+ clinotes/ids.py,sha256=-j_bEcGRXgUT4Mi5tBDCUWy0GwnIDuOAIEshewzIGe8,1243
5
+ clinotes/index.py,sha256=wF6d8EHtwPiUsWJ9Nx0z6vFrbFMh3NqlEtJgoVtSBXc,3685
6
+ clinotes/schema.py,sha256=lZbQlJ9yO1hiaJ9_H67Y8dV3fQJs9X3_bFkT5QZuLCo,1887
7
+ clinotes/server.py,sha256=CmCX7-BzcI3eo4gc8cM5DsjDdKCgZHNnisq-7M7Q2K8,3315
8
+ clinotes/storage.py,sha256=Cug6X1X6v0ymPQJ7D-gnD2YZWC9CW1SKVd9w8aYDJ-4,4920
9
+ clinotes-0.1.0.dist-info/METADATA,sha256=a5b2n77g9juvr1DgrvhxoklYYEjBU2HZfMxJ45xslOY,2807
10
+ clinotes-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
11
+ clinotes-0.1.0.dist-info/entry_points.txt,sha256=ynv2iaU3ZkmkwKIdznu39DkbDTn9SzhwQD6O0sJ2irw,82
12
+ clinotes-0.1.0.dist-info/licenses/LICENSE,sha256=gIqmRCCMX5ZKT4TJtX53YnZC4f1ah-AKidCqDrT23Rk,1093
13
+ clinotes-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ clinotes = clinotes.cli:app
3
+ clinotes-mcp = clinotes.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Karthick Raja M
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.