Files
planning-with-files/tests/test_pi_extension_capabilities.py
T
OthmanAdi 3e35f428f3 release: v2.40.0 (slug-mode resolution fix + perf cache + KV-cache hygiene + Pi false-positive fix)
Bug fixes (items 1-5 in proposal_v2_40.md):

1. Hook resolution order inverted across UserPromptSubmit, PreToolUse, PreCompact.
   Slug-mode now wins over legacy root task_plan.md when both exist. Closes the
   bug where an active .planning/<slug>/ plan was silently bypassed in favor of
   the root file. Resolution chain: PLAN_ID env > .planning/.active_plan >
   newest .planning/<slug>/ by mtime > root fallback.

2. .active_plan target dir is validated. Dead pointers fall through cleanly.

3. .active_plan content is regex-validated as ^[A-Za-z0-9_][A-Za-z0-9._-]*$.
   Whitespace-only and path-traversal corruption fall through instead of
   producing weird path lookups. Tests cover whitespace, ../escape, and
   leading-dot cases.

4. check-complete.sh wires into resolve-plan-dir.sh when no path arg given.
   Restores slug-mode parity for any caller that invokes the script without an
   explicit plan path.

5. Pi extension dangerous-command detection uses word-boundary regex. Benign
   git push origin <branch> no longer triggers the warning; only --force,
   --mirror, +ref, plus rm -rf, sudo, chmod 777/a+rwx, git reset --hard, git
   clean -fd, fork bombs, dd to /dev/[sh]d[a-z].

Performance (items 6, 7):

6. mtime-keyed SHA-256 cache under ${TMPDIR:-/tmp}/pwf-sha cuts redundant hash
   work on warm cache. Caches the result keyed by absolute plan-file path,
   stores mtime + hash, skips sha256sum when mtime unchanged.

7. KV-cache hygiene on injected progress.md tail. Sub-second timestamps and
   timezone-suffix forms are normalized to a stable epoch-zero form so the
   model's prefix cache stays warm across turns. Manus-aligned.

Portability + races (items 19, 20):

19. resolve-plan-dir.sh portable mtime fallback chain: GNU stat -> BSD stat ->
    date -r -> python3 -> python -> perl -> 0. Multi-plan workflows stop
    silently degrading on non-GNU systems.

20. attest-plan.sh uses atomic temp+rename with optional flock guard.
    Concurrent legacy-mode attestations stop producing truncated files that
    triggered false [PLAN TAMPERED] warnings.

Tests: 130 pass / 2 pre-existing Windows exec-bit failures unchanged. +20 new
tests vs v2.39.0. See CHANGELOG for full inventory.

Version bumped to 2.40.0 across 14 SKILL.md variants + plugin.json +
marketplace.json + CITATION.cff via scripts/bump-version.py. .continue,
.gemini, .pi, .kiro lag intentionally.
2026-05-21 23:07:55 +02:00

117 lines
4.6 KiB
Python

"""Behavioral contract tests for the Pi planning-with-files extension source.
These tests validate that the extension source covers Claude-parity hooks,
DeepSeek cache-safe mode, and loop guard safety constraints.
"""
from __future__ import annotations
import re
import unittest
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
EXT_ROOT = REPO_ROOT / ".pi" / "skills" / "planning-with-files" / "extensions" / "planning-with-files"
INDEX_TS = EXT_ROOT / "index.ts"
RUNTIME_TS = EXT_ROOT / "runtime.ts"
PLAN_TS = EXT_ROOT / "plan.ts"
CONSTANTS_TS = EXT_ROOT / "constants.ts"
class PiExtensionCapabilitiesTests(unittest.TestCase):
def _read(self, path: Path) -> str:
self.assertTrue(path.exists(), f"missing required source file: {path}")
return path.read_text(encoding="utf-8")
def test_required_source_files_exist(self) -> None:
for path in (INDEX_TS, RUNTIME_TS, PLAN_TS, CONSTANTS_TS):
self.assertTrue(path.exists(), f"missing required source file: {path}")
def test_mode_union_contains_auto_parity_cache_safe_notify(self) -> None:
text = self._read(RUNTIME_TS)
self.assertRegex(
text,
r'type\s+HookMode\s*=\s*"auto"\s*\|\s*"parity"\s*\|\s*"cache-safe"\s*\|\s*"notify"',
)
def test_registers_required_hook_events(self) -> None:
text = self._read(RUNTIME_TS)
required_events = [
"session_start",
"before_agent_start",
"tool_call",
"tool_result",
"agent_end",
"session_before_compact",
"input",
]
for event_name in required_events:
self.assertIn(f'pi.on("{event_name}"', text)
def test_auto_continue_limit_is_three(self) -> None:
text = self._read(CONSTANTS_TS)
self.assertRegex(text, r"AUTO_CONTINUE_LIMIT\s*=\s*3")
def test_tampered_blocking_message_exists(self) -> None:
text = self._read(CONSTANTS_TS)
self.assertIn("PLAN TAMPERED", text)
def test_plan_resolution_keeps_plan_id_active_plan_and_newest_fallback(self) -> None:
text = self._read(PLAN_TS)
self.assertIn("process.env.PLAN_ID", text)
self.assertIn(".active_plan", text)
self.assertTrue(
re.search(r"resolveNewestPlanDir", text),
"plan resolver must include newest plan directory fallback",
)
def test_dangerous_bash_uses_word_boundary_regex(self) -> None:
# v2.40: substring matching produced false positives on every benign
# `git push origin <branch>`. The runtime must now use a regex array
# so only destructive variants (--force, --mirror, rm -rf, sudo,
# chmod 777, git reset --hard, git clean -fd, fork bomb, dd to disk)
# trigger the warning.
text = self._read(RUNTIME_TS)
self.assertIn(
"DANGEROUS_BASH_PATTERNS",
text,
"runtime must define DANGEROUS_BASH_PATTERNS regex array",
)
# Substring-match shape must NOT be present. The v2.39.0 dangerPatterns
# list with a raw `"git push"` would fire on every benign push.
self.assertNotIn(
'dangerPatterns =',
text,
"v2.39.0 dangerPatterns substring list still present; replace with "
"DANGEROUS_BASH_PATTERNS regex array",
)
self.assertNotIn(
'"git push",',
text,
"raw substring 'git push' inside the danger list would false-positive "
"on benign pushes; use the --force/--mirror regex variant instead",
)
# Each required pattern, as literal substring of the TS source. These
# are stable to YAML/JS escaping: they appear verbatim in the file.
required_substrings = [
r"\brm\s+-[a-z]*r", # rm -rf, rm -fr, rm -Rf
r"\bsudo\b", # sudo
r"\bchmod\s+(0?777", # chmod 777 / chmod 0777
r"a\+rwx", # chmod a+rwx
r"\bgit\s+push\s+.*(--force", # forced push
r"--mirror", # mirror push
r"\bgit\s+reset\s+--hard\b", # git reset --hard
r"\bgit\s+clean\s+-", # git clean -fd family
r"\bdd\s+.*of=", # dd to a raw device
]
missing = [s for s in required_substrings if s not in text]
self.assertFalse(
missing,
"runtime missing required dangerous-command patterns: "
+ ", ".join(missing),
)
if __name__ == "__main__":
unittest.main()