Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/tsk-bxdfvz-helper-path-guard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- `scripts/resume_arm_time.py` now refuses to emit the system-crontab block when `_HELPER_PATH` resolves under a temp directory or inside a linked git worktree, naming the reason instead of pinning an ephemeral path that would orphan the self-removal cron line.
47 changes: 44 additions & 3 deletions scripts/resume_arm_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
import sys
import time

_HELPER_PATH = os.path.realpath(__file__)

# The two tunables, each stating WHAT IT IS A FUNCTION OF. That is the whole point of
# this file: a constant whose dependency is unnamed is the bug it exists to prevent.
#
Expand Down Expand Up @@ -497,14 +499,52 @@ def retry_after(primary_fire, minutes, margin, lead=RETRY_LEAD_SECONDS):
)


def _is_under_temp(path):
temp_roots = ("/tmp", "/var/tmp", "/private/var/folders", "/var/folders")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: _is_under_temp misses resolved macOS temp paths

_HELPER_PATH is computed with os.path.realpath(__file__), but the temp-root list only contains the unresolved paths. On macOS, /tmp and /var/tmp are symlinks to /private/tmp and /private/var/tmp respectively. After realpath, a checkout under /tmp would resolve to /private/tmp/..., which is not in the check list, so the guard silently fails to detect it.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

for root in temp_roots:
if path == root or path.startswith(root + os.sep):
return root
return None


def _is_in_linked_worktree(path):
parent = os.path.dirname(os.path.abspath(path))
while parent and parent != os.path.dirname(parent):
git_dir = os.path.join(parent, ".git")
if os.path.exists(git_dir):
if os.path.isfile(git_dir):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: _is_in_linked_worktree false-positives on git submodules

Git submodules also have .git as a file (containing gitdir: ...), but they are not ephemeral like linked worktrees. The script would refuse to run from a submodule checkout, which is overly broad and could block legitimate non-ephemeral use cases.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

return parent
return None
parent = os.path.dirname(parent)
return None


def _validate_helper_path():
path = _HELPER_PATH
tmp = _is_under_temp(path)
if tmp:
raise SystemExit(
f"FAIL: {_HELPER_PATH} resolves under a temp directory ({tmp}).\n"
"A cron line armed from a temp checkout cannot self-delete when the\n"
"directory is cleaned up. REFUSING to emit."
)
wt = _is_in_linked_worktree(path)
if wt:
raise SystemExit(
f"FAIL: {_HELPER_PATH} is inside a git worktree ({wt}).\n"
"Worktree checkouts are ephemeral; the cron line would pin a path\n"
"that vanishes when the worktree is removed. REFUSING to emit."
)


def system_crontab_block(primary_fire, retry_fire):
"""System crontab lines for the resume pair, with self-deletion and path-precise markers."""
p_min, p_hou, p_dy, p_mo = cron_fields(primary_fire)
r_min, r_hou, r_dy, r_mo = cron_fields(retry_fire)
p_ts = primary_fire.strftime("%Y%m%d%H%M")
r_ts = retry_fire.strftime("%Y%m%d%H%M")
marker_prefix = "/home/jay/.taos-fleet-tools/resume_arm_time.py#"
helper = "/home/jay/.taos-fleet-tools/resume_arm_time.py"
marker_prefix = _HELPER_PATH + "#"
helper = _HELPER_PATH

lines = [
"SYSTEM CRONTAB (durable, survives session death):",
Expand Down Expand Up @@ -539,7 +579,7 @@ def do_fire(fire_type, timestamp_str):
)

ts = timestamp.strftime("%Y%m%d%H%M")
marker = f"/home/jay/.taos-fleet-tools/resume_arm_time.py#{fire_type}-{ts}"
marker = f"{_HELPER_PATH}#{fire_type}-{ts}"

record = f"[RESUME DUE] {fire_type} fired armed_at={timestamp_str}"

Expand Down Expand Up @@ -745,6 +785,7 @@ def main():
" something in the SYSTEM crontab, outside the component that failed.\n"
" If instead you write these lines into a crontab, durability is fine but\n"
" recurring=false does not exist there, so re-read the ONE-SHOT line.")
_validate_helper_path()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: _validate_helper_path() is called late in main()

This validation runs after all the crontab derivation computation. If the script is invoked from an ephemeral location, it still performs the full derivation before refusing to emit the block. Moving the call to the very start of main() would fail fast and avoid unnecessary work.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

print(system_crontab_block(fire, r_fire))


Expand Down
59 changes: 55 additions & 4 deletions tests/test_resume_arm_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def _load_module():

def _marker(fire_type, armed_at):
ts = datetime.datetime.fromisoformat(armed_at).strftime("%Y%m%d%H%M")
return f"/home/jay/.taos-fleet-tools/resume_arm_time.py#{fire_type}-{ts}"
return f"{resume_arm_time._HELPER_PATH}#{fire_type}-{ts}"


class _Proc:
Expand Down Expand Up @@ -111,6 +111,11 @@ def test_canonical_derivation_emits_date_pinned_one_shot(monkeypatch, capsys):
17 0 18 8 *, a date-pinned one-shot -- not the blocked PR's daily 17 0 * * *."""
monkeypatch.setenv("TZ", "UTC")
time.tzset()
monkeypatch.setattr(
resume_arm_time,
"_HELPER_PATH",
"/home/jay/.taos-fleet-tools/scripts/resume_arm_time.py",
)
written = []
monkeypatch.setattr(
resume_arm_time.subprocess, "run", _fake_run(WATCHER_LINE, written)
Expand Down Expand Up @@ -140,8 +145,8 @@ def test_system_crontab_block_names_usr_bin_python3():
fire = datetime.datetime(2026, 8, 18, 0, 7, 0, tzinfo=datetime.timezone.utc)
retry = datetime.datetime(2026, 8, 18, 0, 17, 0, tzinfo=datetime.timezone.utc)
block = resume_arm_time.system_crontab_block(fire, retry)
assert "/usr/bin/python3 /home/jay/.taos-fleet-tools/resume_arm_time.py --fire primary" in block
assert "/usr/bin/python3 /home/jay/.taos-fleet-tools/resume_arm_time.py --fire retry" in block
assert f"/usr/bin/python3 {resume_arm_time._HELPER_PATH} --fire primary" in block
assert f"/usr/bin/python3 {resume_arm_time._HELPER_PATH} --fire retry" in block
# No bare `python3` token (the blocked PR emitted `python3 <path>`).
assert " python3 " not in block

Expand All @@ -156,6 +161,52 @@ def test_helper_imports_getpass():
assert resume_arm_time.getpass is _gp


# --------------------------------------------------------------------------- #
# Helper-path guard: refuse to emit from a temp or linked-worktree location.
# --------------------------------------------------------------------------- #

def test_guard_refuses_temp_path(monkeypatch, capsys):
"""A _HELPER_PATH under /tmp is refused with a named reason."""
monkeypatch.setattr(
resume_arm_time,
"_HELPER_PATH",
"/tmp/scratchpad/wt354/scripts/resume_arm_time.py",
)
monkeypatch.setattr(
resume_arm_time.subprocess, "run", _fake_run(WATCHER_LINE, [])
)
monkeypatch.setattr(
sys, "argv", ["resume_arm_time.py", "2026-08-18T00:00:00+00:00"]
)
with pytest.raises(SystemExit) as exc:
resume_arm_time.main()
assert "temp directory" in str(exc.value)


def test_guard_refuses_linked_worktree(tmp_path, monkeypatch, capsys):
"""A _HELPER_PATH inside a linked worktree is refused with a named reason."""
fake_wt = Path("/home/jay/Development/fake-wt-for-test")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: test_guard_refuses_linked_worktree uses a hardcoded absolute path

Path("/home/jay/Development/fake-wt-for-test") may not exist or be writable in all test environments (e.g., CI containers, different users). Using tmp_path would make the test hermetic and avoid leaving directories behind.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

try:
fake_wt.mkdir(parents=True, exist_ok=True)
(fake_wt / ".git").write_text("gitdir: /some/real/.git/worktrees/fake\n")
fake_path = str(fake_wt / "scripts" / "resume_arm_time.py")
monkeypatch.setattr(resume_arm_time, "_HELPER_PATH", fake_path)
monkeypatch.setattr(
resume_arm_time.subprocess, "run", _fake_run(WATCHER_LINE, [])
)
monkeypatch.setattr(
sys, "argv", ["resume_arm_time.py", "2026-08-18T00:00:00+00:00"]
)
with pytest.raises(SystemExit) as exc:
resume_arm_time.main()
assert "git worktree" in str(exc.value)
finally:
if (fake_wt / ".git").exists():
(fake_wt / ".git").unlink()
if fake_wt.exists():
fake_wt.rmdir()


# --------------------------------------------------------------------------- #
# Blockers B and D: do_fire posts [RESUME DUE], records the armed-at token,
# self-deletes its crontab marker, and is fully sandboxed.
Expand Down Expand Up @@ -275,7 +326,7 @@ def test_do_fire_runs_as_subprocess(tmp_path, monkeypatch):
marker = _marker("primary", armed_at)
initial_crontab = (
f"# taOSmd-resume: {marker}\n"
+ f"7 0 18 8 * /usr/bin/python3 /home/jay/.taos-fleet-tools/resume_arm_time.py --fire primary {armed_at}\n"
+ f"7 0 18 8 * /usr/bin/python3 {resume_arm_time._HELPER_PATH} --fire primary {armed_at}\n"
+ WATCHER_LINE
)
state = _install_fake_crontab(tmp_path, monkeypatch, initial_crontab)
Expand Down