Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b04ffd9c8f | ||
|
|
f202800d7d | ||
|
|
a9f071a25d |
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "SH=\"${CLAUDE_SKILL_DIR}/scripts/inject-plan.sh\"; [ -f \"$SH\" ] || SH=$(ls \"$HOME/.claude/skills/planning-with-files/scripts/inject-plan.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/inject-plan.sh\" 2>/dev/null | head -1); [ -n \"$SH\" ] && [ -f \"$SH\" ] && sh \"$SH\" --context=precompact; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
---
|
||||
|
||||
# Planning with Files
|
||||
|
||||
@@ -94,11 +94,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -144,9 +157,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -171,6 +186,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -258,7 +339,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"name": "planning-with-files",
|
||||
"source": "./",
|
||||
"description": "Persistent file-based planning for AI coding agents. Crash-proof markdown plans that survive context loss, /clear, and crashes, with an opt-in completion gate and multi-agent shared state on disk. Manus-style, installs across 60+ agents via the SKILL.md standard.",
|
||||
"version": "3.8.1"
|
||||
"version": "3.8.2"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planning-with-files",
|
||||
"version": "3.8.1",
|
||||
"version": "3.8.2",
|
||||
"description": "Persistent file-based planning for AI coding agents. Crash-proof markdown plans (task_plan.md, findings.md, progress.md) that survive context loss and /clear, with an opt-in completion gate and multi-agent shared state. Manus-style. Works with Claude Code, Codex CLI, Cursor, Kiro, OpenCode and 60+ agents via the SKILL.md standard. Includes Arabic, German, Spanish, and Chinese (Simplified and Traditional).",
|
||||
"author": {
|
||||
"name": "OthmanAdi",
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -94,11 +94,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -144,9 +157,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -171,6 +186,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -258,7 +339,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -94,11 +94,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -144,9 +157,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -171,6 +186,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -258,7 +339,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -94,11 +94,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -144,9 +157,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -171,6 +186,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -258,7 +339,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
---
|
||||
|
||||
# Planning with Files
|
||||
|
||||
@@ -94,11 +94,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -144,9 +157,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -171,6 +186,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -258,7 +339,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -94,11 +94,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -144,9 +157,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -171,6 +186,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -258,7 +339,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: planning-with-files
|
||||
description: "Manus-style persistent file-based planning for AI coding agents: keeps task_plan.md, findings.md, and progress.md on disk so work survives context loss and /clear. Use when asked to plan out, break down, or organize a multi-step project, research task, or any work requiring 5+ tool calls. Hermes adaptation with minimal notes."
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
---
|
||||
|
||||
> Hermes note: lifecycle automation for this skill is provided by the Hermes adapter plugin in `.hermes/plugins/planning-with-files/`.
|
||||
|
||||
@@ -14,6 +14,7 @@ Usage: python3 session-catchup.py [project-path]
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -44,20 +45,75 @@ def detect_ide() -> str:
|
||||
return 'unknown'
|
||||
|
||||
|
||||
def normalize_project_path(project_path: str) -> str:
|
||||
"""Absolute, platform-native spelling of a project path.
|
||||
|
||||
Git Bash / MSYS2 hands us /c/Users/... where Claude Code recorded
|
||||
C:\\Users\\..., so the drive letter is restored before anything else.
|
||||
"""
|
||||
p = project_path
|
||||
if len(p) >= 3 and p[0] == '/' and p[2] == '/' and p[1].isalpha():
|
||||
p = p[1].upper() + ':' + p[2:]
|
||||
if ':' in p or '\\' in p:
|
||||
try:
|
||||
p = str(Path(p).resolve())
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return p
|
||||
|
||||
|
||||
def claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Spell a project path the way Claude Code names ~/.claude/projects entries.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-'. The count is in UTF-16
|
||||
code units, not codepoints: Claude Code walks the name as UTF-16, so a
|
||||
non-BMP character (an emoji in a folder name) costs TWO dashes. Passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def store_candidates(normalized: str) -> List[str]:
|
||||
"""Every ~/.claude/projects spelling Claude Code has used, exact first.
|
||||
|
||||
Current versions fold '_' to '-' as well, but stores written before that
|
||||
change kept it, and both are live on disk, so both spellings are probed.
|
||||
The leading-dash-stripped forms cover stores created by pre-v3.8.0
|
||||
versions of this script.
|
||||
"""
|
||||
candidates: List[str] = []
|
||||
for width in (2, 1):
|
||||
exact = claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for candidate in list(candidates):
|
||||
stripped = candidate[1:] if candidate.startswith('-') else candidate
|
||||
if stripped and stripped not in candidates:
|
||||
candidates.append(stripped)
|
||||
return candidates
|
||||
|
||||
|
||||
def get_project_dir_claude(project_path: str) -> Path:
|
||||
"""Convert project path to Claude's storage path format."""
|
||||
sanitized = project_path.replace('/', '-')
|
||||
if not sanitized.startswith('-'):
|
||||
sanitized = '-' + sanitized
|
||||
# Claude Code keeps underscores in project-dir names; probe the exact
|
||||
# spelling first and fall back to the legacy '-' spelling for stores
|
||||
# created by older versions of this script (v3.8.0 fix).
|
||||
"""Resolve Claude Code's session store directory for a project path.
|
||||
|
||||
Probes the exact spelling first and falls back through the legacy
|
||||
spellings, so a store written by any past version still resolves. Paths
|
||||
containing '.', ' ' or any other non-alphanumeric character are folded
|
||||
the same way Claude Code folds them, which is what makes recovery work
|
||||
for hidden directories such as ~/.dotfiles (issue #209).
|
||||
"""
|
||||
normalized = normalize_project_path(project_path)
|
||||
projects_root = Path.home() / '.claude' / 'projects'
|
||||
if not (projects_root / sanitized).is_dir():
|
||||
legacy = sanitized.replace('_', '-')
|
||||
if (projects_root / legacy).is_dir():
|
||||
return projects_root / legacy
|
||||
return projects_root / sanitized
|
||||
candidates = store_candidates(normalized)
|
||||
for candidate in candidates:
|
||||
if (projects_root / candidate).is_dir():
|
||||
return projects_root / candidate
|
||||
return projects_root / candidates[0]
|
||||
|
||||
|
||||
def get_project_dir_opencode(project_path: str) -> Optional[Path]:
|
||||
@@ -85,6 +141,82 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
try:
|
||||
data = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(data, dict):
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
def canonical(value: str) -> str:
|
||||
expanded = os.path.expanduser(value)
|
||||
try:
|
||||
return str(Path(expanded).resolve())
|
||||
except (OSError, ValueError):
|
||||
return os.path.abspath(expanded)
|
||||
|
||||
a, b = canonical(left), canonical(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_project_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def get_sessions_sorted_opencode(storage_dir: Path) -> List[Path]:
|
||||
"""
|
||||
Get all OpenCode session files sorted by modification time.
|
||||
@@ -267,7 +399,11 @@ def main():
|
||||
if not project_dir.exists():
|
||||
return
|
||||
|
||||
sessions = get_sessions_sorted(project_dir)
|
||||
sessions, cwd_notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(project_dir), project_path
|
||||
)
|
||||
if cwd_notice:
|
||||
print(cwd_notice)
|
||||
if len(sessions) < 2:
|
||||
return
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ Usage: python3 session-catchup.py [project-path]
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -17,20 +18,75 @@ from typing import List, Dict, Optional, Tuple
|
||||
PLANNING_FILES = ['task_plan.md', 'progress.md', 'findings.md']
|
||||
|
||||
|
||||
def get_project_dir(project_path: str) -> Tuple[Optional[Path], Optional[str]]:
|
||||
"""Resolve session storage path for the current runtime variant."""
|
||||
sanitized = project_path.replace('/', '-')
|
||||
if not sanitized.startswith('-'):
|
||||
sanitized = '-' + sanitized
|
||||
# Claude Code keeps underscores in project-dir names; probe the exact
|
||||
# spelling first and fall back to the legacy '-' spelling for stores
|
||||
# created by older versions of this script (v3.8.0 fix).
|
||||
projects_root = Path.home() / '.claude' / 'projects'
|
||||
if (not (projects_root / sanitized).is_dir()
|
||||
and (projects_root / sanitized.replace('_', '-')).is_dir()):
|
||||
sanitized = sanitized.replace('_', '-')
|
||||
def normalize_project_path(project_path: str) -> str:
|
||||
"""Absolute, platform-native spelling of a project path.
|
||||
|
||||
claude_path = projects_root / sanitized
|
||||
Git Bash / MSYS2 hands us /c/Users/... where Claude Code recorded
|
||||
C:\\Users\\..., so the drive letter is restored before anything else.
|
||||
"""
|
||||
p = project_path
|
||||
if len(p) >= 3 and p[0] == '/' and p[2] == '/' and p[1].isalpha():
|
||||
p = p[1].upper() + ':' + p[2:]
|
||||
if ':' in p or '\\' in p:
|
||||
try:
|
||||
p = str(Path(p).resolve())
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return p
|
||||
|
||||
|
||||
def claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Spell a project path the way Claude Code names ~/.claude/projects entries.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-'. The count is in UTF-16
|
||||
code units, not codepoints: Claude Code walks the name as UTF-16, so a
|
||||
non-BMP character (an emoji in a folder name) costs TWO dashes. Passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def store_candidates(normalized: str) -> List[str]:
|
||||
"""Every ~/.claude/projects spelling Claude Code has used, exact first.
|
||||
|
||||
Current versions fold '_' to '-' as well, but stores written before that
|
||||
change kept it, and both are live on disk, so both spellings are probed.
|
||||
The leading-dash-stripped forms cover stores created by pre-v3.8.0
|
||||
versions of this script.
|
||||
"""
|
||||
candidates: List[str] = []
|
||||
for width in (2, 1):
|
||||
exact = claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for candidate in list(candidates):
|
||||
stripped = candidate[1:] if candidate.startswith('-') else candidate
|
||||
if stripped and stripped not in candidates:
|
||||
candidates.append(stripped)
|
||||
return candidates
|
||||
|
||||
|
||||
def get_project_dir(project_path: str) -> Tuple[Optional[Path], Optional[str]]:
|
||||
"""Resolve session storage path for the current runtime variant.
|
||||
|
||||
Probes the exact ~/.claude/projects spelling first and falls back through
|
||||
the legacy spellings, so a store written by any past version still
|
||||
resolves. Paths containing '.', ' ' or any other non-alphanumeric
|
||||
character are folded the same way Claude Code folds them, which is what
|
||||
makes recovery work for hidden directories such as ~/.dotfiles (#209).
|
||||
"""
|
||||
projects_root = Path.home() / '.claude' / 'projects'
|
||||
candidates = store_candidates(normalize_project_path(project_path))
|
||||
claude_path = projects_root / candidates[0]
|
||||
for candidate in candidates:
|
||||
if (projects_root / candidate).is_dir():
|
||||
claude_path = projects_root / candidate
|
||||
break
|
||||
|
||||
# Codex stores sessions in ~/.codex/sessions with a different format.
|
||||
# Avoid silently scanning Claude paths when running from Codex skill folder.
|
||||
@@ -53,6 +109,82 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
try:
|
||||
data = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(data, dict):
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
def canonical(value: str) -> str:
|
||||
expanded = os.path.expanduser(value)
|
||||
try:
|
||||
return str(Path(expanded).resolve())
|
||||
except (OSError, ValueError):
|
||||
return os.path.abspath(expanded)
|
||||
|
||||
a, b = canonical(left), canonical(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_project_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def parse_session_messages(session_file: Path) -> List[Dict]:
|
||||
"""Parse all messages from a session file, preserving order."""
|
||||
messages = []
|
||||
@@ -177,7 +309,11 @@ def main():
|
||||
# No previous sessions, nothing to catch up on
|
||||
return
|
||||
|
||||
sessions = get_sessions_sorted(project_dir)
|
||||
sessions, cwd_notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(project_dir), project_path
|
||||
)
|
||||
if cwd_notice:
|
||||
print(cwd_notice)
|
||||
if len(sessions) < 1:
|
||||
return
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -70,11 +70,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -120,9 +133,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -147,6 +162,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -234,7 +315,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -94,11 +94,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -144,9 +157,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -171,6 +186,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -258,7 +339,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -2,6 +2,22 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [3.8.2] - 2026-07-24
|
||||
|
||||
### Fixed
|
||||
- **Session recovery silently found nothing for any project path containing a dot, a space, or any other non-alphanumeric character (closes #209, reported by @seathatflowsinourveins).** Claude Code names `~/.claude/projects/` entries by folding every character outside `[A-Za-z0-9-]` to `-`, but three copies of `session-catchup.py` still used a manual replace chain that handled only `/`, `\` and `:`. Those copies computed a directory name Claude Code never writes, no candidate matched, and `main()` returned at the `exists()` check with exit 0, so catchup after `/clear` produced nothing and reported nothing. Hidden directories such as `~/.dotfiles` were the common case. One of the three sits on a live install route: `marketplace.json` declares `"source": "./"`, so the plugin root is the repository root and the SKILL.md restore block resolves `${CLAUDE_PLUGIN_ROOT}/scripts/session-catchup.py` for every plugin user on Linux, macOS or Git Bash. Measured against a real store holding 89 sessions, the shipped resolver produced 0 bytes where the fixed one produces 11336 and recovers 166 messages. The root, `.hermes` and `.mastracode` copies now share the same normalize, sanitize and candidate helpers as the canonical copy, keeping their existing function names, signatures and the `.mastracode` Codex guard (`tests/test_catchup_store_resolution_parity.py`).
|
||||
- **An emoji in a folder name made a project unresolvable in every copy, including the canonical one.** Claude Code walks the directory name as UTF-16, so a non-BMP character costs two dashes, while the sanitizer counted codepoints and produced one. Folding is now counted in UTF-16 code units. The rules were measured against 24 real stores whose recorded `cwd` could be read: one model matches all 24, and it also showed that current versions fold `_` while older stores kept it, so both spellings stay in the probe chain and the exact spelling is still probed first.
|
||||
- The 15 copies that already folded dots keep that behavior unchanged. `.kiro` is untouched because it ships a different program that reads `.kiro/plan/` and never looks at `~/.claude/projects`.
|
||||
|
||||
### Security
|
||||
- **Two projects whose paths fold to the same `~/.claude/projects` name could read each other's transcripts.** The mapping is lossy, so `client.acme` and `client-acme` share one directory. Until this release the resolver did not fold those characters and simply missed the directory; folding the way Claude Code folds means it now finds it, so catchup filters transcripts by the `cwd` they record. A transcript is skipped only when it positively records a different project, transcripts that record none are kept because the field is not present in every generation of the format, and a directory whose transcripts all belong to another project is reported instead of used. The filter works per session rather than rejecting the whole directory, because in a collision both projects live there permanently and rejecting it would cost the project its own history. Reproduced with a planted canary against the preceding commit and again after the fix (`tests/test_catchup_cross_project_guard.py`).
|
||||
|
||||
### Verification
|
||||
- Suite 305 to 311 passing, 282 subtests, plus `sync-ide-folders.py --verify` clean. The new parity suite discovers the copies with `git ls-files` and runs one vector table through each, so the drift that produced #209 fails the suite instead of hiding in a single file.
|
||||
|
||||
### Thanks
|
||||
- seathatflowsinourveins reported the dot-folding mismatch with an exact blob reference, a working reproduction, and a correct reading of the silent return path (#209).
|
||||
|
||||
## [3.8.1] - 2026-07-21
|
||||
|
||||
### Fixed
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ authors:
|
||||
- family-names: Adi
|
||||
given-names: Ahmad Othman Ammar
|
||||
alias: OthmanAdi
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
date-released: "2026-07-21"
|
||||
license: MIT
|
||||
url: "https://github.com/OthmanAdi/planning-with-files"
|
||||
|
||||
+5
-1
@@ -106,6 +106,10 @@ These amazing people have contributed code, documentation, or significant improv
|
||||
|
||||
### Other Contributors
|
||||
|
||||
- **[@seathatflowsinourveins](https://github.com/seathatflowsinourveins)** - [Issue #209](https://github.com/OthmanAdi/planning-with-files/issues/209)
|
||||
- Reported that `session-catchup.py` never folded `.` while Claude Code does, so any project path containing a dot resolved to a `~/.claude/projects` directory that is never written, citing the exact blob, the two sanitize branches, and the `main()` line where the miss returns exit 0 with no output
|
||||
- **Impact:** v3.8.2 folds every character Claude Code folds in the three remaining copies (one of them the copy every `/plugin install` runs on Linux, macOS and Git Bash), counts UTF-16 code units so emoji folder names resolve, and adds a per-session `cwd` filter so two projects sharing one folded directory name cannot read each other's transcripts
|
||||
|
||||
- **[@fd44fdg](https://github.com/fd44fdg)** - [Issue #208](https://github.com/OthmanAdi/planning-with-files/issues/208)
|
||||
- Reported that a stale `.planning/<id>/` directory silently shadowed a fresh root `task_plan.md` in the Pi extension while a false "No task_plan.md found" warning fired on every write and edit, with a root-cause trace against `resolvePlanPaths` and the `runtime.ts` warning path
|
||||
- **Impact:** v3.8.1 anchors Pi plan resolution on the nearest ancestor with planning state (bounded by the `.git` repository boundary), labels every injection with the resolved plan id so shadowing is visible, and kills the subdirectory warning loop; bundled Pi extension bumped to 1.2.2
|
||||
@@ -380,4 +384,4 @@ If you've contributed and don't see your name here, please open an issue! We wan
|
||||
|
||||
**Total Contributors:** 50+ and growing!
|
||||
|
||||
*Last updated: July 14, 2026*
|
||||
*Last updated: July 24, 2026*
|
||||
|
||||
@@ -506,6 +506,7 @@ One hook fire measures 289ms wall-clock since the v3.6.0 optimization, down from
|
||||
|
||||
| Version | Highlights |
|
||||
|---------|------------|
|
||||
| **v3.8.2** | **Session recovery silently found nothing for any project path containing a dot, a space, or any other non-alphanumeric character** (closes #209, reported by @seathatflowsinourveins). Three copies of `session-catchup.py` still folded only `/`, `\` and `:`, and one of them is the copy every `/plugin install` runs on Linux, macOS and Git Bash. Against a real store holding 89 sessions the shipped resolver produced 0 bytes where the fix produces 11336 and recovers 166 messages. Folding now counts UTF-16 code units, so emoji folder names resolve too, and a per-session `cwd` filter stops two projects that fold to one directory name from reading each other's transcripts. One vector table now runs across every copy, so this drift cannot come back. Suite at 311. |
|
||||
| **v3.8.1** | **Pi extension: plan resolution no longer depends on the live shell cwd** (closes #208, reported by @fd44fdg). An agent that cd'd into a subdirectory lost the plan, recitation went dark, and the "No task_plan.md found" warning fired on every write. Resolution now anchors on the nearest ancestor with planning state, bounded by the `.git` repository boundary, with slug-validation and containment parity with the sh resolver; every injection states which plan it resolved (`plan: <id>`), making slug-over-root shadowing visible. Also: `init-session` heredocs never carried the v3.8.0 Next Step section; all copies fixed with an output-level regression test. Gated by an Opus adversarial pass plus a five-lens Sonnet reliability fleet. |
|
||||
| **v3.8.0** | **The Stop hook never fired on macOS or Linux** (a dead install-path fallback stacked on PowerShell-first dispatch), and **session recovery searched a project directory that does not exist** for POSIX or underscore project paths; both fixed with tests that execute the hooks end to end. Opt-in structure-aware injection (`PWF_INJECT=smart`) keeps the active phase and decision journal in the window late in long plans. Next Step pointer in the templates, tool-result outcomes in session catchup, macOS CI leg plus a BSD-userland simulation harness, `resolve-plan-dir.ps1` parity with fail-closed containment, UTF-8-safe ledger truncation, pinned line endings, and a rebuilt README with honest benchmark charts. Suite at 301. |
|
||||
| **v3.7.0** | **Agent Skills standard layout ships in-tree**: `.agents/skills/planning-with-files/` carries the full canonical surface, so tools that read the standard path natively (Zed, Amp, Warp, Devin, Antigravity, Gemini CLI, Cursor) discover the current skill from a plain `git clone`. Locked into the 18-entry parity set; `plan-doctor.sh` now ships in every synced IDE folder. |
|
||||
|
||||
+140
-23
@@ -14,6 +14,7 @@ Usage: python3 session-catchup.py [project-path]
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -44,39 +45,75 @@ def detect_ide() -> str:
|
||||
return 'unknown'
|
||||
|
||||
|
||||
def get_project_dir_claude(project_path: str) -> Path:
|
||||
"""Convert project path to Claude's storage path format.
|
||||
def normalize_project_path(project_path: str) -> str:
|
||||
"""Absolute, platform-native spelling of a project path.
|
||||
|
||||
Windows paths (C:\\Users\\... or Git Bash /c/Users/...) need the drive
|
||||
colon and backslashes sanitized too, not just forward slashes, and
|
||||
Claude's actual sanitized form has no leading dash for those (the drive
|
||||
letter isn't a separator). Real Unix absolute paths keep their existing
|
||||
leading-dash behavior unchanged (path is used as-is, matching Claude's
|
||||
convention there).
|
||||
Git Bash / MSYS2 hands us /c/Users/... where Claude Code recorded
|
||||
C:\\Users\\..., so the drive letter is restored before anything else.
|
||||
"""
|
||||
p = project_path
|
||||
if len(p) >= 3 and p[0] == '/' and p[2] == '/' and p[1].isalpha():
|
||||
# Git Bash / MSYS2: /c/Users/... -> C:/Users/...
|
||||
p = p[1].upper() + ':' + p[2:]
|
||||
if ':' in p or '\\' in p:
|
||||
try:
|
||||
p = str(Path(p).resolve())
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
sanitized = p.replace('\\', '-').replace('/', '-').replace(':', '-')
|
||||
else:
|
||||
sanitized = p.replace('/', '-')
|
||||
if not sanitized.startswith('-'):
|
||||
sanitized = '-' + sanitized
|
||||
# Claude Code keeps underscores in project-dir names; probe the exact
|
||||
# spelling first and fall back to the legacy '-' spelling for stores
|
||||
# created by older versions of this script (v3.8.0 fix).
|
||||
return p
|
||||
|
||||
|
||||
def claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Spell a project path the way Claude Code names ~/.claude/projects entries.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-'. The count is in UTF-16
|
||||
code units, not codepoints: Claude Code walks the name as UTF-16, so a
|
||||
non-BMP character (an emoji in a folder name) costs TWO dashes. Passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def store_candidates(normalized: str) -> List[str]:
|
||||
"""Every ~/.claude/projects spelling Claude Code has used, exact first.
|
||||
|
||||
Current versions fold '_' to '-' as well, but stores written before that
|
||||
change kept it, and both are live on disk, so both spellings are probed.
|
||||
The leading-dash-stripped forms cover stores created by pre-v3.8.0
|
||||
versions of this script.
|
||||
"""
|
||||
candidates: List[str] = []
|
||||
for width in (2, 1):
|
||||
exact = claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for candidate in list(candidates):
|
||||
stripped = candidate[1:] if candidate.startswith('-') else candidate
|
||||
if stripped and stripped not in candidates:
|
||||
candidates.append(stripped)
|
||||
return candidates
|
||||
|
||||
|
||||
def get_project_dir_claude(project_path: str) -> Path:
|
||||
"""Resolve Claude Code's session store directory for a project path.
|
||||
|
||||
Probes the exact spelling first and falls back through the legacy
|
||||
spellings, so a store written by any past version still resolves. Paths
|
||||
containing '.', ' ' or any other non-alphanumeric character are folded
|
||||
the same way Claude Code folds them, which is what makes recovery work
|
||||
for hidden directories such as ~/.dotfiles (issue #209).
|
||||
"""
|
||||
normalized = normalize_project_path(project_path)
|
||||
projects_root = Path.home() / '.claude' / 'projects'
|
||||
if not (projects_root / sanitized).is_dir():
|
||||
legacy = sanitized.replace('_', '-')
|
||||
if (projects_root / legacy).is_dir():
|
||||
return projects_root / legacy
|
||||
return projects_root / sanitized
|
||||
candidates = store_candidates(normalized)
|
||||
for candidate in candidates:
|
||||
if (projects_root / candidate).is_dir():
|
||||
return projects_root / candidate
|
||||
return projects_root / candidates[0]
|
||||
|
||||
|
||||
def get_project_dir_opencode(project_path: str) -> Optional[Path]:
|
||||
@@ -104,6 +141,82 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
try:
|
||||
data = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(data, dict):
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
def canonical(value: str) -> str:
|
||||
expanded = os.path.expanduser(value)
|
||||
try:
|
||||
return str(Path(expanded).resolve())
|
||||
except (OSError, ValueError):
|
||||
return os.path.abspath(expanded)
|
||||
|
||||
a, b = canonical(left), canonical(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_project_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def get_sessions_sorted_opencode(storage_dir: Path) -> List[Path]:
|
||||
"""
|
||||
Get all OpenCode session files sorted by modification time.
|
||||
@@ -474,7 +587,11 @@ def main():
|
||||
if not project_dir.exists():
|
||||
return
|
||||
|
||||
sessions = get_sessions_sorted(project_dir)
|
||||
sessions, cwd_notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(project_dir), project_path
|
||||
)
|
||||
if cwd_notice:
|
||||
print(cwd_notice)
|
||||
if len(sessions) < 2:
|
||||
return
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
---
|
||||
|
||||
# نظام تخطيط الملفات
|
||||
|
||||
@@ -70,11 +70,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -120,9 +133,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -147,6 +162,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -230,7 +311,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
---
|
||||
|
||||
# Dateiplanungssystem
|
||||
|
||||
@@ -70,11 +70,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -120,9 +133,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -147,6 +162,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -230,7 +311,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
---
|
||||
|
||||
# Sistema de Planificación con Archivos
|
||||
|
||||
@@ -70,11 +70,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -120,9 +133,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -147,6 +162,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -230,7 +311,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ hooks:
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -70,11 +70,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -120,9 +133,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -147,6 +162,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -230,7 +311,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ hooks:
|
||||
command: "RESOLVED=\"\"; SCOPE=\"\"; SLUG_RE='^[A-Za-z0-9_][A-Za-z0-9._-]*$'; if [ -n \"${PLAN_ID:-}\" ] && printf \"%s\" \"$PLAN_ID\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${PLAN_ID}\" ]; then RESOLVED=\".planning/${PLAN_ID}\"; SCOPE=\"scoped\"; elif [ -f .planning/.active_plan ]; then AP=$(tr -d '\\r\\n[:space:]' < .planning/.active_plan 2>/dev/null); if [ -n \"$AP\" ] && printf \"%s\" \"$AP\" | grep -Eq \"$SLUG_RE\" && [ -d \".planning/${AP}\" ]; then RESOLVED=\".planning/${AP}\"; SCOPE=\"scoped\"; fi; fi; if [ -z \"$RESOLVED\" ] && [ -d .planning ]; then NEWEST=\"\"; NEWEST_MT=0; for d in .planning/*/; do d=\"${d%/}\"; n=$(basename \"$d\"); case \"$n\" in .*) continue;; esac; printf \"%s\" \"$n\" | grep -Eq \"$SLUG_RE\" || continue; [ -f \"$d/task_plan.md\" ] || continue; m=$(stat -c '%Y' \"$d\" 2>/dev/null || stat -f '%m' \"$d\" 2>/dev/null || date -r \"$d\" +%s 2>/dev/null || echo 0); if [ \"$m\" -gt \"$NEWEST_MT\" ] 2>/dev/null; then NEWEST_MT=\"$m\"; NEWEST=\"$d\"; fi; done; [ -n \"$NEWEST\" ] && { RESOLVED=\"$NEWEST\"; SCOPE=\"scoped\"; }; fi; if [ -z \"$RESOLVED\" ] && [ -f task_plan.md ]; then RESOLVED=\".\"; SCOPE=\"root\"; fi; [ -z \"$RESOLVED\" ] && exit 0; if [ \"$SCOPE\" = \"root\" ]; then PLAN_FILE=\"task_plan.md\"; PROGRESS_FILE=\"progress.md\"; ATTEST=\"\"; [ -f .plan-attestation ] && ATTEST=$(tr -d '\\r\\n[:space:]' < .plan-attestation 2>/dev/null); else PLAN_FILE=\"${RESOLVED}/task_plan.md\"; PROGRESS_FILE=\"${RESOLVED}/progress.md\"; ATTEST=\"\"; [ -f \"${RESOLVED}/.attestation\" ] && ATTEST=$(tr -d '\\r\\n[:space:]' < \"${RESOLVED}/.attestation\" 2>/dev/null); fi; [ -f \"$PLAN_FILE\" ] || exit 0; TAMPERED=0; ACTUAL=\"\"; if [ -n \"$ATTEST\" ]; then CD=\"${TMPDIR:-/tmp}/pwf-sha\"; mkdir -p \"$CD\" 2>/dev/null; KEY=$(printf \"%s\" \"$PLAN_FILE\" | { sha256sum 2>/dev/null || shasum -a 256 2>/dev/null; } | awk '{print $1}' | cut -c1-16); MT=$(stat -c '%Y' \"$PLAN_FILE\" 2>/dev/null || stat -f '%m' \"$PLAN_FILE\" 2>/dev/null || date -r \"$PLAN_FILE\" +%s 2>/dev/null || echo 0); CF=\"$CD/$KEY\"; CM=\"\"; CS=\"\"; if [ -f \"$CF\" ]; then CM=$(sed -n 1p \"$CF\" 2>/dev/null); CS=$(sed -n 2p \"$CF\" 2>/dev/null); fi; if [ -n \"$MT\" ] && [ \"$MT\" = \"$CM\" ] && [ -n \"$CS\" ]; then ACTUAL=\"$CS\"; else ACTUAL=$( (sha256sum \"$PLAN_FILE\" 2>/dev/null || shasum -a 256 \"$PLAN_FILE\" 2>/dev/null) | awk '{print $1}'); [ -n \"$ACTUAL\" ] && [ -n \"$MT\" ] && printf \"%s\\n%s\\n\" \"$MT\" \"$ACTUAL\" > \"$CF\" 2>/dev/null; fi; [ \"$ACTUAL\" != \"$ATTEST\" ] && TAMPERED=1; fi; echo '[planning-with-files] PreCompact: context compaction is about to occur.'; echo 'Before compaction completes: ensure progress.md captures recent actions and task_plan.md status reflects current phase.'; echo 'task_plan.md, findings.md, progress.md remain on disk and will be re-read after compaction.'; [ -n \"$ATTEST\" ] && echo \"Plan-SHA256 at compaction: $ATTEST\"; exit 0"
|
||||
metadata:
|
||||
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -70,11 +70,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -120,9 +133,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -147,6 +162,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -230,7 +311,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ hooks:
|
||||
- type: command
|
||||
command: "SH=\"${CLAUDE_SKILL_DIR}/scripts/inject-plan.sh\"; [ -f \"$SH\" ] || SH=$(ls \"$HOME/.claude/skills/planning-with-files/scripts/inject-plan.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/inject-plan.sh\" 2>/dev/null | head -1); [ -n \"$SH\" ] && [ -f \"$SH\" ] && sh \"$SH\" --context=precompact; exit 0"
|
||||
metadata:
|
||||
version: "3.8.1"
|
||||
version: "3.8.2"
|
||||
---
|
||||
|
||||
# Planning with Files
|
||||
|
||||
@@ -94,11 +94,24 @@ def normalize_path(project_path: str) -> str:
|
||||
return p
|
||||
|
||||
|
||||
def _claude_sanitize(path_str: str) -> str:
|
||||
"""Claude Code's project-dir name: every character outside [A-Za-z0-9_-]
|
||||
becomes '-'; underscores and the leading dash of POSIX absolute paths are
|
||||
KEPT (real stores look like -home-user-proj and C--Users-x-My_Repo)."""
|
||||
return re.sub(r'[^A-Za-z0-9_-]', '-', path_str)
|
||||
def _claude_sanitize(path_str: str, astral_width: int = 2) -> str:
|
||||
"""Claude Code's project-dir name for a project path.
|
||||
|
||||
Every character outside [A-Za-z0-9_-] becomes '-', and the leading dash of
|
||||
POSIX absolute paths is kept (real stores look like -home-user-proj). The
|
||||
count is in UTF-16 code units rather than codepoints, so a non-BMP
|
||||
character such as an emoji in a folder name costs TWO dashes; passing
|
||||
astral_width=1 produces the codepoint-width spelling for older stores.
|
||||
|
||||
Underscores are NOT universally kept: current versions fold '_' to '-'
|
||||
while older stores kept it, and both spellings are live on disk, so
|
||||
get_claude_project_dir() probes both.
|
||||
"""
|
||||
return re.sub(
|
||||
r'[^A-Za-z0-9_-]',
|
||||
lambda m: '-' * (astral_width if ord(m.group()) > 0xFFFF else 1),
|
||||
path_str,
|
||||
)
|
||||
|
||||
|
||||
def _newest_session_cwd_matches(project_dir: Path, normalized: str) -> bool:
|
||||
@@ -144,9 +157,11 @@ def get_claude_project_dir(project_path: str) -> Path:
|
||||
|
||||
primary = _claude_sanitize(normalized)
|
||||
candidates = [primary]
|
||||
legacy_underscore = primary.replace('_', '-')
|
||||
if legacy_underscore not in candidates:
|
||||
candidates.append(legacy_underscore)
|
||||
for width in (2, 1):
|
||||
exact = _claude_sanitize(normalized, width)
|
||||
for spelling in (exact, exact.replace('_', '-')):
|
||||
if spelling not in candidates:
|
||||
candidates.append(spelling)
|
||||
for cand in list(candidates):
|
||||
stripped = cand[1:] if cand.startswith('-') else cand
|
||||
if stripped and stripped not in candidates:
|
||||
@@ -171,6 +186,72 @@ def get_sessions_sorted(project_dir: Path) -> List[Path]:
|
||||
return sorted(main_sessions, key=safe_stat_mtime, reverse=True)
|
||||
|
||||
|
||||
def claude_session_cwd(session_file: Path) -> Optional[str]:
|
||||
"""The cwd a Claude Code transcript records, or None if it records none."""
|
||||
try:
|
||||
with open(session_file, 'r', encoding='utf-8', errors='replace') as f:
|
||||
for _ in range(50):
|
||||
line = f.readline()
|
||||
if not line:
|
||||
break
|
||||
data = json_loads(line)
|
||||
if data:
|
||||
cwd = data.get('cwd')
|
||||
if isinstance(cwd, str) and cwd:
|
||||
return cwd
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def same_project_path(left: str, right: str) -> bool:
|
||||
"""Compare two absolute paths the way the host filesystem would."""
|
||||
a, b = normalize_for_compare(left), normalize_for_compare(right)
|
||||
if os.name == 'nt':
|
||||
a, b = a.lower(), b.lower()
|
||||
return a == b
|
||||
|
||||
|
||||
def filter_sessions_by_cwd(sessions: List[Path], project_path: str) -> Tuple[List[Path], Optional[str]]:
|
||||
"""Drop transcripts that positively belong to a different project.
|
||||
|
||||
Claude Code folds project paths into a single directory name, so two
|
||||
projects whose paths differ only in folded characters (client.acme and
|
||||
client-acme both fold to client-acme) share one store. Without this
|
||||
filter a catchup in one of them prints the other's conversation into the
|
||||
fresh context.
|
||||
|
||||
Fail open: transcripts that record no cwd are kept, because that field is
|
||||
not present in every generation of the format, and a store whose sessions
|
||||
all record another project is reported rather than silently used.
|
||||
Returns (sessions_to_use, notice).
|
||||
"""
|
||||
project_cmp = normalize_path(project_path)
|
||||
mine: List[Path] = []
|
||||
unknown: List[Path] = []
|
||||
foreign: List[str] = []
|
||||
for session in sessions:
|
||||
cwd = claude_session_cwd(session)
|
||||
if cwd is None:
|
||||
unknown.append(session)
|
||||
elif same_project_path(cwd, project_cmp):
|
||||
mine.append(session)
|
||||
else:
|
||||
foreign.append(cwd)
|
||||
|
||||
if mine:
|
||||
keep = [s for s in sessions if s in mine or s in unknown]
|
||||
return keep, None
|
||||
if foreign:
|
||||
return [], (
|
||||
"[planning-with-files] Session catchup skipped: "
|
||||
f"{Path(sorted(set(foreign))[0]).name} and this project share one "
|
||||
"~/.claude/projects directory, so no transcript here belongs to "
|
||||
f"{project_cmp}."
|
||||
)
|
||||
return unknown, None
|
||||
|
||||
|
||||
def safe_stat_mtime(path: Path) -> float:
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
@@ -258,7 +339,12 @@ def get_session_candidates(project_path: str) -> Tuple[str, Iterable[Path]]:
|
||||
|
||||
claude_project_dir = get_claude_project_dir(project_path)
|
||||
if claude_project_dir.exists():
|
||||
return 'claude', get_sessions_sorted(claude_project_dir)
|
||||
sessions, notice = filter_sessions_by_cwd(
|
||||
get_sessions_sorted(claude_project_dir), project_path
|
||||
)
|
||||
if notice:
|
||||
print(notice)
|
||||
return 'claude', sessions
|
||||
return 'claude', []
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Two projects that fold to one store directory must not read each other.
|
||||
|
||||
Claude Code names ~/.claude/projects entries by folding every character
|
||||
outside [A-Za-z0-9-] to '-'. That mapping is lossy, so /home/dev/client.acme
|
||||
and /home/dev/client-acme both land in -home-dev-client-acme and share a
|
||||
single directory of transcripts. Since v3.8.2 the resolver folds the same way
|
||||
Claude Code does, which means it now finds that shared directory instead of
|
||||
missing it, so catchup has to decide which transcripts in it are actually
|
||||
this project's.
|
||||
|
||||
The rule under test: a transcript is skipped only when it positively records
|
||||
a different cwd. Transcripts that record none are kept, because the field is
|
||||
not present in every generation of the format, and a directory whose
|
||||
transcripts all belong to another project is reported rather than used.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
ROOT_SCRIPT = REPO_ROOT / "scripts" / "session-catchup.py"
|
||||
|
||||
VICTIM = "/home/dev/client-acme"
|
||||
DONOR = "/home/dev/client.acme"
|
||||
CANARY = "ACME_MERGER_PRICE_IS_FOUR_HUNDRED_MILLION"
|
||||
|
||||
|
||||
def guarded_scripts() -> list[Path]:
|
||||
out = subprocess.run(
|
||||
["git", "ls-files", "*session-catchup.py"],
|
||||
cwd=REPO_ROOT, capture_output=True, text=True, check=True,
|
||||
).stdout.split()
|
||||
scripts = []
|
||||
for rel in out:
|
||||
path = REPO_ROOT / rel
|
||||
if path.is_file() and "def filter_sessions_by_cwd" in path.read_text(encoding="utf-8"):
|
||||
scripts.append(path)
|
||||
return sorted(scripts)
|
||||
|
||||
|
||||
def load_module(script_path: Path, alias: str):
|
||||
spec = importlib.util.spec_from_file_location(alias, script_path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def write_session(directory: Path, name: str, cwd: str | None, body: str) -> Path:
|
||||
"""A minimal transcript: optional cwd, a planning-file write, then a message."""
|
||||
path = directory / name
|
||||
lines = []
|
||||
first = {"type": "user", "message": {"content": "start of session " + name}}
|
||||
if cwd is not None:
|
||||
first["cwd"] = cwd
|
||||
lines.append(first)
|
||||
lines.append({
|
||||
"type": "assistant",
|
||||
"message": {"content": [
|
||||
{"type": "tool_use", "name": "Write",
|
||||
"input": {"file_path": (cwd or "/home/dev/x") + "/task_plan.md"}},
|
||||
]},
|
||||
})
|
||||
lines.append({
|
||||
"type": "assistant",
|
||||
"message": {"content": [{"type": "text", "text": body}]},
|
||||
})
|
||||
path.write_text(
|
||||
"\n".join(json.dumps(line) for line in lines) + "\n", encoding="utf-8"
|
||||
)
|
||||
return path
|
||||
|
||||
|
||||
class CrossProjectGuardTests(unittest.TestCase):
|
||||
"""Unit level, run against every copy that carries the guard."""
|
||||
|
||||
def setUp(self):
|
||||
self.scripts = guarded_scripts()
|
||||
self.assertTrue(self.scripts, "no copy exposes filter_sessions_by_cwd")
|
||||
|
||||
def _each(self):
|
||||
for script in self.scripts:
|
||||
rel = script.relative_to(REPO_ROOT).as_posix()
|
||||
module = load_module(script, f"g_{abs(hash(str(script)))}")
|
||||
yield rel, module
|
||||
|
||||
def test_foreign_only_store_yields_nothing_and_says_so(self):
|
||||
for rel, module in self._each():
|
||||
with self.subTest(copy=rel), tempfile.TemporaryDirectory() as tmp:
|
||||
d = Path(tmp)
|
||||
sessions = [write_session(d, "a.jsonl", DONOR, CANARY)]
|
||||
kept, notice = module.filter_sessions_by_cwd(sessions, VICTIM)
|
||||
self.assertEqual([], kept, f"{rel} kept another project's transcript")
|
||||
self.assertIsNotNone(notice, f"{rel} skipped silently")
|
||||
|
||||
def test_mixed_store_keeps_only_this_project(self):
|
||||
for rel, module in self._each():
|
||||
with self.subTest(copy=rel), tempfile.TemporaryDirectory() as tmp:
|
||||
d = Path(tmp)
|
||||
foreign = write_session(d, "a.jsonl", DONOR, CANARY)
|
||||
mine = write_session(d, "b.jsonl", VICTIM, "my own work")
|
||||
kept, notice = module.filter_sessions_by_cwd([foreign, mine], VICTIM)
|
||||
self.assertEqual([mine], kept, f"{rel} did not isolate the project")
|
||||
self.assertIsNone(notice)
|
||||
|
||||
def test_transcripts_without_a_cwd_are_kept(self):
|
||||
"""Fail open: older transcripts carry no cwd and must still be recovered."""
|
||||
for rel, module in self._each():
|
||||
with self.subTest(copy=rel), tempfile.TemporaryDirectory() as tmp:
|
||||
d = Path(tmp)
|
||||
legacy = write_session(d, "a.jsonl", None, "legacy transcript")
|
||||
kept, notice = module.filter_sessions_by_cwd([legacy], VICTIM)
|
||||
self.assertEqual([legacy], kept, f"{rel} dropped a legacy transcript")
|
||||
self.assertIsNone(notice)
|
||||
|
||||
def test_own_transcripts_pass_through_untouched(self):
|
||||
for rel, module in self._each():
|
||||
with self.subTest(copy=rel), tempfile.TemporaryDirectory() as tmp:
|
||||
d = Path(tmp)
|
||||
a = write_session(d, "a.jsonl", VICTIM, "one")
|
||||
b = write_session(d, "b.jsonl", VICTIM, "two")
|
||||
kept, notice = module.filter_sessions_by_cwd([a, b], VICTIM)
|
||||
self.assertEqual([a, b], kept)
|
||||
self.assertIsNone(notice)
|
||||
|
||||
|
||||
class CrossProjectGuardEndToEndTests(unittest.TestCase):
|
||||
"""Run the real script against a store shared by two projects."""
|
||||
|
||||
def _run(self, home: Path, project: str) -> str:
|
||||
env = dict(os.environ)
|
||||
env["HOME"] = str(home)
|
||||
env["USERPROFILE"] = str(home)
|
||||
env["PYTHONIOENCODING"] = "utf-8"
|
||||
env.pop("OPENCODE_DATA_DIR", None)
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(ROOT_SCRIPT), project],
|
||||
capture_output=True, text=True, env=env, timeout=60,
|
||||
)
|
||||
return proc.stdout + proc.stderr
|
||||
|
||||
def test_victim_never_prints_the_other_projects_conversation(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
store = home / ".claude" / "projects" / "-home-dev-client-acme"
|
||||
store.mkdir(parents=True)
|
||||
# Both projects fold to this one directory. Only the donor has
|
||||
# transcripts, and they carry the secret.
|
||||
write_session(store, "a.jsonl", DONOR, CANARY)
|
||||
write_session(store, "b.jsonl", DONOR, CANARY + "_SECOND")
|
||||
|
||||
output = self._run(home, VICTIM)
|
||||
self.assertNotIn(
|
||||
CANARY, output,
|
||||
"catchup disclosed another project's conversation",
|
||||
)
|
||||
|
||||
def test_own_history_is_still_recovered_from_a_shared_store(self):
|
||||
"""The guard must not cost the project its own transcripts.
|
||||
|
||||
Rejecting the whole directory would be the easy fix and the wrong one:
|
||||
in a collision both projects live there permanently, so the victim
|
||||
would lose its own history for good.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
store = home / ".claude" / "projects" / "-home-dev-client-acme"
|
||||
store.mkdir(parents=True)
|
||||
write_session(store, "a.jsonl", DONOR, CANARY)
|
||||
time.sleep(0.05)
|
||||
write_session(store, "b.jsonl", VICTIM, "MY_OWN_PLANNING_NOTE")
|
||||
time.sleep(0.05)
|
||||
write_session(store, "c.jsonl", VICTIM, "MY_LATEST_TURN")
|
||||
|
||||
output = self._run(home, VICTIM)
|
||||
self.assertNotIn(CANARY, output)
|
||||
self.assertIn(
|
||||
"MY_OWN_PLANNING_NOTE", output,
|
||||
"the guard dropped this project's own transcript",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,196 @@
|
||||
"""One store-resolution vector table, run against EVERY shipped session-catchup.py.
|
||||
|
||||
Issue #209 existed because the copies drifted: v3.8.0 replaced the sanitizer in
|
||||
the canonical script (and everything synced from it) with a character whitelist,
|
||||
but three unsynced copies kept a manual `.replace()` chain that never folded
|
||||
'.'. The suite stayed green because each existing test pointed at exactly one
|
||||
copy, so nothing compared them.
|
||||
|
||||
This module discovers the copies instead of listing them, and runs the same
|
||||
vectors through each, so a future copy or a future divergence fails here.
|
||||
|
||||
The surface under test is sanitize plus probe, not path normalization, so the
|
||||
per-module normalize step is patched to identity exactly as
|
||||
test_catchup_project_dir.py does. That keeps POSIX vectors meaningful on
|
||||
Windows, where Path.resolve() would otherwise rewrite '/home/...' to 'C:\\home\\...'.
|
||||
|
||||
Folding rules pinned here were measured against 24 real ~/.claude/projects
|
||||
stores whose recorded `cwd` could be read: Claude Code folds every character
|
||||
outside [A-Za-z0-9-] to '-', counting UTF-16 code units, so a non-BMP character
|
||||
costs two dashes. Older stores kept '_'; both spellings are live, so both are
|
||||
probed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
# .kiro ships a different program: it reads .kiro/plan/*.md off the filesystem
|
||||
# and never touches ~/.claude/projects, so it has no resolver to compare.
|
||||
EXCLUDED_PARTS = {".kiro"}
|
||||
|
||||
RESOLVER_NAMES = (
|
||||
"get_claude_project_dir", # canonical (and every copy synced from it)
|
||||
"get_project_dir_claude", # root scripts/ and .hermes
|
||||
"get_project_dir", # .mastracode (returns a Tuple)
|
||||
)
|
||||
|
||||
NORMALIZE_NAMES = ("normalize_path", "normalize_project_path")
|
||||
|
||||
|
||||
def tracked_catchup_scripts() -> list[Path]:
|
||||
"""Every session-catchup.py tracked by git, minus the .kiro variant."""
|
||||
out = subprocess.run(
|
||||
["git", "ls-files", "*session-catchup.py"],
|
||||
cwd=REPO_ROOT, capture_output=True, text=True, check=True,
|
||||
).stdout.split()
|
||||
paths = []
|
||||
for rel in out:
|
||||
path = REPO_ROOT / rel
|
||||
if EXCLUDED_PARTS & set(Path(rel).parts):
|
||||
continue
|
||||
if path.is_file():
|
||||
paths.append(path)
|
||||
return sorted(paths)
|
||||
|
||||
|
||||
def load_module(script_path: Path, alias: str):
|
||||
spec = importlib.util.spec_from_file_location(alias, script_path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def resolver_for(module):
|
||||
"""Return (callable, name) for whichever resolver this copy exposes."""
|
||||
for name in RESOLVER_NAMES:
|
||||
fn = getattr(module, name, None)
|
||||
if callable(fn):
|
||||
return fn, name
|
||||
return None, None
|
||||
|
||||
|
||||
def resolve_name(fn, resolver_name: str, project_path: str) -> str:
|
||||
result = fn(project_path)
|
||||
if resolver_name == "get_project_dir":
|
||||
# .mastracode returns (path, skip_message)
|
||||
result = result[0]
|
||||
assert result is not None, f"{resolver_name} returned None for {project_path}"
|
||||
return Path(result).name
|
||||
|
||||
|
||||
# (label, project path, the directory name Claude Code actually writes)
|
||||
VECTORS = [
|
||||
("hidden dir (#209)", "/home/dev/.dotfiles", "-home-dev--dotfiles"),
|
||||
("nested hidden dir", "/home/dev/.config/nvim", "-home-dev--config-nvim"),
|
||||
("dots inside a segment", "/home/dev/my.app.v2", "-home-dev-my-app-v2"),
|
||||
("space in a segment", "/home/dev/My Project", "-home-dev-My-Project"),
|
||||
("plain path (regression)", "/home/dev/project", "-home-dev-project"),
|
||||
("underscore kept (old)", "/home/dev/Ayseu_Visa_2026", "-home-dev-Ayseu_Visa_2026"),
|
||||
("underscore folded (new)", "/home/dev/MORPHOS_SEND", "-home-dev-MORPHOS-SEND"),
|
||||
# A non-BMP character occupies two UTF-16 code units, so it folds to two
|
||||
# dashes; the trailing '_' folds too in current versions. Measured against
|
||||
# the real store C--Users-...-Teaching-Material----Daily-Sessions.
|
||||
("emoji (UTF-16 width)", "/home/dev/\U0001F4C5_Daily", "-home-dev----Daily"),
|
||||
]
|
||||
|
||||
|
||||
class StoreResolutionParityTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.scripts = tracked_catchup_scripts()
|
||||
|
||||
def test_every_copy_exposes_a_resolver(self):
|
||||
"""A new copy that resolves stores must be discoverable by this suite."""
|
||||
self.assertTrue(self.scripts, "no session-catchup.py copies found")
|
||||
for script in self.scripts:
|
||||
with self.subTest(script=script.relative_to(REPO_ROOT).as_posix()):
|
||||
module = load_module(script, f"pc_{abs(hash(str(script)))}")
|
||||
_, name = resolver_for(module)
|
||||
self.assertIsNotNone(
|
||||
name,
|
||||
f"{script.relative_to(REPO_ROOT)} reads ~/.claude/projects but "
|
||||
"exposes no known resolver; add it to RESOLVER_NAMES",
|
||||
)
|
||||
|
||||
def test_vectors_resolve_identically_in_every_copy(self):
|
||||
for script in self.scripts:
|
||||
rel = script.relative_to(REPO_ROOT).as_posix()
|
||||
module = load_module(script, f"pv_{abs(hash(str(script)))}")
|
||||
fn, resolver_name = resolver_for(module)
|
||||
if fn is None:
|
||||
continue
|
||||
|
||||
for label, project_path, expected in VECTORS:
|
||||
with self.subTest(copy=rel, vector=label):
|
||||
self._assert_vector(module, fn, resolver_name, project_path, expected, rel, label)
|
||||
|
||||
def _assert_vector(self, module, fn, resolver_name, project_path, expected, rel, label):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
projects = home / ".claude" / "projects"
|
||||
projects.mkdir(parents=True)
|
||||
(projects / expected).mkdir()
|
||||
|
||||
patches = [mock.patch.object(module.Path, "home", return_value=home)]
|
||||
for norm in NORMALIZE_NAMES:
|
||||
if hasattr(module, norm):
|
||||
patches.append(
|
||||
mock.patch.object(module, norm, side_effect=lambda p: p)
|
||||
)
|
||||
for patch in patches:
|
||||
patch.start()
|
||||
try:
|
||||
got = resolve_name(fn, resolver_name, project_path)
|
||||
finally:
|
||||
for patch in reversed(patches):
|
||||
patch.stop()
|
||||
|
||||
self.assertEqual(
|
||||
expected, got,
|
||||
f"{rel} [{label}] resolved {project_path!r} to {got!r}, "
|
||||
f"but Claude Code writes {expected!r}",
|
||||
)
|
||||
|
||||
def test_missing_store_does_not_resolve_to_the_projects_root(self):
|
||||
"""A missing store must never make the store root itself the answer."""
|
||||
for script in self.scripts:
|
||||
rel = script.relative_to(REPO_ROOT).as_posix()
|
||||
module = load_module(script, f"pe_{abs(hash(str(script)))}")
|
||||
fn, resolver_name = resolver_for(module)
|
||||
if fn is None:
|
||||
continue
|
||||
with self.subTest(copy=rel):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
projects = home / ".claude" / "projects"
|
||||
projects.mkdir(parents=True)
|
||||
patches = [mock.patch.object(module.Path, "home", return_value=home)]
|
||||
for norm in NORMALIZE_NAMES:
|
||||
if hasattr(module, norm):
|
||||
patches.append(
|
||||
mock.patch.object(module, norm, side_effect=lambda p: p)
|
||||
)
|
||||
for patch in patches:
|
||||
patch.start()
|
||||
try:
|
||||
result = fn("/home/dev/absent")
|
||||
if resolver_name == "get_project_dir":
|
||||
result = result[0]
|
||||
finally:
|
||||
for patch in reversed(patches):
|
||||
patch.stop()
|
||||
self.assertNotEqual(
|
||||
projects.resolve(), Path(result).resolve(),
|
||||
f"{rel} resolved a missing project to the store root",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user