Skip to content

Commit 3f1b951

Browse files
fix(obsidian): close review residuals O1, O4, O7 in the vault writer
O1 — no directory is ever created outside the vault. mkdir(parents=True) ran BEFORE the containment re-check, so an ancestor swapped for a symlink between projection_path and the write created directories on the far side of the link before the file write was refused. Containment is now checked on the nearest EXISTING ancestor before mkdir (resolve() on unbuilt directories cannot see where a hostile link sends children), re-checked after mkdir as before, and once more immediately before os.replace — narrowing the accepted TOCTOU window to the rename itself. The new test asserts the property that matters: nothing appears outside the vault, not merely that an error was raised. O4 — the dry run previews the replace warning. classify_write returned WRITTEN for an owned-and-changed note, so --dry-run said 'would write' where the real publish then said 'written + replaced your edits' — the one warning added so a learner is told BEFORE losing text was invisible in the preview. classify_write now returns REPLACED, plan_dry_run carries the 'would replace your edits in …' warning, and journey beat 10 asserts the preview warns (and that the dry run itself does not touch the edit). O7 — an unreadable mode refuses the replace. The 0o644 fallback on any OSError meant a note the learner had locked to 0o600 could be silently rewritten world-readable if one stat failed. A vanished file still gets the 0o644 new-file default (the inode-identity check refuses the race); any other stat failure on an existing note now refuses with the reason. All three ruled MINOR-with-small-fix by ARBITRATION Q3. 95 tests across the writer/backend/CLI files pass; 35 journey tests pass; pyright clean.
1 parent 2c48cab commit 3f1b951

5 files changed

Lines changed: 162 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,13 @@ experience may change before `1.0.0`.
4848

4949
### Fixed
5050

51+
- The Obsidian publisher closed three review residuals: containment is now
52+
checked before any directory is created (a hostile ancestor symlink can no
53+
longer cause directories outside the vault) and once more immediately before
54+
the atomic replace; `--dry-run` now says "would replace your edits in …" —
55+
with the same warning a real publish prints — instead of a plain "would
56+
write"; and a note whose permissions cannot be read is refused rather than
57+
silently rewritten with default permissions.
5158
- `get_study_history` (the MCP tool) and `studyloop plan evaluate` no longer
5259
fail when searching session history: the full-text query joined two tables
5360
that both carry a `content` column without qualifying it, and OR'd multiple

‎packages/studyloop/src/studyloop/second_brain/obsidian.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@ def plan_dry_run(self, plan_id: str | None) -> PublishResult:
237237
written: list[str] = []
238238
unchanged: list[str] = []
239239
skipped: list[str] = []
240+
warnings: list[str] = []
240241

241242
if plan_id is None:
242243
identity = self._identity("today-projection", None)
@@ -273,6 +274,16 @@ def plan_dry_run(self, plan_id: str | None) -> PublishResult:
273274
unchanged.append(target.relative)
274275
elif verdict.refusal is not None:
275276
skipped.append(verdict.refusal)
277+
elif verdict.outcome is WriteOutcome.REPLACED:
278+
# The dry run must preview the warning a real publish prints
279+
# (O4): "would write" alone hid that saying yes replaces the
280+
# learner's own edits.
281+
written.append(target.relative)
282+
warnings.append(
283+
f"would replace your edits in '{target.relative}' — a projection "
284+
"is regenerated from the plan, so write beside it in "
285+
f"'{target.relative.removesuffix('.md')}.notes.md' instead."
286+
)
276287
else:
277288
written.append(target.relative)
278289

@@ -282,6 +293,7 @@ def plan_dry_run(self, plan_id: str | None) -> PublishResult:
282293
written=tuple(written),
283294
unchanged=tuple(unchanged),
284295
skipped=tuple(skipped),
296+
warnings=tuple(warnings),
285297
)
286298

287299
def _backlinks(self, plan: StudyPlan) -> tuple[str, ...]:

‎packages/studyloop/src/studyloop/second_brain/obsidian_writer.py‎

Lines changed: 54 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,27 @@ def _assert_replaceable(
242242
)
243243

244244

245+
def _assert_parent_contained(target: VaultTarget, *, when: str) -> None:
246+
"""Refuse when ``target``'s directory no longer resolves under the vault.
247+
248+
Resolved on the nearest EXISTING ancestor: ``Path.resolve`` on a path whose
249+
directories do not exist yet cannot follow a symlink that would be followed
250+
once they do, so checking the unbuilt parent directly would pass exactly
251+
when it matters (O1). ``when`` names the call site in the message so a
252+
refusal says which window it caught.
253+
"""
254+
ancestor = target.path.parent
255+
while not ancestor.exists():
256+
ancestor = ancestor.parent
257+
try:
258+
ancestor.resolve().relative_to(target.root)
259+
except ValueError as exc:
260+
raise SecondBrainError(
261+
f"Refusing to write outside the vault: '{target.relative}' no longer "
262+
f"resolves under the configured vault (checked {when})."
263+
) from exc
264+
265+
245266
@dataclass(frozen=True)
246267
class WriteVerdict:
247268
"""What a write WOULD do, decided without doing it.
@@ -283,7 +304,11 @@ def classify_write(
283304
return WriteVerdict(WriteOutcome.WRITTEN, str(exc))
284305
if existing_text == rendered:
285306
return WriteVerdict(WriteOutcome.UNCHANGED)
286-
return WriteVerdict(WriteOutcome.WRITTEN)
307+
# REPLACED, not WRITTEN (O4): the real publish distinguishes creating a
308+
# note from overwriting a learner's edits, and warns on the latter. A dry
309+
# run that said "would write" for both could not preview the one warning
310+
# that was added precisely so a learner is told before losing text.
311+
return WriteVerdict(WriteOutcome.REPLACED)
287312

288313

289314
def write_projection(
@@ -336,26 +361,38 @@ def write_projection(
336361
# StudyLoop wrote it. Recorded so the caller can say so.
337362
was_replaced = True
338363

364+
# Containment check BEFORE anything is created (O1, 2026-09-04 review):
365+
# mkdir(parents=True) used to run first, so an ancestor swapped for a
366+
# symlink between projection_path and here created directories OUTSIDE the
367+
# vault before the file write was refused. Checked on the nearest EXISTING
368+
# ancestor, because resolve() on a not-yet-created path cannot see where a
369+
# hostile symlink would send its children.
370+
_assert_parent_contained(target, when="before creating directories")
371+
339372
path.parent.mkdir(parents=True, exist_ok=True)
340373

341374
# Re-check containment now that the parents exist: a symlink could have been
342375
# created since projection_path ran. The residual TOCTOU window is accepted --
343376
# it cannot be closed with POSIX path APIs alone -- but narrowing it to the
344377
# microseconds before the replace is worth the extra call.
345-
try:
346-
path.parent.resolve().relative_to(target.root)
347-
except ValueError as exc:
348-
raise SecondBrainError(
349-
f"Refusing to write outside the vault: '{target.relative}' no longer "
350-
"resolves under the configured vault."
351-
) from exc
378+
_assert_parent_contained(target, when="after creating directories")
352379

353380
# Replace-by-rename creates a NEW inode, so an existing note's mode has to be
354381
# copied across or a learner who tightened its permissions silently loses that.
382+
# A file that vanished between the read above and this stat is a new file for
383+
# mode purposes (the inode-identity check below still refuses the replace);
384+
# any OTHER stat failure on an existing note is refused rather than defaulted
385+
# (O7): silently re-opening a note the learner had locked down to 0o600 as
386+
# 0o644 is exactly the loss the copy exists to prevent.
355387
try:
356388
existing_mode = stat.S_IMODE(path.stat().st_mode)
357-
except OSError:
389+
except FileNotFoundError:
358390
existing_mode = 0o644
391+
except OSError as exc:
392+
raise SecondBrainError(
393+
f"Could not read the permissions of '{target.relative}': {exc}. "
394+
"Refusing to replace it, so its mode cannot be silently widened."
395+
) from exc
359396

360397
# delete=False, and closed by the `with handle:` block below before the
361398
# rename: a context manager here would delete the file we are about to
@@ -387,6 +424,14 @@ def write_projection(
387424
f"Refusing to overwrite '{target.relative}': it changed while StudyLoop "
388425
"was preparing the new version. Nothing was written; try again."
389426
)
427+
# And containment one last time, immediately before the replace (O1):
428+
# everything above narrowed the window; this closes it to the rename
429+
# itself, which is as far as POSIX path APIs can take it.
430+
try:
431+
_assert_parent_contained(target, when="before the replace")
432+
except SecondBrainError:
433+
temp_path.unlink(missing_ok=True)
434+
raise
390435
os.replace(temp_path, path)
391436
except OSError as exc:
392437
temp_path.unlink(missing_ok=True)

‎packages/studyloop/tests/journeys/test_obsidian_learners_week.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,19 @@ def remember(beat: str) -> None:
213213
projection + "\n\nI typed this into the projection by mistake.\n",
214214
encoding="utf-8",
215215
)
216+
# O4 (2026-09-04 review): BEFORE the replace happens, the dry run must
217+
# preview the warning — "would write" alone hid that saying yes replaces
218+
# the learner's own edits, which defeats the one thing a preview is for.
219+
preview = world.run("brain", "publish", "--dry-run")
220+
assert preview.exit_code == 0, preview.output
221+
preview_warnings = [detail for status, detail in preview.results() if status == "warning"]
222+
assert any("replace your edits" in w for w in preview_warnings), (
223+
"beat 10: the dry run did not warn that the learner's edits would be "
224+
f"replaced; it printed:\n{preview.output}"
225+
)
226+
assert "I typed this into the projection by mistake." in world.read(PROJECTION), (
227+
"beat 10: the DRY RUN itself replaced the edit"
228+
)
216229
republished = world.run("brain", "publish")
217230
assert republished.exit_code == 0, republished.output
218231
assert "I typed this into the projection by mistake." not in world.read(PROJECTION), (

‎packages/studyloop/tests/test_obsidian_writer.py‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,3 +290,79 @@ def test_create_only_write_refuses_an_existing_file(vault) -> None:
290290
write_projection(target, "# Template\n", _identity(), create_only=True)
291291
with pytest.raises(SecondBrainError, match="already exists"):
292292
write_projection(target, "# Template\n", _identity(), create_only=True)
293+
294+
295+
# ---------------------------------------------------------------------------
296+
# O1/O4/O7 — the 2026-09-04 review's residuals
297+
# ---------------------------------------------------------------------------
298+
299+
300+
def test_no_directory_is_created_outside_the_vault(vault, tmp_path) -> None:
301+
"""O1: containment is checked BEFORE mkdir, on the nearest existing ancestor.
302+
303+
mkdir(parents=True) used to run first, so an ancestor swapped for a symlink
304+
between projection_path and the write created directories OUTSIDE the vault
305+
before the file write was refused. The refusal is not enough on its own —
306+
the test's point is that nothing appears on the far side of the link.
307+
"""
308+
outside = tmp_path / "elsewhere"
309+
outside.mkdir()
310+
target = projection_path(vault, "Study", "Plans/python-decorators.md")
311+
# The ancestor swap, after path validation, before the write.
312+
(vault / "Study").symlink_to(outside, target_is_directory=True)
313+
314+
with pytest.raises(SecondBrainError, match="outside the vault"):
315+
write_projection(target, _rendered(), _identity())
316+
317+
assert list(outside.iterdir()) == [], "directories were created outside the vault"
318+
319+
320+
def test_classify_write_previews_the_replace_warning(vault) -> None:
321+
"""O4: a dry run must say 'would replace', not 'would write'.
322+
323+
classify_write returned WRITTEN for an owned-and-changed note, so --dry-run
324+
could not preview the warning that was added precisely so a learner is told
325+
before losing text.
326+
"""
327+
from studyloop.second_brain.obsidian_writer import classify_write
328+
329+
target = projection_path(vault, "Study", "Plans/python-decorators.md")
330+
write_projection(target, _rendered(), _identity())
331+
332+
plan = full_plan()
333+
plan.mission.why = "Edited by hand since the last publish."
334+
changed = render_plan_projection(plan, _identity())
335+
336+
assert classify_write(target, changed, _identity()).outcome is WriteOutcome.REPLACED
337+
# And the counterpart: a first write must still be WRITTEN, or the warning
338+
# appears on every publish and the learner learns to ignore it.
339+
fresh = projection_path(vault, "Study", "Plans/other.md")
340+
assert classify_write(fresh, changed, _identity()).outcome is WriteOutcome.WRITTEN
341+
342+
343+
def test_unreadable_mode_on_an_existing_note_refuses_the_replace(vault, monkeypatch) -> None:
344+
"""O7: never default a real note's mode to 0o644.
345+
346+
A learner who chmod-ed a note to 0o600 must not have it silently reopened
347+
as 0o644 because one stat failed. New files keep the 0o644 default; an
348+
existing note whose mode cannot be read refuses instead.
349+
"""
350+
target = projection_path(vault, "Study", "Plans/python-decorators.md")
351+
write_projection(target, _rendered(), _identity())
352+
353+
real_stat = Path.stat
354+
355+
def failing_stat(self, *args, **kwargs):
356+
if self == target.path:
357+
raise PermissionError(13, "Permission denied", str(self))
358+
return real_stat(self, *args, **kwargs)
359+
360+
monkeypatch.setattr(Path, "stat", failing_stat)
361+
362+
plan = full_plan()
363+
plan.mission.why = "Changed."
364+
with pytest.raises(SecondBrainError, match="permissions"):
365+
write_projection(target, render_plan_projection(plan, _identity()), _identity())
366+
367+
monkeypatch.undo()
368+
assert "Changed." not in target.path.read_text(), "the note was replaced anyway"

0 commit comments

Comments
 (0)