sessionmemory 0.11.0__tar.gz → 0.13.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 (40) hide show
  1. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/PKG-INFO +1 -1
  2. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/pyproject.toml +1 -1
  3. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/pyproject.toml.orig +1 -1
  4. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/cli.py +2 -0
  5. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/inject.py +2 -2
  6. sessionmemory-0.13.0/src/sessionmemory/commands/local.py +134 -0
  7. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/path.py +4 -2
  8. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/bootstrap.py +4 -0
  9. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/doctor.py +87 -1
  10. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/gitinfo.py +31 -8
  11. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/inject.py +26 -2
  12. sessionmemory-0.13.0/src/sessionmemory/lib/localmd.py +430 -0
  13. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/paths.py +9 -2
  14. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/README.md +0 -0
  15. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/__init__.py +0 -0
  16. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/__init__.py +0 -0
  17. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/_common.py +0 -0
  18. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/delete.py +0 -0
  19. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/doctor.py +0 -0
  20. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/export.py +0 -0
  21. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/init.py +0 -0
  22. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/log.py +0 -0
  23. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/new.py +0 -0
  24. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/project.py +0 -0
  25. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/reindex.py +0 -0
  26. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/commands/search.py +0 -0
  27. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/__init__.py +0 -0
  28. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/atomic.py +0 -0
  29. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/backlog.py +0 -0
  30. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/config.py +0 -0
  31. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/embed.py +0 -0
  32. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/export.py +0 -0
  33. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/field.py +0 -0
  34. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/fieldindex.py +0 -0
  35. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/frontmatter.py +0 -0
  36. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/ids.py +0 -0
  37. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/log.py +0 -0
  38. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/registry.py +0 -0
  39. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/resolve.py +0 -0
  40. {sessionmemory-0.11.0 → sessionmemory-0.13.0}/src/sessionmemory/lib/specs.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: sessionmemory
3
- Version: 0.11.0
3
+ Version: 0.13.0
4
4
  Summary: Durable memory for coding agents, one folder of searchable pages per project.
5
5
  Author: Nathaniel Landau
6
6
  Author-email: Nathaniel Landau <github@natelandau.com>
@@ -11,7 +11,7 @@ description = "Durable memory for coding agents, one folder of searchable pages
11
11
  name = "sessionmemory"
12
12
  readme = "README.md"
13
13
  requires-python = ">=3.13,<3.15"
14
- version = "0.11.0"
14
+ version = "0.13.0"
15
15
 
16
16
  [[project.authors]]
17
17
  name = "Nathaniel Landau"
@@ -12,7 +12,7 @@
12
12
  name = "sessionmemory"
13
13
  readme = "README.md"
14
14
  requires-python = ">=3.13,<3.15"
15
- version = "0.11.0"
15
+ version = "0.13.0"
16
16
 
17
17
  [project.scripts]
18
18
  sessionmemory = "sessionmemory.cli:main"
@@ -12,6 +12,7 @@ from sessionmemory.commands import doctor as doctor_commands
12
12
  from sessionmemory.commands import export as export_commands
13
13
  from sessionmemory.commands import init as init_commands
14
14
  from sessionmemory.commands import inject as inject_commands
15
+ from sessionmemory.commands import local as local_commands
15
16
  from sessionmemory.commands import log as log_commands
16
17
  from sessionmemory.commands import new as new_commands
17
18
  from sessionmemory.commands import path as path_commands
@@ -73,6 +74,7 @@ app.command("reindex", help="Rebuild this project's search indexes, or every pro
73
74
  app.command("search", help="Search this project's learnings by meaning, or its logs with --logs.")(
74
75
  search_commands.search_command
75
76
  )
77
+ app.add_typer(local_commands.app, name="local")
76
78
  app.add_typer(new_commands.app, name="new")
77
79
 
78
80
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from pathlib import Path # noqa: TC003
5
+ from pathlib import Path
6
6
 
7
7
  import typer
8
8
 
@@ -18,7 +18,7 @@ def inject_command(cwd: Path | None = CWD, command: str = COMMAND, *, as_json: b
18
18
  """Print what this project's session should start with."""
19
19
  vault = require_vault()
20
20
  slug = require_project(vault, cwd)
21
- injection = inject.build(vault, slug)
21
+ injection = inject.build(vault, slug, cwd=cwd if cwd is not None else Path.cwd())
22
22
  if as_json:
23
23
  emit_json(inject.payload(injection, command=command))
24
24
  return
@@ -0,0 +1,134 @@
1
+ """Commands that keep a checkout's CLAUDE.local.md in the vault and link it back."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import typer
8
+ from nclutils import pp
9
+
10
+ from sessionmemory.commands._common import (
11
+ VersionedGroup,
12
+ emit_json,
13
+ emit_value,
14
+ fail,
15
+ require_project,
16
+ require_vault,
17
+ )
18
+ from sessionmemory.lib import localmd
19
+
20
+ app = typer.Typer(
21
+ cls=VersionedGroup,
22
+ no_args_is_help=True,
23
+ help="Keep this project's CLAUDE.local.md in the vault and link it into checkouts.",
24
+ )
25
+
26
+ CWD = typer.Option(None, "--cwd", help="Directory to resolve the project from.")
27
+ JSON = typer.Option(False, "--json", help="Emit JSON instead of prose.") # noqa: FBT003
28
+
29
+
30
+ def _checkout(cwd: Path | None) -> localmd.Checkout:
31
+ """Resolve the project and locate the checkout, failing on any library error.
32
+
33
+ Args:
34
+ cwd (Path | None): The directory to resolve from, or the shell's directory.
35
+
36
+ Returns:
37
+ localmd.Checkout: The checkout holding `cwd`.
38
+ """
39
+ vault = require_vault()
40
+ slug = require_project(vault, cwd)
41
+ try:
42
+ return localmd.checkout(vault, slug, cwd if cwd is not None else Path.cwd())
43
+ except localmd.LocalMdError as err:
44
+ fail(err.message, err.details)
45
+
46
+
47
+ @app.command(
48
+ "adopt",
49
+ help="Move this checkout's CLAUDE.local.md into the vault and link it back.",
50
+ )
51
+ def adopt_command(cwd: Path | None = CWD) -> None:
52
+ """Move this checkout's CLAUDE.local.md into the vault and link it back.
53
+
54
+ Raises:
55
+ Exit: When the file cannot be adopted.
56
+ """
57
+ co = _checkout(cwd)
58
+ try:
59
+ result = localmd.adopt(co)
60
+ except localmd.LocalMdError as err:
61
+ fail(err.message, err.details)
62
+
63
+ for target in result.relative_imports:
64
+ pp.warning(f"@{target} resolves from the vault copy's folder and will not load")
65
+ if not result.already_linked:
66
+ pp.warning("the hooks commit the vault copy to the vault's git remote")
67
+ emit_value(str(result.target))
68
+
69
+
70
+ @app.command(
71
+ "link",
72
+ help="Link this checkout to the vault's CLAUDE.local.md when that is safe.",
73
+ )
74
+ def link_command(cwd: Path | None = CWD, as_json: bool = JSON) -> None: # noqa: FBT001
75
+ """Link this checkout to the vault's CLAUDE.local.md when that is safe.
76
+
77
+ Raises:
78
+ Exit: When a file or link is in the way.
79
+ """
80
+ co = _checkout(cwd)
81
+ try:
82
+ result = localmd.link(co)
83
+ except localmd.LocalMdError as err:
84
+ fail(err.message, err.details)
85
+
86
+ if as_json:
87
+ emit_json({"status": result.status, "link": str(result.link), "target": str(result.target)})
88
+ if result.status == "conflict":
89
+ raise typer.Exit(1)
90
+ return
91
+
92
+ if result.status == "conflict":
93
+ fail(
94
+ f"{result.link} is in the way of the vault copy ({result.state})",
95
+ ["Run `local adopt` to move it into the vault, or `local status` to compare them."],
96
+ )
97
+ if result.status == "none":
98
+ pp.info("the vault holds no CLAUDE.local.md for this project")
99
+ return
100
+ emit_value(str(result.link))
101
+
102
+
103
+ @app.command("status", help="Report how this checkout's CLAUDE.local.md relates to the vault.")
104
+ def status_command(cwd: Path | None = CWD, as_json: bool = JSON) -> None: # noqa: FBT001
105
+ """Report how this checkout's CLAUDE.local.md relates to the vault."""
106
+ co = _checkout(cwd)
107
+ try:
108
+ current = localmd.state(co)
109
+ match = localmd.contents_match(co)
110
+ ignored = co.ignored()
111
+ tracked = co.tracked()
112
+ except localmd.LocalMdError as err:
113
+ fail(err.message, err.details)
114
+
115
+ if as_json:
116
+ emit_json(
117
+ {
118
+ "state": str(current),
119
+ "link": str(co.link),
120
+ "target": str(co.target),
121
+ "ignored": ignored,
122
+ "tracked": tracked,
123
+ "match": match,
124
+ }
125
+ )
126
+ return
127
+
128
+ emit_value(f"state: {current}")
129
+ emit_value(f"link: {co.link}")
130
+ emit_value(f"target: {co.target}")
131
+ emit_value(f"ignored: {'yes' if ignored else 'no'}")
132
+ emit_value(f"tracked: {'yes' if tracked else 'no'}")
133
+ if current is localmd.State.DIVERGED:
134
+ emit_value(f"contents: {'identical' if match else 'different'}")
@@ -11,7 +11,8 @@ from sessionmemory.commands._common import emit_value, require_project, require_
11
11
  from sessionmemory.lib import paths
12
12
 
13
13
  # Typer lists an Enum's members in --help and rejects anything else at parse time. The
14
- # members are the keys of `paths.project_paths`, with `project` standing for `project_dir`.
14
+ # members are the keys of `paths.project_paths`, with `project` standing for `project_dir`
15
+ # and `local` for `local_md`.
15
16
  PathKind = enum.Enum(
16
17
  "PathKind",
17
18
  {
@@ -25,6 +26,7 @@ PathKind = enum.Enum(
25
26
  "runbooks",
26
27
  "reference",
27
28
  "backlog",
29
+ "local",
28
30
  )
29
31
  },
30
32
  type=str,
@@ -38,5 +40,5 @@ def path_command(kind: PathKind = KIND_ARGUMENT, cwd: Path | None = CWD_OPTION)
38
40
  """Print one of this project's vault paths."""
39
41
  vault = require_vault()
40
42
  slug = require_project(vault, cwd)
41
- key = "project_dir" if kind.value == "project" else kind.value
43
+ key = {"project": "project_dir", "local": "local_md"}.get(kind.value, kind.value)
42
44
  emit_value(paths.project_paths(vault, slug)[key])
@@ -36,6 +36,10 @@ GITIGNORE = """\
36
36
  # Plans are scratch for the session that writes them and never belong in history.
37
37
  projects/*/plans/
38
38
 
39
+ # A project's CLAUDE.local.md is private to its person but belongs in the vault, so it is
40
+ # re-included over a global ignore rule that names it.
41
+ !projects/*/CLAUDE.local.md
42
+
39
43
  # Obsidian's per-machine window state, which conflicts on every sync.
40
44
  .obsidian/workspace*.json
41
45
 
@@ -14,7 +14,7 @@ from dataclasses import dataclass
14
14
  from pathlib import Path
15
15
  from typing import TYPE_CHECKING
16
16
 
17
- from sessionmemory.lib import field, fieldindex, paths, registry, specs
17
+ from sessionmemory.lib import field, fieldindex, localmd, paths, registry, specs
18
18
  from sessionmemory.lib.frontmatter import (
19
19
  FrontmatterError,
20
20
  MissingFrontmatterError,
@@ -236,6 +236,91 @@ def spec_statuses(vault: Path, _embedder: Embedder) -> list[Finding]:
236
236
  return findings
237
237
 
238
238
 
239
+ _DIVERGED = (
240
+ "differs from the vault copy; copy the newer one over the vault copy, "
241
+ "delete the checkout file, and run local link"
242
+ )
243
+ _TRACKED = "tracked by git; run git rm --cached CLAUDE.local.md before adopting it"
244
+ _UNIGNORED_LINK = "not ignored by git; run local link to add it to info/exclude"
245
+ _UNIGNORED_FILE = "not ignored by git; run local adopt to replace it with an ignored link"
246
+
247
+
248
+ def _state_message(co: localmd.Checkout, *, ignored: bool) -> str | None:
249
+ """Name what is wrong with an untracked entry at the link path, given its state."""
250
+ current = localmd.state(co)
251
+ if current is localmd.State.DIVERGED:
252
+ try:
253
+ match = localmd.contents_match(co)
254
+ except OSError:
255
+ return None
256
+ if match is False:
257
+ return _DIVERGED
258
+ return None if match is None or ignored else _UNIGNORED_FILE
259
+ if ignored:
260
+ return None
261
+ if current is localmd.State.FOREIGN_LINK:
262
+ return (
263
+ f"not ignored by git, and a symlink to {co.link.resolve()} rather than the "
264
+ "vault copy; remove it, then run local link"
265
+ )
266
+ return _UNIGNORED_LINK
267
+
268
+
269
+ def _checkout_message(co: localmd.Checkout) -> str | None:
270
+ """Name what is wrong at one checkout's link path, with advice that fits its state.
271
+
272
+ A tracked file and a diverged file each get one finding and no ignore advice, since
273
+ `local link` refuses both and the first remedy is a different command. An
274
+ unreadable file, or one git cannot inspect, is not judged.
275
+ """
276
+ if not (co.link.is_symlink() or co.link.exists()):
277
+ return None
278
+ try:
279
+ tracked = co.tracked()
280
+ ignored = co.ignored()
281
+ except localmd.LocalMdError:
282
+ return None
283
+ return _TRACKED if tracked else _state_message(co, ignored=ignored)
284
+
285
+
286
+ def local_instructions(vault: Path, _embedder: Embedder) -> list[Finding]:
287
+ """Report problems with a project's vault copy of CLAUDE.local.md.
288
+
289
+ Covers a relative `@import` that cannot resolve from the vault folder, and at the
290
+ registered root a tracked file, a regular file that has drifted from the vault
291
+ copy, and a link or file that git does not ignore.
292
+ """
293
+ try:
294
+ projects = registry.load(vault)
295
+ except registry.RegistryError:
296
+ # dead_projects reports an unreadable registry.
297
+ projects = {}
298
+ findings = []
299
+ for slug in paths.iter_project_slugs(vault):
300
+ copy = paths.local_md_path(vault, slug)
301
+ if not copy.is_file():
302
+ continue
303
+ try:
304
+ text = copy.read_text(encoding="utf-8", errors="replace")
305
+ except OSError:
306
+ continue
307
+ findings.extend(
308
+ Finding(
309
+ "local", str(copy), f"@{target} resolves from the vault folder and will not load"
310
+ )
311
+ for target in localmd.relative_imports(text)
312
+ )
313
+ project = projects.get(slug)
314
+ if not project or not project.root or not Path(project.root).is_dir():
315
+ continue
316
+ root = Path(project.root)
317
+ co = localmd.Checkout(worktree=root, link=root / paths.LOCAL_MD_FILE, target=copy)
318
+ message = _checkout_message(co)
319
+ if message is not None:
320
+ findings.append(Finding("local", str(co.link), message))
321
+ return findings
322
+
323
+
239
324
  def _is_stale(directory: Path, embedder: Embedder) -> str | None:
240
325
  index = fieldindex.index_path(directory, embedder)
241
326
  if not index.is_file():
@@ -280,6 +365,7 @@ CHECKS: tuple[Callable[[Path, Embedder], list[Finding]], ...] = (
280
365
  ticked_backlog_lines,
281
366
  dangling_references,
282
367
  spec_statuses,
368
+ local_instructions,
283
369
  stale_indexes,
284
370
  )
285
371
 
@@ -20,9 +20,13 @@ import os
20
20
  import subprocess
21
21
  from dataclasses import dataclass
22
22
  from pathlib import Path
23
+ from typing import TYPE_CHECKING
23
24
 
24
25
  from sessionmemory.lib import registry
25
26
 
27
+ if TYPE_CHECKING:
28
+ from collections.abc import Mapping
29
+
26
30
  GIT_TIMEOUT_SECONDS = 10
27
31
 
28
32
  # The one git failure that is an answer rather than an outage. Every other non-zero exit,
@@ -60,20 +64,23 @@ class GitContext:
60
64
  return self.repo_root != self.worktree_root
61
65
 
62
66
 
63
- def _git(cwd: Path, *args: str) -> _GitAnswer:
64
- """Run a git command and report both its output and whether git answered at all.
67
+ def run_git(
68
+ cwd: Path, *args: str, env: Mapping[str, str] | None = None
69
+ ) -> subprocess.CompletedProcess[str] | None:
70
+ """Run git in `cwd` under the C locale, for a caller that reads its exit code itself.
65
71
 
66
72
  Args:
67
73
  cwd (Path): The directory to run in.
68
74
  *args: Arguments passed to git.
75
+ env (Mapping[str, str] | None): The environment to start from, in place of the
76
+ process's own.
69
77
 
70
78
  Returns:
71
- _GitAnswer: The stripped stdout, and whether git reached a verdict. A non-zero
72
- exit counts as a verdict only when git says the directory is not a
73
- repository.
79
+ subprocess.CompletedProcess[str] | None: The finished process whatever its exit
80
+ code, or None when git could not be run or did not finish in time.
74
81
  """
75
82
  try:
76
- completed = subprocess.run( # noqa: S603
83
+ return subprocess.run( # noqa: S603
77
84
  ["git", *args], # noqa: S607
78
85
  cwd=cwd,
79
86
  capture_output=True,
@@ -81,11 +88,27 @@ def _git(cwd: Path, *args: str) -> _GitAnswer:
81
88
  check=False,
82
89
  timeout=GIT_TIMEOUT_SECONDS,
83
90
  # The C locale keeps git's own messages in the wording the classifier reads.
84
- env={**os.environ, "LC_ALL": "C", "LANGUAGE": ""},
91
+ env={**(os.environ if env is None else env), "LC_ALL": "C", "LANGUAGE": ""},
85
92
  )
86
93
  except (OSError, subprocess.SubprocessError):
87
- return _GitAnswer(stdout=None, answered=False)
94
+ return None
95
+
96
+
97
+ def _git(cwd: Path, *args: str) -> _GitAnswer:
98
+ """Run a git command and report both its output and whether git answered at all.
88
99
 
100
+ Args:
101
+ cwd (Path): The directory to run in.
102
+ *args: Arguments passed to git.
103
+
104
+ Returns:
105
+ _GitAnswer: The stripped stdout, and whether git reached a verdict. A non-zero
106
+ exit counts as a verdict only when git says the directory is not a
107
+ repository.
108
+ """
109
+ completed = run_git(cwd, *args)
110
+ if completed is None:
111
+ return _GitAnswer(stdout=None, answered=False)
89
112
  if completed.returncode != 0:
90
113
  return _GitAnswer(stdout=None, answered=_NOT_A_REPOSITORY in completed.stderr.lower())
91
114
  return _GitAnswer(stdout=completed.stdout.strip() or None, answered=True)
@@ -11,7 +11,7 @@ from dataclasses import dataclass
11
11
  from datetime import date, timedelta
12
12
  from typing import TYPE_CHECKING
13
13
 
14
- from sessionmemory.lib import backlog, config, field, paths, registry
14
+ from sessionmemory.lib import backlog, config, field, localmd, paths, registry
15
15
 
16
16
  if TYPE_CHECKING:
17
17
  from pathlib import Path
@@ -33,6 +33,7 @@ class Injection:
33
33
  runbooks: tuple[str, ...] = ()
34
34
  reviewed: str = ""
35
35
  review_due: bool = False
36
+ unadopted_local: bool = False
36
37
 
37
38
 
38
39
  def _sort_key(title: str) -> str:
@@ -95,7 +96,24 @@ def _review_due(*, learnings: int, reviewed: str, today: str) -> bool:
95
96
  return elapsed > timedelta(days=REVIEW_INTERVAL_DAYS)
96
97
 
97
98
 
98
- def build(vault: Path, slug: str, *, today: str | None = None) -> Injection:
99
+ def _unadopted_local(vault: Path, slug: str, cwd: Path | None) -> bool:
100
+ """Report whether `cwd` holds a plain CLAUDE.local.md the vault does not have yet.
101
+
102
+ A hint must never fail a session start, so any git or checkout failure reads as no hint.
103
+ `tracked` runs only for an unadopted file, so a project without one costs no extra git call.
104
+ """
105
+ if cwd is None:
106
+ return False
107
+ try:
108
+ co = localmd.checkout(vault, slug, cwd)
109
+ return localmd.state(co) is localmd.State.UNADOPTED and not co.tracked()
110
+ except localmd.LocalMdError:
111
+ return False
112
+
113
+
114
+ def build(
115
+ vault: Path, slug: str, *, today: str | None = None, cwd: Path | None = None
116
+ ) -> Injection:
99
117
  """Read the project's pages and files; the index is never consulted here.
100
118
 
101
119
  Specs are counted rather than listed. A spec outlives the work it describes, so a
@@ -118,6 +136,7 @@ def build(vault: Path, slug: str, *, today: str | None = None) -> Injection:
118
136
  review_due=_review_due(
119
137
  learnings=len(titles), reviewed=reviewed, today=today or config.today()
120
138
  ),
139
+ unadopted_local=_unadopted_local(vault, slug, cwd),
121
140
  )
122
141
 
123
142
 
@@ -203,6 +222,10 @@ def render(injection: Injection, *, command: str = "sessionmemory") -> str:
203
222
  lines.append(f" {injection.open_backlog} open backlog {item}")
204
223
  spec = "spec" if injection.specs == 1 else "specs"
205
224
  lines.append(f" {injection.specs} {spec} in specs/")
225
+ if injection.unadopted_local:
226
+ lines.append(
227
+ f" CLAUDE.local.md here is not in the vault yet; `{command} local adopt --cwd .` moves it there"
228
+ )
206
229
  return "\n".join(lines)
207
230
 
208
231
 
@@ -218,4 +241,5 @@ def payload(injection: Injection, *, command: str) -> dict[str, object]:
218
241
  "runbooks": list(injection.runbooks),
219
242
  "reviewed": injection.reviewed,
220
243
  "review_due": injection.review_due,
244
+ "unadopted_local": injection.unadopted_local,
221
245
  }
@@ -0,0 +1,430 @@
1
+ """Link a checkout's `CLAUDE.local.md` to the copy kept in the vault.
2
+
3
+ This is the one place the states of a checkout's link are known. The vault holds the
4
+ file so it survives a lost machine and is shared by every checkout of a project, and
5
+ each checkout holds a symlink to it.
6
+
7
+ The link is absolute. The vault's root differs from machine to machine and a linked
8
+ worktree sits at a different depth from the main checkout, so no relative path is
9
+ correct for both. It sits at the git work tree's top level, which is where Claude Code
10
+ looks for the file, rather than at the registered root or the working directory.
11
+
12
+ The ignore entry goes in `info/exclude`, never in a `.gitignore`, because a
13
+ `.gitignore` is a committed file and linking must not leave a change to commit. Git
14
+ reads `info/exclude` from the shared git directory, so one entry covers every linked
15
+ worktree of a repository.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import enum
21
+ import os
22
+ import re
23
+ import uuid
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+ from typing import TYPE_CHECKING, Literal
27
+
28
+ from sessionmemory.lib import atomic, gitinfo, paths
29
+
30
+ if TYPE_CHECKING:
31
+ import subprocess
32
+
33
+ LinkStatus = Literal["created", "present", "none", "conflict"]
34
+
35
+ _FENCE = re.compile(r"^\s*(```|~~~)")
36
+ # A list marker on an indented line opens a nested item, not an indented code block.
37
+ _LIST_ITEM = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s")
38
+ _INLINE_CODE = re.compile(r"`[^`]*`")
39
+ # Four spaces or a tab open an indented code block.
40
+ _INDENTED_CODE = (" ", "\t")
41
+ # Prose punctuation that follows an import, as in "see @a.md, then @b.md)".
42
+ _TRAILING = ",.;:!?)]}>'\""
43
+ # An import starts a line or follows whitespace, so the `@` in an address is not one.
44
+ _IMPORT = re.compile(r"(?:^|(?<=\s))@(\S+)")
45
+
46
+
47
+ class LocalMdError(Exception):
48
+ """A failure to link that the caller reports rather than recovers from."""
49
+
50
+ def __init__(self, message: str, details: list[str] | None = None) -> None:
51
+ """Create the error.
52
+
53
+ Args:
54
+ message (str): The one-line reason.
55
+ details (list[str] | None): Follow-up lines for the reader.
56
+ """
57
+ super().__init__(message)
58
+ self.message = message
59
+ self.details = details or []
60
+
61
+
62
+ class State(enum.StrEnum):
63
+ """What a checkout holds at the link path, relative to the vault copy."""
64
+
65
+ LINKED = "linked"
66
+ NOT_LINKED = "not linked"
67
+ UNADOPTED = "unadopted"
68
+ DIVERGED = "diverged"
69
+ FOREIGN_LINK = "foreign link"
70
+ DANGLING = "dangling"
71
+ NONE = "none"
72
+
73
+
74
+ def _git_safe_env() -> dict[str, str]:
75
+ """The process environment without any `GIT_`-prefixed variable.
76
+
77
+ A git hook exports `GIT_DIR` and `GIT_INDEX_FILE`, which would retarget these calls
78
+ at the repository running the hook. A prefix rather than a fixed set, because the
79
+ indexed `GIT_CONFIG_KEY_<n>` family cannot be enumerated.
80
+ """
81
+ return {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
82
+
83
+
84
+ def _git(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
85
+ """Run git in `cwd`.
86
+
87
+ Args:
88
+ cwd (Path): The directory to run in.
89
+ *args: Arguments passed to git.
90
+
91
+ Returns:
92
+ subprocess.CompletedProcess[str]: The finished process, whatever its exit code.
93
+
94
+ Raises:
95
+ LocalMdError: When git cannot be run or does not finish in time.
96
+ """
97
+ done = gitinfo.run_git(cwd, *args, env=_git_safe_env())
98
+ if done is None:
99
+ msg = f"git could not run in {cwd}"
100
+ raise LocalMdError(msg, [f"git {args[0]} did not start or did not finish in time"])
101
+ return done
102
+
103
+
104
+ @dataclass(frozen=True)
105
+ class Checkout:
106
+ """One git work tree and the vault copy its link should point at."""
107
+
108
+ worktree: Path
109
+ link: Path
110
+ target: Path
111
+
112
+ def tracked(self) -> bool:
113
+ """Report whether git tracks the link path.
114
+
115
+ Returns:
116
+ bool: True when `CLAUDE.local.md` is committed or staged in this checkout.
117
+ """
118
+ done = _git(self.worktree, "ls-files", "--error-unmatch", "--", paths.LOCAL_MD_FILE)
119
+ return done.returncode == 0
120
+
121
+ def ignored(self) -> bool:
122
+ """Report whether git already ignores the link path, by any rule.
123
+
124
+ Returns:
125
+ bool: True when `git check-ignore` matches the link path.
126
+
127
+ Raises:
128
+ LocalMdError: When git fails for any reason other than "not ignored", such as
129
+ a directory that is not a repository.
130
+ """
131
+ done = _git(self.worktree, "check-ignore", "-q", "--", paths.LOCAL_MD_FILE)
132
+ if done.returncode not in (0, 1):
133
+ msg = f"git check-ignore failed in {self.worktree}"
134
+ raise LocalMdError(msg, [done.stderr.strip()] if done.stderr.strip() else [])
135
+ return done.returncode == 0
136
+
137
+
138
+ def checkout(vault: Path, slug: str, cwd: Path) -> Checkout:
139
+ """Locate the work tree holding `cwd` and the vault copy for `slug`.
140
+
141
+ Args:
142
+ vault (Path): The vault root.
143
+ slug (str): The project's slug.
144
+ cwd (Path): Any directory inside the checkout.
145
+
146
+ Returns:
147
+ Checkout: The work tree's top level, its link path, and the vault copy.
148
+
149
+ Raises:
150
+ LocalMdError: When `cwd` is not inside a git work tree.
151
+ """
152
+ done = _git(cwd, "rev-parse", "--show-toplevel")
153
+ toplevel = done.stdout.strip()
154
+ if done.returncode != 0 or not toplevel:
155
+ msg = f"{cwd} is not inside a git work tree"
156
+ raise LocalMdError(msg)
157
+ worktree = Path(toplevel).resolve()
158
+ return Checkout(
159
+ worktree=worktree,
160
+ link=worktree / paths.LOCAL_MD_FILE,
161
+ target=paths.local_md_path(vault, slug),
162
+ )
163
+
164
+
165
+ def state(co: Checkout) -> State:
166
+ """Classify what the checkout holds at the link path.
167
+
168
+ Args:
169
+ co (Checkout): The checkout to inspect.
170
+
171
+ Returns:
172
+ State: The link's state.
173
+ """
174
+ target_is_file = co.target.is_file()
175
+ if co.link.is_symlink():
176
+ if not co.link.exists():
177
+ return State.DANGLING
178
+ if target_is_file and co.link.resolve() == co.target.resolve():
179
+ return State.LINKED
180
+ return State.FOREIGN_LINK
181
+ if co.link.exists():
182
+ return State.DIVERGED if target_is_file else State.UNADOPTED
183
+ return State.NOT_LINKED if target_is_file else State.NONE
184
+
185
+
186
+ def contents_match(co: Checkout) -> bool | None:
187
+ """Compare the checkout's file with the vault copy byte for byte.
188
+
189
+ Args:
190
+ co (Checkout): The checkout to inspect.
191
+
192
+ Returns:
193
+ bool | None: None unless both are regular files, which a link is not.
194
+ """
195
+ if co.link.is_symlink() or not co.link.is_file() or not co.target.is_file():
196
+ return None
197
+ return co.link.read_bytes() == co.target.read_bytes()
198
+
199
+
200
+ def ensure_ignored(co: Checkout) -> bool:
201
+ """Make git ignore the link path without touching any committed file.
202
+
203
+ Args:
204
+ co (Checkout): The checkout to hide the link in.
205
+
206
+ Returns:
207
+ bool: True when it wrote an entry, False when git already ignored the path.
208
+
209
+ Raises:
210
+ LocalMdError: When git cannot name its exclude file.
211
+ """
212
+ if co.ignored():
213
+ return False
214
+
215
+ done = _git(co.worktree, "rev-parse", "--git-path", "info/exclude")
216
+ if done.returncode != 0 or not done.stdout.strip():
217
+ msg = "git did not name its exclude file"
218
+ raise LocalMdError(msg, [done.stderr.strip()] if done.stderr.strip() else [])
219
+
220
+ exclude = co.worktree / done.stdout.strip()
221
+ exclude.parent.mkdir(parents=True, exist_ok=True)
222
+ existing = exclude.read_text(encoding="utf-8", errors="replace") if exclude.exists() else ""
223
+ # A `.gitignore` negation outranks info/exclude, so an entry already there would only
224
+ # be appended again on every call without ever taking effect.
225
+ if paths.LOCAL_MD_FILE in (line.strip() for line in existing.splitlines()):
226
+ return False
227
+ prefix = "\n" if existing and not existing.endswith("\n") else ""
228
+ with exclude.open("a", encoding="utf-8") as handle:
229
+ handle.write(f"{prefix}{paths.LOCAL_MD_FILE}\n")
230
+ return True
231
+
232
+
233
+ def relative_imports(text: str) -> list[str]:
234
+ """List the `@path` imports in `text` that resolve against the file's own directory.
235
+
236
+ Args:
237
+ text (str): The markdown to scan.
238
+
239
+ Returns:
240
+ list[str]: Each import path, without its `@`, in order. Absolute and home paths
241
+ are left out, since they mean the same file from the vault.
242
+ """
243
+ found: list[str] = []
244
+ fence: str | None = None
245
+ for line in text.splitlines():
246
+ if opened := _FENCE.match(line):
247
+ marker = opened.group(1)
248
+ if fence is None:
249
+ fence = marker
250
+ elif fence == marker:
251
+ fence = None
252
+ continue
253
+ if fence is not None or (line.startswith(_INDENTED_CODE) and not _LIST_ITEM.match(line)):
254
+ continue
255
+ # A space rather than nothing, so text either side of a code span stays apart.
256
+ for match in _IMPORT.finditer(_INLINE_CODE.sub(" ", line)):
257
+ target = match.group(1).rstrip(_TRAILING)
258
+ if target and not target.startswith(("/", "~")):
259
+ found.append(target)
260
+ return found
261
+
262
+
263
+ def place_link(link: Path, target: Path) -> None:
264
+ """Point `link` at `target`, replacing a symlink or file already there.
265
+
266
+ The symlink is built at a temporary name and renamed over `link`, so a crash leaves
267
+ either the old entry or the new link and never neither. Use `create_link` when
268
+ nothing is at `link`, since a crash here can leave the temporary name behind.
269
+
270
+ Args:
271
+ link (Path): Where the symlink goes.
272
+ target (Path): What it points at.
273
+ """
274
+ temp = link.with_name(f".{link.name}.{uuid.uuid4().hex}.tmp")
275
+ temp.unlink(missing_ok=True)
276
+ temp.symlink_to(target)
277
+ try:
278
+ temp.replace(link)
279
+ except OSError:
280
+ temp.unlink(missing_ok=True)
281
+ raise
282
+
283
+
284
+ def create_link(link: Path, target: Path) -> bool:
285
+ """Point a new `link` at `target`, refusing to replace anything that appeared there.
286
+
287
+ Creating the symlink is exclusive, so a file written at `link` after its state was
288
+ read is never overwritten, and no temporary name is left behind.
289
+
290
+ Args:
291
+ link (Path): Where the symlink goes.
292
+ target (Path): What it points at.
293
+
294
+ Returns:
295
+ bool: True when it created the link, False when something already sat at `link`.
296
+ """
297
+ try:
298
+ link.symlink_to(target)
299
+ except FileExistsError:
300
+ return False
301
+ return True
302
+
303
+
304
+ @dataclass(frozen=True)
305
+ class LinkResult:
306
+ """The outcome of linking one checkout."""
307
+
308
+ status: LinkStatus
309
+ link: Path
310
+ target: Path
311
+ state: State
312
+ added_ignore: bool
313
+
314
+
315
+ def link(co: Checkout) -> LinkResult:
316
+ """Link the checkout to the vault copy when that is safe.
317
+
318
+ Args:
319
+ co (Checkout): The checkout to link.
320
+
321
+ Returns:
322
+ LinkResult: `none` when the vault holds no copy, `present` when already linked,
323
+ `created` when it placed the link, and `conflict` when a file or foreign
324
+ link is in the way and nothing was changed. `present` and `created` also
325
+ make git ignore the link path.
326
+
327
+ Raises:
328
+ LocalMdError: When git tracks `CLAUDE.local.md`, since replacing a committed
329
+ file would leave a change to commit.
330
+ """
331
+ current = state(co)
332
+
333
+ def result(
334
+ status: LinkStatus, *, added_ignore: bool = False, now: State | None = None
335
+ ) -> LinkResult:
336
+ return LinkResult(status, co.link, co.target, now or current, added_ignore)
337
+
338
+ if not co.target.is_file():
339
+ return result("none")
340
+ if co.tracked():
341
+ msg = f"{paths.LOCAL_MD_FILE} is tracked by git in {co.worktree}"
342
+ raise LocalMdError(msg, ["Remove it from the index before linking it."])
343
+ if current is State.LINKED:
344
+ return result("present", added_ignore=ensure_ignored(co))
345
+ if current in {State.DIVERGED, State.FOREIGN_LINK}:
346
+ return result("conflict")
347
+
348
+ added = ensure_ignored(co)
349
+ if current is State.DANGLING:
350
+ place_link(co.link, co.target)
351
+ elif not create_link(co.link, co.target):
352
+ return result("conflict", added_ignore=added, now=state(co))
353
+ return result("created", added_ignore=added)
354
+
355
+
356
+ @dataclass(frozen=True)
357
+ class AdoptResult:
358
+ """The outcome of adopting one checkout's file into the vault."""
359
+
360
+ target: Path
361
+ already_linked: bool
362
+ relative_imports: list[str]
363
+ added_ignore: bool
364
+
365
+
366
+ def adopt(co: Checkout) -> AdoptResult:
367
+ """Move the checkout's `CLAUDE.local.md` into the vault and link it back.
368
+
369
+ The vault copy is written and read back before the original is replaced, so a
370
+ failed copy leaves the original untouched.
371
+
372
+ Args:
373
+ co (Checkout): The checkout holding the file to adopt.
374
+
375
+ Returns:
376
+ AdoptResult: Where the vault copy lives, whether the checkout was already
377
+ linked, the file's relative `@` imports, and whether an ignore entry was
378
+ written.
379
+
380
+ Raises:
381
+ LocalMdError: When there is no regular file to adopt, git tracks it, the vault
382
+ already holds different content, a symlink points elsewhere, or the file is
383
+ not UTF-8.
384
+ """
385
+ current = state(co)
386
+ if current is State.LINKED:
387
+ return AdoptResult(
388
+ target=co.target,
389
+ already_linked=True,
390
+ relative_imports=[],
391
+ added_ignore=ensure_ignored(co),
392
+ )
393
+ if co.tracked():
394
+ msg = f"{paths.LOCAL_MD_FILE} is tracked by git in {co.worktree}"
395
+ raise LocalMdError(msg, ["Remove it from the index before adopting it."])
396
+ if current is State.FOREIGN_LINK:
397
+ msg = f"{co.link} is a symlink to {co.link.resolve()}, not to the vault copy"
398
+ raise LocalMdError(msg)
399
+ if current in {State.NONE, State.NOT_LINKED, State.DANGLING}:
400
+ msg = f"no {paths.LOCAL_MD_FILE} in {co.worktree}"
401
+ raise LocalMdError(msg)
402
+ if not co.link.is_file():
403
+ msg = f"{co.link} is not a regular file"
404
+ raise LocalMdError(msg)
405
+ if current is State.DIVERGED and not contents_match(co):
406
+ msg = f"{co.link} and {co.target} differ"
407
+ raise LocalMdError(msg, ["Keep one of them, delete the other, and run this again."])
408
+
409
+ original = co.link.read_bytes()
410
+ try:
411
+ text = original.decode("utf-8")
412
+ except UnicodeDecodeError as exc:
413
+ msg = f"{co.link} is not valid UTF-8"
414
+ raise LocalMdError(msg, [str(exc)]) from exc
415
+
416
+ if current is State.UNADOPTED:
417
+ atomic.write_text(co.target, text)
418
+ if co.target.read_bytes() != original:
419
+ co.target.unlink(missing_ok=True)
420
+ msg = f"the copy at {co.target} does not match {co.link}"
421
+ raise LocalMdError(msg, [f"{co.link} was left untouched."])
422
+
423
+ added = ensure_ignored(co)
424
+ place_link(co.link, co.target)
425
+ return AdoptResult(
426
+ target=co.target,
427
+ already_linked=False,
428
+ relative_imports=relative_imports(text),
429
+ added_ignore=added,
430
+ )
@@ -2,8 +2,8 @@
2
2
 
3
3
  `learnings/` and `logs/` are fields: flat directories of pages, each with its own
4
4
  index. `specs/` is indexed too, with the same table but a derived embedding input, though
5
- it is not a field. `plans/`, `runbooks/`, `reference/`, and `backlog.md` sit beside them
6
- and are never indexed. A project's files are found by its slug and nothing else; there
5
+ it is not a field. `plans/`, `runbooks/`, `reference/`, `backlog.md`, and `CLAUDE.local.md` sit
6
+ beside them and are never indexed. A project's files are found by its slug and nothing else; there
7
7
  is no global scope.
8
8
  """
9
9
 
@@ -24,6 +24,7 @@ PLANS_DIR = "plans"
24
24
  RUNBOOKS_DIR = "runbooks"
25
25
  REFERENCE_DIR = "reference"
26
26
  BACKLOG_FILE = "backlog.md"
27
+ LOCAL_MD_FILE = "CLAUDE.local.md"
27
28
 
28
29
  FIELD_DIRS: tuple[str, ...] = (LEARNINGS_DIR, LOGS_DIR)
29
30
 
@@ -68,6 +69,11 @@ def backlog_path(vault: Path, slug: str) -> Path:
68
69
  return project_dir(vault, slug) / BACKLOG_FILE
69
70
 
70
71
 
72
+ def local_md_path(vault: Path, slug: str) -> Path:
73
+ """Return the vault copy of the project's CLAUDE.local.md."""
74
+ return project_dir(vault, slug) / LOCAL_MD_FILE
75
+
76
+
71
77
  def project_paths(vault: Path, slug: str) -> dict[str, str]:
72
78
  """Return every path a caller of `sessionmemory project --json` reads, by its payload key.
73
79
 
@@ -82,6 +88,7 @@ def project_paths(vault: Path, slug: str) -> dict[str, str]:
82
88
  "runbooks": str(runbooks_dir(vault, slug)),
83
89
  "reference": str(reference_dir(vault, slug)),
84
90
  "backlog": str(backlog_path(vault, slug)),
91
+ "local_md": str(local_md_path(vault, slug)),
85
92
  }
86
93
 
87
94
 
File without changes