mini-trellis 0.3.7 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +77 -202
  2. package/dist/cli/index.js +12 -6
  3. package/dist/cli/index.js.map +1 -1
  4. package/dist/commands/doctor.d.ts.map +1 -1
  5. package/dist/commands/doctor.js +22 -1
  6. package/dist/commands/doctor.js.map +1 -1
  7. package/dist/commands/init.d.ts +2 -0
  8. package/dist/commands/init.d.ts.map +1 -1
  9. package/dist/commands/init.js +5 -3
  10. package/dist/commands/init.js.map +1 -1
  11. package/dist/commands/migrate.d.ts.map +1 -1
  12. package/dist/commands/migrate.js +15 -1
  13. package/dist/commands/migrate.js.map +1 -1
  14. package/dist/commands/refresh.d.ts +11 -14
  15. package/dist/commands/refresh.d.ts.map +1 -1
  16. package/dist/commands/refresh.js +78 -9
  17. package/dist/commands/refresh.js.map +1 -1
  18. package/dist/commands/uninstall.js +1 -1
  19. package/dist/commands/uninstall.js.map +1 -1
  20. package/dist/commands/upgrade.d.ts +4 -1
  21. package/dist/commands/upgrade.d.ts.map +1 -1
  22. package/dist/commands/upgrade.js +51 -0
  23. package/dist/commands/upgrade.js.map +1 -1
  24. package/dist/configurators/index.d.ts.map +1 -1
  25. package/dist/configurators/index.js +25 -1
  26. package/dist/configurators/index.js.map +1 -1
  27. package/dist/configurators/kiro.d.ts +3 -0
  28. package/dist/configurators/kiro.d.ts.map +1 -0
  29. package/dist/configurators/kiro.js +24 -0
  30. package/dist/configurators/kiro.js.map +1 -0
  31. package/dist/configurators/pi.d.ts +1 -0
  32. package/dist/configurators/pi.d.ts.map +1 -1
  33. package/dist/configurators/pi.js +17 -7
  34. package/dist/configurators/pi.js.map +1 -1
  35. package/dist/configurators/shared.d.ts.map +1 -1
  36. package/dist/configurators/shared.js +2 -0
  37. package/dist/configurators/shared.js.map +1 -1
  38. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/SKILL.md +1 -1
  39. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/references/organize-history.md +2 -2
  40. package/dist/templates/common/commands/remember.md +16 -4
  41. package/dist/templates/common/skills/update-spec.md +8 -4
  42. package/dist/templates/markdown/agents.md +7 -5
  43. package/dist/templates/markdown/spec/guides/mini-memory.md.txt +7 -3
  44. package/dist/templates/shared-hooks/index.d.ts +1 -1
  45. package/dist/templates/shared-hooks/index.d.ts.map +1 -1
  46. package/dist/templates/shared-hooks/index.js +1 -0
  47. package/dist/templates/shared-hooks/index.js.map +1 -1
  48. package/dist/templates/shared-hooks/session-start.py +33 -6
  49. package/dist/templates/trellis/gitattributes.txt +5 -6
  50. package/dist/templates/trellis/scripts/add_session.py +241 -175
  51. package/dist/templates/trellis/scripts/common/paths.py +12 -5
  52. package/dist/templates/trellis/scripts/common/recording_lock.py +71 -0
  53. package/dist/types/ai-tools.d.ts +2 -2
  54. package/dist/types/ai-tools.d.ts.map +1 -1
  55. package/dist/types/ai-tools.js +32 -0
  56. package/dist/types/ai-tools.js.map +1 -1
  57. package/dist/utils/kiro-hooks.d.ts +4 -0
  58. package/dist/utils/kiro-hooks.d.ts.map +1 -0
  59. package/dist/utils/kiro-hooks.js +47 -0
  60. package/dist/utils/kiro-hooks.js.map +1 -0
  61. package/dist/utils/managed-removal.d.ts.map +1 -1
  62. package/dist/utils/managed-removal.js +6 -0
  63. package/dist/utils/managed-removal.js.map +1 -1
  64. package/package.json +2 -2
@@ -25,7 +25,7 @@ Commit evidence:
25
25
  resolved to its real subject from the local object database BEFORE
26
26
  anything is written. An OID that cannot be resolved fails the command
27
27
  before the journal or index is touched — no placeholder prose is ever
28
- recorded. Pass "-" (the default) for a planning session with no commits.
28
+ recorded. Pass "-" (the default) when there are no associated commits.
29
29
 
30
30
  Retry convergence:
31
31
  The journal append, the index row and the optional auto-commit are one
@@ -67,6 +67,7 @@ from common.paths import (
67
67
  from common.developer import ensure_developer
68
68
  from common.git import branch_exists_locally, run_git
69
69
  from common.io import write_text_atomic
70
+ from common.recording_lock import recording_lock
70
71
  from common.log import Colors, colored
71
72
  from common.safe_commit import (
72
73
  print_gitignore_warning,
@@ -98,6 +99,7 @@ MARKER_PREFIX = "<!-- trellis-session:"
98
99
  # Bumped when the fingerprint inputs change. Untagged markers are v1, whose
99
100
  # fingerprint mixed in the calendar date; see compute_record_fingerprint.
100
101
  MARKER_VERSION = 2
102
+ TOPIC_MARKER_VERSION = 3
101
103
  LEGACY_MARKER_RE = re.compile(r"^<!-- trellis-session: fp=([0-9a-f]{16}) -->$")
102
104
  ENTRY_DATE_RE = re.compile(r"^\*\*Date\*\*: (\d{4}-\d{2}-\d{2})\s*$")
103
105
  SESSION_HEADING_RE = re.compile(r"^## Session (\d+):", re.MULTILINE)
@@ -274,22 +276,15 @@ def is_git_worktree(repo_root: Path) -> bool:
274
276
 
275
277
 
276
278
  def warn_if_parallel_worktree(repo_root: Path) -> None:
277
- """Non-blocking note: index.md conflicts across parallel worktrees/branches
278
- are expected and safe. Only fires when running in a linked git worktree
279
- (not the main tree) with `session_auto_commit` enabled (#415 quick-fix tier).
280
- """
281
- if not get_session_auto_commit(repo_root):
282
- return
279
+ """A checkout lock cannot coordinate uncommitted writes in other worktrees."""
283
280
  if not is_git_worktree(repo_root):
284
281
  return
285
282
  print(
286
283
  colored(
287
- "[NOTE] Running in a git worktree with session_auto_commit enabled: "
288
- "journal-*.md files auto-merge via .gitattributes, but index.md "
289
- "conflicts across parallel worktrees/branches are expected and safe "
290
- "to resolve by picking either side (task state lives in task.json, "
291
- "not index.md). See .trellis/spec/cli/backend/directory-structure.md "
292
- '("Workspace Journal Merge Behavior").',
284
+ "[NOTE] Parallel worktrees may assign the same session number "
285
+ "before either record is committed. After merging, check complete "
286
+ "journal entries and both index rows; union merge and picking one "
287
+ "index side do not guarantee complete records.",
293
288
  Colors.YELLOW,
294
289
  ),
295
290
  file=sys.stderr,
@@ -514,9 +509,9 @@ def compute_legacy_fingerprint(payload: dict, date: str) -> str:
514
509
  return _hash_payload({**payload, "date": date})
515
510
 
516
511
 
517
- def render_marker(fingerprint: str) -> str:
512
+ def render_marker(fingerprint: str, version: int = MARKER_VERSION) -> str:
518
513
  """Machine-readable record marker; renders as nothing in Markdown."""
519
- return f"{MARKER_PREFIX} v={MARKER_VERSION} fp={fingerprint} -->"
514
+ return f"{MARKER_PREFIX} v={version} fp={fingerprint} -->"
520
515
 
521
516
 
522
517
  def _append_topic_links(
@@ -681,9 +676,9 @@ def resolve_next_session(repo_root: Path, dev_dir: Path, index_file: Path) -> in
681
676
  Deriving the number from the working tree alone lets two branches that
682
677
  each record before merging claim the same number (observed twice on
683
678
  2026-08-06). Taking the union with every recorded ref — the default
684
- branch, and the other local heads a parallel worktree records on — makes
685
- the number monotonic across concurrent branches; `journal-*.md`
686
- merge=union then keeps both entries when the branches meet.
679
+ branch, and the other local heads a parallel worktree records on — avoids
680
+ reuse of committed numbers. Other worktrees' uncommitted records are not
681
+ visible here; union merge does not resolve duplicate numbers or semantics.
687
682
  """
688
683
  highest = max_local_session(dev_dir, index_file)
689
684
 
@@ -714,10 +709,7 @@ def find_marker_entries(dev_dir: Path, marker: str) -> list[tuple[Path, int | No
714
709
  for f in sorted(dev_dir.glob(f"{FILE_JOURNAL_PREFIX}*.md")):
715
710
  if not f.is_file():
716
711
  continue
717
- try:
718
- lines = f.read_text(encoding="utf-8").splitlines()
719
- except OSError:
720
- continue
712
+ lines = f.read_text(encoding="utf-8").splitlines()
721
713
  for i, line in enumerate(lines):
722
714
  if line.strip() != marker:
723
715
  continue
@@ -747,27 +739,62 @@ def content_at_head(repo_root: Path, path: Path) -> str | None:
747
739
  return out if rc == 0 else None
748
740
 
749
741
 
750
- def index_has_session_row(index_file: Path, session_num: int) -> bool:
751
- """Whether the session-history block already holds this session's row."""
752
- if not index_file.is_file():
753
- return False
754
- try:
755
- lines = index_file.read_text(encoding="utf-8").splitlines()
756
- except OSError:
757
- return False
742
+ def index_blocks(content: str) -> dict[str, tuple[int, int]]:
743
+ """Validate every managed block before replacing any index content."""
744
+ lines = content.splitlines()
745
+ blocks: dict[str, tuple[int, int]] = {}
746
+ previous_end = -1
747
+ for name in ("current-status", "active-documents", "session-history"):
748
+ starts = [i for i, line in enumerate(lines) if line.strip() == f"<!-- @@@auto:{name} -->"]
749
+ ends = [i for i, line in enumerate(lines) if line.strip() == f"<!-- @@@/auto:{name} -->"]
750
+ if len(starts) != 1 or len(ends) != 1 or not previous_end < starts[0] < ends[0]:
751
+ raise ValueError(f"Markers not found in index.md or malformed: {name} must have one ordered, non-nested pair")
752
+ blocks[name] = (starts[0], ends[0])
753
+ previous_end = ends[0]
754
+ start, end = blocks["session-history"]
755
+ history = lines[start + 1:end]
756
+ headers = [i for i, line in enumerate(history) if re.match(r"^\|\s*#\s*\|", line)]
757
+ separators = [i for i, line in enumerate(history) if re.match(r"^\|[-| ]+\|\s*$", line)]
758
+ if len(headers) != 1 or len(separators) != 1 or headers[0] + 1 != separators[0]:
759
+ raise ValueError("index.md session-history needs one table header and separator")
760
+ numbers = [int(m.group(1)) for line in history if (m := re.match(r"^\|\s*(\d+)\s*\|", line))]
761
+ if len(numbers) != len(set(numbers)):
762
+ raise ValueError("index.md has conflicting duplicate session-history rows")
763
+ return blocks
764
+
765
+
766
+ def session_index_row(
767
+ session_num: int, today: str, title: str,
768
+ evidence: list[tuple[str, str]], branch: str | None,
769
+ ) -> str:
770
+ return f"| {session_num} | {today} | {escape_markdown_cell(title)} | {format_commit_display(evidence)} | `{escape_markdown_cell(branch or '-')}` |"
758
771
 
759
- row_re = re.compile(r"^\|\s*%d\s*\|" % session_num)
760
- in_history = False
761
- for line in lines:
762
- if "@@@auto:session-history" in line:
763
- in_history = True
764
- continue
765
- if "@@@/auto:session-history" in line:
766
- in_history = False
767
- continue
768
- if in_history and row_re.match(line):
769
- return True
770
- return False
772
+
773
+ def _row_cells(row: str) -> list[str]:
774
+ return [cell.strip() for cell in re.split(r"(?<!\\)\|", row.strip())[1:-1]]
775
+
776
+
777
+ def index_has_session_row(index_file: Path, session_num: int, expected_row: str) -> bool:
778
+ """Verify this exact record, not just a row with the same number."""
779
+ content = index_file.read_text(encoding="utf-8")
780
+ start, end = index_blocks(content)["session-history"]
781
+ rows = [line for line in content.splitlines()[start + 1:end]
782
+ if re.match(r"^\|\s*%d\s*\|" % session_num, line)]
783
+ if rows and _row_cells(rows[0]) != _row_cells(expected_row):
784
+ raise ValueError(f"index.md session {session_num} conflicts with a different record; repair that row before retrying")
785
+ status_start, status_end = index_blocks(content)["current-status"]
786
+ status = "\n".join(content.splitlines()[status_start + 1:status_end])
787
+ totals = re.findall(r"^- \*\*Total Sessions\*\*: (\d+)\s*$", status, re.MULTILINE)
788
+ return len(rows) == 1 and len(totals) == 1 and int(totals[0]) >= session_num
789
+
790
+
791
+ def record_date(journal_file: Path, marker: str) -> str:
792
+ lines = journal_file.read_text(encoding="utf-8").splitlines()
793
+ position = next(i for i, line in enumerate(lines) if line.strip() == marker)
794
+ date = _entry_date_at(lines, position)
795
+ if date is None:
796
+ raise ValueError(f"{journal_file.name}: record has no date; repair it before retrying")
797
+ return date
771
798
 
772
799
 
773
800
  def _entry_date_at(lines: list[str], marker_index: int) -> str | None:
@@ -844,6 +871,10 @@ def classify_record(
844
871
  dev_dir: Path,
845
872
  index_file: Path,
846
873
  marker: str,
874
+ title: str,
875
+ evidence: list[tuple[str, str]],
876
+ branch: str | None,
877
+ expected_summary: str,
847
878
  ) -> tuple[str, Path | None, int | None, str | None]:
848
879
  """Classify the current state of this exact record.
849
880
 
@@ -872,21 +903,36 @@ def classify_record(
872
903
  "repair it by hand before retrying."
873
904
  )
874
905
 
906
+ content = journal_file.read_text(encoding="utf-8")
907
+ marker_position = content.index(marker)
908
+ headings = list(SESSION_HEADING_RE.finditer(content))
909
+ start = next(heading.start() for heading in reversed(headings) if heading.start() < marker_position)
910
+ end = next((heading.start() for heading in headings if heading.start() > marker_position), len(content))
911
+ entry = content[start:end]
912
+ heading = entry.splitlines()[0].split(":", 1)[1]
913
+ if (_normalize_text(heading) != _normalize_text(title)
914
+ or _normalize_text(expected_summary) not in _normalize_text(entry)):
915
+ return "", None, None, (
916
+ f"{journal_file.name}: journal title, summary or topic links no longer "
917
+ "match this record's inputs. Inspect the changed entry before retrying."
918
+ )
919
+
875
920
  head_content = content_at_head(repo_root, journal_file)
876
921
  if head_content is not None and marker in head_content:
877
922
  return STATE_COMMITTED, journal_file, session_num, None
878
923
 
879
- if index_has_session_row(index_file, session_num):
924
+ expected_row = session_index_row(session_num, record_date(journal_file, marker), title, evidence, branch)
925
+ try:
926
+ indexed = index_has_session_row(index_file, session_num, expected_row)
927
+ except ValueError as exc:
928
+ if "different record" in str(exc):
929
+ return "", None, None, str(exc)
930
+ indexed = False
931
+ except OSError:
932
+ indexed = False
933
+ if indexed:
880
934
  return STATE_INDEX_RECORDED, journal_file, session_num, None
881
935
 
882
- recorded_total = get_current_session(index_file)
883
- if recorded_total > session_num:
884
- return "", None, None, (
885
- f"journal entry for session {session_num} has no index row, but "
886
- f"index.md already counts {recorded_total} sessions. Repairing the "
887
- "row would rewrite a later record — resolve index.md by hand."
888
- )
889
-
890
936
  return STATE_JOURNAL_RECORDED, journal_file, session_num, None
891
937
 
892
938
 
@@ -936,13 +982,13 @@ def generate_session_content(
936
982
  for oid, subject in evidence:
937
983
  commit_table += f"\n| `{oid}` | {escape_markdown_cell(subject)} |"
938
984
  else:
939
- commit_table = "(No commits - planning session)"
985
+ commit_table = "(No associated commits)"
940
986
 
941
987
  package_line = f"\n**Package**: {package}" if package else ""
942
988
  branch_line = f"\n**Branch**: `{branch}`" if branch else ""
943
989
 
944
990
  main_changes_section = _render_main_changes(changes or [], extra_content)
945
- testing_section = _render_bullet_section("Testing", tests or [], bullet_prefix="- [OK] ")
991
+ testing_section = _render_bullet_section("Testing", tests or [])
946
992
  next_steps_section = _render_bullet_section("Next Steps", next_steps or [])
947
993
 
948
994
  return f"""
@@ -959,11 +1005,7 @@ def generate_session_content(
959
1005
 
960
1006
  ### Git Commits
961
1007
 
962
- {commit_table}{testing_section}
963
-
964
- ### Status
965
-
966
- [OK] **Completed**{next_steps_section}
1008
+ {commit_table}{testing_section}{next_steps_section}
967
1009
  """
968
1010
 
969
1011
 
@@ -985,106 +1027,53 @@ def update_index(
985
1027
  branch: str | None = None,
986
1028
  ) -> bool:
987
1029
  """Update index.md with new session info."""
988
- commit_display = format_commit_display(evidence)
989
-
990
- # Get file number from active_file name
991
- match = re.search(r"(\d+)", active_file)
992
- active_num = int(match.group(1)) if match else 0
993
- files_table = count_journal_files(dev_dir, active_num)
994
-
995
- print(f"Updating index.md for session {new_session}...")
996
- print(f" Title: {title}")
997
- print(f" Commit: {commit_display}")
998
- print(f" Active File: {active_file}")
999
- print()
1000
-
1001
- content = index_file.read_text(encoding="utf-8")
1002
-
1003
- if "@@@auto:current-status" not in content:
1004
- print("Error: Markers not found in index.md. Please ensure markers exist.", file=sys.stderr)
1005
- return False
1006
-
1007
- # Process sections
1008
- lines = content.splitlines()
1009
- new_lines = []
1010
-
1011
- in_current_status = False
1012
- in_active_documents = False
1013
- in_session_history = False
1014
- header_written = False
1015
-
1016
- for line in lines:
1017
- if "@@@auto:current-status" in line:
1018
- new_lines.append(line)
1019
- in_current_status = True
1020
- new_lines.append(f"- **Active File**: `{active_file}`")
1021
- new_lines.append(f"- **Total Sessions**: {new_session}")
1022
- new_lines.append(f"- **Last Active**: {today}")
1023
- continue
1024
-
1025
- if "@@@/auto:current-status" in line:
1026
- in_current_status = False
1027
- new_lines.append(line)
1028
- continue
1029
-
1030
- if "@@@auto:active-documents" in line:
1031
- new_lines.append(line)
1032
- in_active_documents = True
1033
- new_lines.append("| File | Lines | Status |")
1034
- new_lines.append("|------|-------|--------|")
1035
- new_lines.append(files_table)
1036
- continue
1037
-
1038
- if "@@@/auto:active-documents" in line:
1039
- in_active_documents = False
1040
- new_lines.append(line)
1041
- continue
1042
-
1043
- if "@@@auto:session-history" in line:
1044
- new_lines.append(line)
1045
- in_session_history = True
1046
- header_written = False
1047
- continue
1048
-
1049
- if "@@@/auto:session-history" in line:
1050
- in_session_history = False
1051
- new_lines.append(line)
1052
- continue
1053
-
1054
- if in_current_status:
1055
- continue
1056
-
1057
- if in_active_documents:
1058
- continue
1059
-
1060
- if in_session_history:
1061
- # Migrate old 4/6-column headers to 5-column Branch-only history.
1062
- if re.match(
1063
- r"^\|\s*#\s*\|\s*Date\s*\|\s*Title\s*\|\s*Commits\s*\|\s*Branch\s*\|\s*Base Branch\s*\|\s*$",
1064
- line,
1065
- ):
1066
- new_lines.append("| # | Date | Title | Commits | Branch |")
1067
- continue
1068
- if re.match(r"^\|\s*#\s*\|\s*Date\s*\|\s*Title\s*\|\s*Commits\s*\|\s*Branch\s*\|\s*$", line):
1069
- new_lines.append("| # | Date | Title | Commits | Branch |")
1070
- continue
1071
- if re.match(r"^\|\s*#\s*\|\s*Date\s*\|\s*Title\s*\|\s*Commits\s*\|\s*$", line):
1072
- new_lines.append("| # | Date | Title | Commits | Branch |")
1073
- continue
1074
- if re.match(r"^\|[-| ]+\|\s*$", line) and not header_written:
1075
- new_lines.append("|---|------|-------|---------|--------|")
1076
- new_lines.append(f"| {new_session} | {today} | {title} | {commit_display} | `{branch or '-'}` |")
1077
- header_written = True
1078
- continue
1079
- new_lines.append(line)
1080
- continue
1081
-
1082
- new_lines.append(line)
1083
-
1084
- if not write_text_atomic(index_file, "\n".join(new_lines)):
1085
- print(f"Error: failed to write {index_file}", file=sys.stderr)
1030
+ try:
1031
+ content = index_file.read_text(encoding="utf-8")
1032
+ blocks = index_blocks(content)
1033
+ expected_row = session_index_row(new_session, today, title, evidence, branch)
1034
+ index_has_session_row(index_file, new_session, expected_row)
1035
+ latest_file, latest_num, _ = get_latest_journal_info(dev_dir)
1036
+ active_file = latest_file.name if latest_file else active_file
1037
+ total = max(get_current_session(index_file), max_local_session(dev_dir, index_file))
1038
+ lines = content.splitlines()
1039
+ replacements: dict[str, list[str]] = {
1040
+ "current-status": [
1041
+ f"- **Active File**: `{active_file}`",
1042
+ f"- **Total Sessions**: {total}",
1043
+ f"- **Last Active**: {max(today, datetime.now().strftime('%Y-%m-%d'))}",
1044
+ ],
1045
+ "active-documents": [
1046
+ "| File | Lines | Status |", "|------|-------|--------|",
1047
+ count_journal_files(dev_dir, latest_num),
1048
+ ],
1049
+ }
1050
+ start, end = blocks["session-history"]
1051
+ history = lines[start + 1:end]
1052
+ if not any(_row_cells(line) == _row_cells(expected_row) for line in history):
1053
+ separator = next(i for i, line in enumerate(history) if re.match(r"^\|[-| ]+\|\s*$", line))
1054
+ # Keep historical rows and user text. Only the managed header is
1055
+ # upgraded, as in the previous four/six-column compatibility path.
1056
+ history[separator - 1] = "| # | Date | Title | Commits | Branch |"
1057
+ history[separator] = "|---|------|-------|---------|--------|"
1058
+ record_rows = [(i, int(m.group(1))) for i, line in enumerate(history)
1059
+ if (m := re.match(r"^\|\s*(\d+)\s*\|", line))]
1060
+ position = next((i for i, number in record_rows if number < new_session),
1061
+ record_rows[-1][0] + 1 if record_rows else separator + 1)
1062
+ history.insert(position, expected_row)
1063
+ replacements["session-history"] = history
1064
+ for name, (start, end) in sorted(blocks.items(), key=lambda item: item[1][0], reverse=True):
1065
+ lines[start + 1:end] = replacements[name]
1066
+ updated = "\n".join(lines) + ("\n" if content.endswith("\n") else "")
1067
+ # Validate the proposed structure before replacing the user's index.
1068
+ index_blocks(updated)
1069
+ if not write_text_atomic(index_file, updated):
1070
+ raise OSError(f"failed to write {index_file}")
1071
+ if not index_has_session_row(index_file, new_session, expected_row):
1072
+ raise ValueError("index.md post-write verification did not find this record")
1073
+ except (OSError, ValueError) as exc:
1074
+ print(f"Error: {exc}", file=sys.stderr)
1086
1075
  return False
1087
- print("[OK] Updated index.md successfully!")
1076
+ print("[OK] Updated and verified index.md.")
1088
1077
  return True
1089
1078
 
1090
1079
 
@@ -1225,6 +1214,34 @@ def add_session(
1225
1214
  topic_paths: list[str] | None = None,
1226
1215
  ) -> int:
1227
1216
  """Add a new session, resuming an interrupted one instead of duplicating it."""
1217
+ try:
1218
+ with recording_lock(get_repo_root()):
1219
+ return _add_session(
1220
+ title, commit, summary, changes, extra_content, tests, next_steps,
1221
+ auto_commit, package, branch, commit_subjects, idempotency_key,
1222
+ topic_paths,
1223
+ )
1224
+ except (OSError, ValueError) as exc:
1225
+ print(f"Error: session recording failed: {exc}. Retry the identical command; existing records are preserved.", file=sys.stderr)
1226
+ return 1
1227
+
1228
+
1229
+ def _add_session(
1230
+ title: str,
1231
+ commit: str,
1232
+ summary: str,
1233
+ changes: list[str] | None,
1234
+ extra_content: str | None,
1235
+ tests: list[str] | None,
1236
+ next_steps: list[str] | None,
1237
+ auto_commit: bool,
1238
+ package: str | None,
1239
+ branch: str | None,
1240
+ commit_subjects: list[str] | None,
1241
+ idempotency_key: str | None,
1242
+ topic_paths: list[str] | None,
1243
+ ) -> int:
1244
+ """Recording state machine; the caller holds the checkout lock."""
1228
1245
  repo_root = get_repo_root()
1229
1246
  warn_if_parallel_worktree(repo_root)
1230
1247
  ensure_developer(repo_root)
@@ -1269,36 +1286,71 @@ def add_session(
1269
1286
  index_file = dev_dir / "index.md"
1270
1287
  today = datetime.now().strftime("%Y-%m-%d")
1271
1288
 
1289
+ if not dev_dir.resolve().is_relative_to(repo_root.resolve()):
1290
+ print("Error: workspace escapes the project; no session was written.", file=sys.stderr)
1291
+ return 1
1292
+ for state_file in [index_file, *dev_dir.glob(f"{FILE_JOURNAL_PREFIX}*.md")]:
1293
+ if state_file.is_symlink():
1294
+ print(f"Error: recording state must be a regular project file, not a symlink: {state_file.name}; no session was written.", file=sys.stderr)
1295
+ return 1
1296
+
1272
1297
  record_summary = _append_topic_links(summary, topic_paths)
1298
+ rendered_summary = _append_topic_links(summary, topic_paths, dev_dir, repo_root)
1273
1299
  payload = _fingerprint_payload(
1274
1300
  developer, title, record_summary, package, branch, evidence,
1275
1301
  changes, extra_content, tests, next_steps, idempotency_key,
1276
1302
  )
1277
- marker = render_marker(compute_record_fingerprint(payload))
1303
+ # A changed topic is a new input even when the caller reuses its short
1304
+ # title/summary. Do not collapse a correction into an uncommitted note.
1305
+ if topic_paths:
1306
+ payload["topic_versions"] = [
1307
+ [topic, hashlib.sha256((repo_root / topic).read_bytes()).hexdigest()]
1308
+ for topic in topic_paths
1309
+ ]
1310
+ marker_version = TOPIC_MARKER_VERSION if topic_paths else MARKER_VERSION
1311
+ marker = render_marker(compute_record_fingerprint(payload), marker_version)
1312
+
1313
+ # Legacy records did not capture topic versions. Keep their existing
1314
+ # retry identity; only new v3 records can distinguish changed content.
1315
+ legacy_payload = {key: value for key, value in payload.items() if key != "topic_versions"}
1316
+ old_marker = render_marker(compute_record_fingerprint(legacy_payload))
1317
+ if topic_paths and not find_marker_entries(dev_dir, marker) and find_marker_entries(dev_dir, old_marker):
1318
+ print("[WARN] Resuming a legacy topic-linked record without a saved topic version. Verify the topic separately; for a new correction use changed summary text or a new --idempotency-key.", file=sys.stderr)
1319
+ marker = old_marker
1278
1320
 
1279
1321
  # `today` is no longer a fingerprint input; a record has to be findable by
1280
1322
  # its own retry after a date rollover. It still dates the rendered entry.
1281
- marker, resolve_error = resolve_effective_marker(dev_dir, payload, marker)
1323
+ marker, resolve_error = resolve_effective_marker(dev_dir, legacy_payload, marker)
1282
1324
  if resolve_error:
1283
1325
  print(f"Error: {resolve_error}", file=sys.stderr)
1284
1326
  return 1
1285
1327
 
1286
1328
  state, matched_file, matched_num, classify_error = classify_record(
1287
- repo_root, dev_dir, index_file, marker
1329
+ repo_root, dev_dir, index_file, marker, title, evidence, branch, rendered_summary
1288
1330
  )
1289
1331
  if classify_error:
1290
1332
  print(f"Error: {classify_error}", file=sys.stderr)
1291
1333
  return 1
1292
1334
 
1293
- if state == STATE_COMMITTED and idempotency_key:
1294
- print(
1295
- f"[OK] Session {matched_num} with idempotency key "
1296
- f"'{idempotency_key}' is already recorded and committed in "
1297
- f"{matched_file.name if matched_file else 'the journal'}; "
1298
- "nothing to do.",
1299
- file=sys.stderr,
1300
- )
1301
- return 0
1335
+ seen_numbers: set[int] = set()
1336
+ for journal in sorted(dev_dir.glob(f"{FILE_JOURNAL_PREFIX}*.md")):
1337
+ for heading in SESSION_HEADING_RE.finditer(journal.read_text(encoding="utf-8")):
1338
+ number = int(heading.group(1))
1339
+ if number in seen_numbers:
1340
+ print(f"Error: duplicate journal session number {number}; resolve the merged records and index before recording. No new session was written.", file=sys.stderr)
1341
+ return 1
1342
+ seen_numbers.add(number)
1343
+
1344
+ if state == STATE_COMMITTED and idempotency_key and matched_file and matched_num:
1345
+ expected = session_index_row(matched_num, record_date(matched_file, marker), title, evidence, branch)
1346
+ try:
1347
+ indexed = index_has_session_row(index_file, matched_num, expected)
1348
+ except (OSError, ValueError):
1349
+ indexed = False
1350
+ if indexed:
1351
+ print(f"[OK] Session {matched_num} with idempotency key '{idempotency_key}' is already recorded and committed in {matched_file.name}; nothing to do.", file=sys.stderr)
1352
+ return 0
1353
+ state = STATE_JOURNAL_RECORDED
1302
1354
 
1303
1355
  # A committed record is finished, so an identical later request is a
1304
1356
  # legitimately new session. It must not reuse the committed marker: two
@@ -1312,10 +1364,10 @@ def add_session(
1312
1364
  while state == STATE_COMMITTED:
1313
1365
  generation += 1
1314
1366
  marker = render_marker(
1315
- compute_record_fingerprint({**payload, "generation": generation})
1367
+ compute_record_fingerprint({**payload, "generation": generation}), marker_version
1316
1368
  )
1317
1369
  state, matched_file, matched_num, classify_error = classify_record(
1318
- repo_root, dev_dir, index_file, marker
1370
+ repo_root, dev_dir, index_file, marker, title, evidence, branch, rendered_summary
1319
1371
  )
1320
1372
  if classify_error:
1321
1373
  print(f"Error: {classify_error}", file=sys.stderr)
@@ -1337,7 +1389,6 @@ def add_session(
1337
1389
  journal_file, current_num, current_lines = get_latest_journal_info(dev_dir)
1338
1390
  new_session = resolve_next_session(repo_root, dev_dir, index_file)
1339
1391
 
1340
- rendered_summary = _append_topic_links(summary, topic_paths, dev_dir, repo_root)
1341
1392
  session_content = generate_session_content(
1342
1393
  new_session, title, evidence, rendered_summary, today, marker, package, branch,
1343
1394
  changes=changes, extra_content=extra_content, tests=tests,
@@ -1424,7 +1475,7 @@ def add_session(
1424
1475
  evidence,
1425
1476
  new_session,
1426
1477
  active_file,
1427
- today,
1478
+ record_date(target_file, marker),
1428
1479
  branch,
1429
1480
  ):
1430
1481
  print(
@@ -1439,6 +1490,15 @@ def add_session(
1439
1490
  else:
1440
1491
  print(f"[OK] index.md already records session {new_session}.", file=sys.stderr)
1441
1492
 
1493
+ try:
1494
+ expected = session_index_row(new_session, record_date(target_file, marker), title, evidence, branch)
1495
+ if (find_marker_entries(dev_dir, marker) != [(target_file, new_session)]
1496
+ or not index_has_session_row(index_file, new_session, expected)):
1497
+ raise ValueError("journal/index verification did not find this exact record")
1498
+ except (OSError, ValueError) as exc:
1499
+ print(f"[BLOCKED] Checkpoint: {exc}. Preserve the journal and retry after repairing index.md.", file=sys.stderr)
1500
+ return 1
1501
+
1442
1502
  print("", file=sys.stderr)
1443
1503
  print("========================================", file=sys.stderr)
1444
1504
  print(f"[OK] Journal session {new_session} and index recorded (topic content must be verified separately).", file=sys.stderr)
@@ -1493,7 +1553,7 @@ def main() -> int:
1493
1553
  help=(
1494
1554
  "Comma-separated commit OIDs (7-40 hex chars each). Each one is "
1495
1555
  "resolved to its real subject before anything is written; an "
1496
- "unresolvable OID fails the command. Use '-' for a planning session."
1556
+ "unresolvable OID fails the command. Use '-' for no associated commits."
1497
1557
  ),
1498
1558
  )
1499
1559
  parser.add_argument(
@@ -1540,6 +1600,10 @@ def main() -> int:
1540
1600
 
1541
1601
  # Load active task once — shared by package and branch resolution
1542
1602
  repo_root = get_repo_root()
1603
+ trellis = repo_root / DIR_WORKFLOW
1604
+ if not trellis.is_dir() or trellis.is_symlink():
1605
+ print("Error: project is not initialized with a regular .trellis directory; journal not written.", file=sys.stderr)
1606
+ return 1
1543
1607
  topic_links: list[str] = []
1544
1608
  for topic in args.topic:
1545
1609
  try:
@@ -1605,9 +1669,11 @@ def _write_recording_status(exit_code: int) -> None:
1605
1669
  """
1606
1670
  try:
1607
1671
  trellis = get_repo_root() / DIR_WORKFLOW
1608
- if not trellis.is_dir():
1672
+ if not trellis.is_dir() or trellis.is_symlink():
1609
1673
  return
1610
1674
  target = trellis / ".runtime" / "writes" / "latest.json"
1675
+ if not target.resolve().is_relative_to(trellis.parent.resolve()):
1676
+ raise OSError("recording diagnostics escape the project")
1611
1677
  target.parent.mkdir(parents=True, exist_ok=True)
1612
1678
  payload: dict[str, object] = {
1613
1679
  "schema": 1,
@@ -55,7 +55,7 @@ DEVELOPER_HINT = (
55
55
  # =============================================================================
56
56
 
57
57
  def get_repo_root(start_path: Path | None = None) -> Path:
58
- """Find the nearest directory containing .trellis/ folder.
58
+ """Find the nearest initialized project, bounded by an independent Git root.
59
59
 
60
60
  This handles nested git repos correctly (e.g., test project inside another repo).
61
61
 
@@ -63,17 +63,24 @@ def get_repo_root(start_path: Path | None = None) -> Path:
63
63
  start_path: Starting directory to search from. Defaults to current directory.
64
64
 
65
65
  Returns:
66
- Path to repository root, or current directory if no .trellis/ found.
66
+ Nearest initialized project or independent Git root; otherwise the
67
+ original starting directory.
67
68
  """
68
69
  current = (start_path or Path.cwd()).resolve()
69
70
 
70
- while current != current.parent:
71
- if (current / DIR_WORKFLOW).is_dir():
71
+ start = current
72
+ while True:
73
+ trellis = current / DIR_WORKFLOW
74
+ if trellis.is_dir() and not trellis.is_symlink():
72
75
  return current
76
+ if (current / ".git").exists():
77
+ return current
78
+ if current == current.parent:
79
+ break
73
80
  current = current.parent
74
81
 
75
82
  # Fallback to current directory if no .trellis/ found
76
- return Path.cwd().resolve()
83
+ return start
77
84
 
78
85
 
79
86
  # =============================================================================