From dedddfc225e75922728c382afe5faf2afc43fd68 Mon Sep 17 00:00:00 2001 From: rob Date: Wed, 25 Nov 2026 21:31:04 +0000 Subject: [PATCH] TASK-007 Add isolated manual testing adapter --- .gitignore | 6 + .roborto/testtask-hook | 6 + .roborto/testtask.conf | 7 ++ AGENTS.md | 2 +- docs/CURRENT_STATE.md | 8 ++ docs/DECISIONS.md | 7 ++ docs/HANDOFF.md | 35 +++--- docs/PROJECT_OVERVIEW.md | 4 + docs/TASKS.md | 16 +++ scripts/README.md | 45 ++++++++ scripts/tests/test_testtask.py | 78 +++++++++++++ scripts/testtask.sh | 5 + scripts/testtask_adapter.py | 203 +++++++++++++++++++++++++++++++++ 13 files changed, 407 insertions(+), 15 deletions(-) create mode 100755 .roborto/testtask-hook create mode 100644 .roborto/testtask.conf create mode 100644 scripts/tests/test_testtask.py create mode 100755 scripts/testtask.sh create mode 100644 scripts/testtask_adapter.py diff --git a/.gitignore b/.gitignore index 72122b6..3c271e5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,8 @@ /docs/snapshots/ /.worktrees/ + +# Disposable manual-test snapshots +/.test-worktrees/ + +# Python validation caches +__pycache__/ diff --git a/.roborto/testtask-hook b/.roborto/testtask-hook new file mode 100755 index 0000000..4018b8c --- /dev/null +++ b/.roborto/testtask-hook @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +COMMON="$(git -C "$ROBORTO_PROJECT_ROOT" rev-parse --path-format=absolute --git-common-dir)" +SHARED="$(dirname "$COMMON")" +PYTHON="${FOLDERSHARE_TEST_PYTHON:-$SHARED/api/.venv/bin/python}" +exec "$PYTHON" "$ROBORTO_PROJECT_ROOT/scripts/testtask_adapter.py" "$@" diff --git a/.roborto/testtask.conf b/.roborto/testtask.conf new file mode 100644 index 0000000..9b6505b --- /dev/null +++ b/.roborto/testtask.conf @@ -0,0 +1,7 @@ +ROBORTO_PROJECT_SLUG="foldershare" +ROBORTO_TASK_ID_PATTERN='^[0-9]{3}$' +ROBORTO_WORKTREE="${ROBORTO_PROJECT_ROOT}/.test-worktrees/task-${ROBORTO_TASK_ID}" +ROBORTO_HOOK="${ROBORTO_PROJECT_ROOT}/.roborto/testtask-hook" +ROBORTO_BROWSER_URL="http://127.0.0.1:5503/" +ROBORTO_READY_PORTS=(5502 5503) +ROBORTO_READY_LABELS=(API Web) diff --git a/AGENTS.md b/AGENTS.md index 2726559..ba77d43 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,7 @@ Verify and report the current worktree path, branch, Git status, existing uncomm For implementation, use one accepted numbered task per isolated task branch/worktree by default. Concurrent tasks use separate worktrees; do not mix unrelated task changes or edit a manual-test snapshot. Derive the task branch from the repository-approved integration branch. This repository has **no approved branch naming, worktree path, merge strategy, or release branch convention yet**; proposed defaults are in `docs/DECISIONS.md`. Resolve those conventions with Captain before first use rather than treating proposals as established rules. Never switch a branch used by another console or check one branch out in two worktrees. -Do not commit, push, merge, rebase, reset, deploy, or perform destructive operations without repository workflow authority or Captain's explicit authorization. Leave merge and release authority with Captain unless explicitly delegated. The repository has no discovered manual-test/testtask adapter; if one is later added, use it for test evidence and keep implementation in the task worktree. +Do not commit, push, merge, rebase, reset, deploy, or perform destructive operations without repository workflow authority or Captain's explicit authorization. Leave merge and release authority with Captain unless explicitly delegated. Use `scripts/testtask.sh NNN` for isolated manual testing; see `scripts/README.md` for prerequisites and invocation. Implementation stays in its task worktree; `.test-worktrees/` contains disposable test copies only. Refresh by stopping and rerunning after source changes. Never copy live environment, databases or media into a snapshot. ## Task lifecycle and handoff diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index ea2d052..89eeb78 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -34,3 +34,11 @@ These observations are based on the supplied ZIP source, **not runtime exploit t - Tests and production deployment are still unverified. The ZIP is not a live Git repository; its HEAD/branch are historical snapshot metadata. No source-code security fixes or runtime validation are part of this reconciliation patch. + +## TASK-007 adapter implementation (2026-11-05) + +- Worktree `/home/rob/projects/foldershare/.worktrees/TASK-007`, branch `task/TASK-007-testtask`, base `codex` / `cd6d6b3`; uncommitted and awaiting Captain validation. Primary worktree and TASK-002 implementation left untouched. +- Testtask adapter now provisioned and smoke-tested in this worktree. Until integrated, invoke `./.worktrees/TASK-007/scripts/testtask.sh 002` from primary root; `scripts/README.md` documents prerequisites and lifecycle. +- Six adapter safety tests pass; Python and shell syntax/diff checks pass. Repeated Flask/Vite lifecycle smoke checks passed, including real headless Firefox startup, HTTP 200 frontend/401 protected API, proxy logins and disabled-account rejection. Occupied-port refusal preserves unrelated listeners; cleanup removes owned snapshots. Source snapshot includes 75 safe files from TASK-002 and verifies hashes before readiness. +- Uses existing dependencies (no install), ephemeral database/media/accounts and loopback 5502/5503. No real media or local databases used. Test fixtures seed initial access tokens; application login issuance is unchanged and not certified by this harness. +- Graphical browser interaction and Captain acceptance remain. No production readiness, clean dependency-install verification, merge or deployment claimed. The earlier no-adapter observation applies to primary codex until TASK-007 integration. TASK-002's sibling worktree remains implementation-ready, unmerged. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 5c7a77c..30961a0 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -68,3 +68,10 @@ Until approved, brief the concrete convention choice before creating later task ## Pending: Git integration branch convention The 2026-11-04 snapshot references work on `codex` while the existing proposal suggests `main`. There is no evidence that a general integration branch choice was approved. Before creating a task worktree, Codex must inspect live Git state and ask Captain to approve the integration base, worktree path, and eventual merge destination. A task branch is not authority to merge or deploy. + +## WF-004: TASK-007 testtask implementation + +- Accepted by Captain on 2026-11-05: codex base at cd6d6b3, task/TASK-007-testtask, .worktrees/TASK-007. Merge and deployment remain Captain authority. +- Use the existing standalone roborto-testtask engine with a project adapter. Safe source copies are disposable testing snapshots, not Git checkouts or development sources. The adapter discovers a unique checked-out task/TASK-###-* branch and includes current tracked/permitted untracked source. +- Flask/Vite bind only 127.0.0.1:5502/5503, with an isolated Vite proxy. Reuse existing dependency installations without installs or runtime source changes. Mutable Vite cache goes into run state. +- SQLite, accounts and sample media are generated per session; no live state is copied. Candidate must support FOLDERSHARE_DATABASE_URI. No application code is patched to make the harness work. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 6f66072..12cea2a 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,26 +1,33 @@ # Foldershare handoff -This is a replaceable snapshot. Live repository/Git and maintained context take precedence. +Updated 2026-11-05. TASK-007: **Implementation-ready / awaiting Captain validation**. -- Updated: 2026-11-04 (planning reconciliation from `foldershare-20261104-160824-012796.zip`) -- Snapshot documents report `codex` / `767b424` at the earlier inspection; live Git worktree, branch, status and HEAD **have not been checked** in this archive-only reconciliation. -- Files changed by patch: `docs/PROJECT_OVERVIEW.md`, `docs/DECISIONS.md`, `docs/CURRENT_STATE.md`, `docs/TASKS.md`, `docs/HANDOFF.md` only. No application code, no tests executed, no merge or deployment. +## Location and state -## Current outcome +Implementation: `/home/rob/projects/foldershare/.worktrees/TASK-007`, branch `task/TASK-007-testtask`, base `codex` / `cd6d6b3`. Uncommitted; no merge/push/deployment. Primary and TASK-002 worktrees untouched. TASK-002's own handoff remains in its worktree and its acceptance is separate. -Captain defined FolderShare as a private Pi-hosted, read-only browser/download service for named friends. V1: single assigned root per user, admin-controlled accounts, browse and single-file download using opaque filename-free URLs. Future: multi-select ZIP downloads. The patch records PRD-001 through PRD-004 and DEP-001, plus TASK-002 through TASK-006; security/auth fixes must precede exposure. +## Captain action -## Major static-source risks to address +From `/home/rob/projects/foldershare`: -`POST /api/file` trusts client path; user mutation routes lack admin checks; listing exposes host paths; download click is not wired; token/disabled behavior needs tests. See `CURRENT_STATE.md`. Do not expose this snapshot implementation to untrusted users. +```sh +./.worktrees/TASK-007/scripts/testtask.sh 002 +``` -## Next Codex action +Choose Firefox. The launcher opens http://127.0.0.1:5503 and prints this session's disposable password for `captain` (admin), `friend`, `unassigned`, `disabled`. The disabled account must fail login. Confirm admin user-management and folder assignment behavior, then Ctrl-C in the terminal to stop servers and remove session data/snapshot. No live accounts/media are copied. After integration, the shorter command is `./scripts/testtask.sh 002`. -1. In the **live repository**, read AGENTS/context documents and inspect branch, HEAD, git status, worktrees and existing changes before applying this patch. Check patch with `git apply --check`; do not overwrite later edits. -2. Apply documentation-only patch, review diff and report conflicts. Do **not** quietly replace newer state or start any implementation task. -3. Ask Captain to select TASK-002 as first implementation task and approve concrete integration branch/worktree conventions (live `codex` vs proposal `main`). Keep TASK-006 blocked pending remote access and target Pi choice. -4. Once authorized, create one isolated worktree for TASK-002, implement/test there, and submit a Captain-validation handoff. Do not merge or deploy without authority. +Keep TASK-002 stable during testing; rerun after edits. Snapshots are exact safe-file copies under TASK-007's ignored `.test-worktrees/task-002`, not Git branches or editing sources. Hash manifest and session state are in a private engine temporary directory. Existing snapshots are never overwritten. See `scripts/README.md` for prerequisites, exclusions, ports, Node/Python overrides and abrupt-exit recovery. ## Validation -Patch was generated from the exact supplied ZIP. No live Git or application validation can be claimed from the archive alone. +- `python3 -m unittest discover -s scripts/tests -v`: six pass. +- `bash -n scripts/testtask.sh .roborto/testtask-hook .roborto/testtask.conf`: pass. +- `python3 -m py_compile scripts/testtask_adapter.py` and `git diff --check`: pass. +- Engine runs against TASK-002: 75-file snapshot hash verification; real Flask/Vite readiness; frontend 200, direct/proxied protected API 401; valid fixture logins and disabled rejection; actual headless Firefox startup; automatic cleanup. Repeated sessions succeed. Occupied-port test confirms safe refusal without killing the listener. +- Bounded diff/source review covered shell entry/config, source discovery/copy, exclusions, DB isolation, foreground process ownership, runtime credentials and cleanup. No application source edits. + +## Limits + +Graphical user interaction awaits Captain. Existing local dependencies reused; no installation/container/clean-environment verification. Candidate must support isolated database configuration (TASK-002); TASK-007's baseline application itself lacks that prerequisite until integration. Fresh fixture tokens enable existing login for testing; this does not fix or certify application token issuance. Ordinary-user browse UI and secure downloads remain TASK-003/TASK-004. + +Accept TASK-007 only after manual review. Merge/release remain Captain authority; do not start another task automatically. diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md index 818b838..a1f4739 100644 --- a/docs/PROJECT_OVERVIEW.md +++ b/docs/PROJECT_OVERVIEW.md @@ -33,3 +33,7 @@ Local environment files and runtime data under `api/` are ignored by Git. Their ## Product direction accepted 2026-11-04 (requirements; not verified implementation) FolderShare is intended as a private, read-only, authenticated file browser and downloader for selected friends, hosted on a Raspberry Pi on Captain's LAN. The Pi will access an existing video library through a shared/mounted folder. Captain administers accounts and each account's accessible folder. An intended hostname is `share.roborto.net` (subject to DNS/network-access design). V1 permits browsing and single-file downloads; multi-select file/folder ZIP downloads are deferred. These are product requirements, not claims that the current application implements them safely. + +## Manual testing adapter (TASK-007, pending integration) + +`scripts/testtask.sh`, `.roborto/testtask.conf` and `.roborto/testtask-hook` adapt the installed `roborto-testtask` engine using `scripts/testtask_adapter.py`. The adapter uses disposable source copies, SQLite/accounts/media and loopback Flask/Vite services. See `scripts/README.md`; existing local Python/Node installations are prerequisites, not bundled dependencies. These files are present on TASK-007 only until integration. diff --git a/docs/TASKS.md b/docs/TASKS.md index 213efbc..1e29fde 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -96,3 +96,19 @@ The scopes below translate Captain's explicit product requirements into implemen ## Future feature concept (no numbered task yet) - Batch file/folder selection and prepared or streamed ZIP download (PRD-004). Scope a task only when Captain schedules it. ZIP entries must reuse V1 path/permission protections; no compression-heavy default for large existing videos. + +## TASK-007: Configure testtask + +- Status: Complete. Captain confirmed the graphical test worked on 2026-11-25 and authorized commit and merge into codex. +- Objective: Make the installed roborto-testtask engine usable for isolated FolderShare manual testing. +- Scope: Wrapper, engine configuration, project lifecycle hook, exact safe snapshots of checked-out task branches including uncommitted/permitted untracked files, disposable SQLite/accounts/media, loopback Flask/Vite services, readiness, cleanup and documentation. +- Non-goals: Application changes, copying live databases/media/secrets, dependency installation, containerization, merge or deployment; do not modify TASK-002. +- Acceptance: One documented command prepares TASK-002, verifies snapshot hashes, starts isolated API/frontend, passes HTTP smoke checks, prints disposable credentials, and removes only owned state on exit. Repeated runs work; occupied ports and existing snapshots fail safely; malformed IDs/unknown sources are rejected. Captain manual browser validation required. +- Dependencies: Installed roborto-testtask, Firefox, Python API environment, Node >=18 and existing react/node_modules; candidate must support FOLDERSHARE_DATABASE_URI (TASK-002). +- Branch/worktree: Captain approved codex base, task/TASK-007-testtask and .worktrees/TASK-007. Captain authorized local integration into codex on 2026-11-25. +- Risks: Snapshot omissions, stale source, secret inclusion, unsafe cleanup, port conflicts and dependency drift. Use hash manifests, exclusions, ownership markers and loopback binding. +- Validation: Shell/Python syntax, adapter safety tests and engine lifecycle smoke using TASK-002; record graphical-browser limitations honestly. +- Specialist: Roborto Project Context and Webapp Feature; bounded diff review. + +- TASK-007 evidence: Six adapter safety tests pass; shell/Python syntax and diff checks pass. Repeated real-server lifecycle runs pass, including headless Firefox startup, frontend/API HTTP readiness, proxy logins and disabled-login denial; snapshots removed on exit. Occupied-port refusal preserves an unrelated listener. The adapter uses existing dependencies and leaves the source application intact. +- Captain accepted the graphical Firefox run using TASK-002. Six adapter tests passed again and the owned snapshot was removed on shutdown. diff --git a/scripts/README.md b/scripts/README.md index a722394..50c0616 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -9,3 +9,48 @@ python3 scripts/create_snapshot.py The script writes a timestamped ZIP into `docs/snapshots/`. It includes the application source, `AGENTS.md`, `docs/`, and `scripts/`, including safe untracked files. It omits Git metadata, task worktrees, dependency directories, local environment files, local databases, shared files, caches, generated builds, prior snapshots, symlinks, and common key/credential files. The root `.gitignore` ignores `docs/snapshots/` and `.worktrees/`. Inspect the ZIP contents before uploading it if you have added new local data or sensitive file types to the project. + +## Manual task testing (`testtask`) + +From the primary project root, run: + +```sh +./scripts/testtask.sh 002 +``` + +Supply the three-digit task number. +The adapter locates a unique checked-out `task/TASK-002-*` branch, captures its +current tracked changes and permitted untracked files, then starts an isolated +copy at http://127.0.0.1:5503 with API at 127.0.0.1:5502. Both ports must be free. +The candidate must support `FOLDERSHARE_DATABASE_URI` (provided by TASK-002). + +Prerequisites: installed `roborto-testtask`, Firefox/display, existing Python API +venv and frontend node_modules in the primary worktree, and Node >=18. No packages +are installed automatically. Python defaults to primary `api/.venv/bin/python`; +set `FOLDERSHARE_TEST_PYTHON` to override. Node uses PATH, otherwise the latest +installed nvm version; set `FOLDERSHARE_TEST_NODE` to choose explicitly. Dependencies +are reused; this verifies the local environment, not a clean dependency install. + +Choose Firefox at the prompt. The launcher prints fresh disposable credentials: +`captain` (admin), `friend` (assigned `/friends`), `unassigned`, and `disabled` +(which must fail login). Each run has a new shared test password. Only a generated +sample file is available; live media/databases/environment files are excluded. + +Snapshots live below the adapter checkout's ignored `.test-worktrees/`. Source +hashes are verified before startup and again before readiness; rerun after any +candidate edit. Do not develop in a snapshot. A running session is not refreshed +in place. Ctrl-C stops the owned processes and removes that session's snapshot, +database, credentials and cache. Foreign/existing snapshots are never replaced; +after an abrupt machine/launcher failure, inspect ownership and remaining +processes before manually clearing a leftover snapshot. Do not run broad cleanup. + +Test credentials have initial access tokens so existing login rendering can be +exercised; this is test fixture setup, not a fix to application token issuance. +Secure downloads are tracked in TASK-004. + +Adapter checks: + +```sh +python3 -m unittest discover -s scripts/tests -v +bash -n scripts/testtask.sh .roborto/testtask-hook .roborto/testtask.conf +``` diff --git a/scripts/tests/test_testtask.py b/scripts/tests/test_testtask.py new file mode 100644 index 0000000..2e36716 --- /dev/null +++ b/scripts/tests/test_testtask.py @@ -0,0 +1,78 @@ +"""Safety checks: python3 -m unittest discover -s scripts/tests -v.""" +import importlib.util +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] +os.environ.update(ROBORTO_PROJECT_ROOT=str(ROOT), ROBORTO_RUN_DIR='/tmp/testtask-unit-run', ROBORTO_TASK_ID='002', ROBORTO_WORKTREE=str(ROOT / '.test-worktrees/task-002')) +spec = importlib.util.spec_from_file_location('adapter', ROOT / 'scripts/testtask_adapter.py') +adapter = importlib.util.module_from_spec(spec) +spec.loader.exec_module(adapter) + + +class AdapterTests(unittest.TestCase): + def test_snapshot_excludes_local_data_and_links(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + subprocess.run(['git', 'init', '-q', str(root)], check=True) + for name in ['api/source.py', 'api/new_test.py', 'api/.env', 'api/accounts.sqlite', 'api/share/movie.mp4', 'react/node_modules/package/code.js', 'docs/snapshots/old.zip', 'api/id_rsa', '.roborto/testtask.conf']: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('fixture') + (root / 'api/link.py').symlink_to(root / 'api/source.py') + subprocess.run(['git', '-C', str(root), 'add', 'api/source.py'], check=True) + (root / 'api/source.py').write_text('unstaged change') + files = adapter.safe_files(root) + self.assertEqual(set(files), {'api/source.py', 'api/new_test.py', '.roborto/testtask.conf'}) + (root / 'api/new_test.py').write_text('updated') + self.assertNotEqual(files, adapter.safe_files(root)) + + def test_cleanup_preserves_foreign_snapshot(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + snapshot = root / '.test-worktrees/task-002' + snapshot.mkdir(parents=True) + marker = snapshot / adapter.MARKER + marker.write_text('/other/session') + with patch.object(adapter, 'ROOT', root), patch.object(adapter, 'SNAPSHOT', snapshot): + adapter.cleanup() + self.assertTrue(snapshot.exists()) + marker.write_text(str(adapter.RUN)) + adapter.cleanup() + adapter.cleanup() + self.assertFalse(snapshot.exists()) + + def test_cleanup_rejects_unexpected_path(self): + with patch.object(adapter, 'SNAPSHOT', Path('/tmp/unowned')): + with self.assertRaises(RuntimeError): + adapter.cleanup() + + def test_existing_snapshot_is_never_replaced(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + snapshot = root / '.test-worktrees/task-002' + snapshot.mkdir(parents=True) + with patch.object(adapter, 'ROOT', root), patch.object(adapter, 'SNAPSHOT', snapshot): + with self.assertRaisesRegex(RuntimeError, 'already exists'): + adapter.validate() + + def test_malformed_task_rejected(self): + with patch.object(adapter, 'TASK', '../002'): + with self.assertRaises(RuntimeError): + adapter.validate() + + def test_task_discovery(self): + output = b'worktree /tmp/TASK-002\0HEAD abc\0branch refs/heads/task/TASK-002-authorization\0\0' + with patch.object(adapter.subprocess, 'check_output', return_value=output): + self.assertEqual(adapter.source(), Path('/tmp/TASK-002')) + with patch.object(adapter, 'TASK', '999'): + with self.assertRaisesRegex(RuntimeError, 'found 0'): + adapter.source() + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/testtask.sh b/scripts/testtask.sh new file mode 100755 index 0000000..67f04b3 --- /dev/null +++ b/scripts/testtask.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." +command -v roborto-testtask >/dev/null || { echo 'Install roborto-testtask first.' >&2; exit 127; } +exec roborto-testtask "$@" diff --git a/scripts/testtask_adapter.py b/scripts/testtask_adapter.py new file mode 100644 index 0000000..8bac4bc --- /dev/null +++ b/scripts/testtask_adapter.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Local testtask hook: exact safe source copy, isolated state, foreground servers.""" +import base64 +import hashlib +import json +import os +from pathlib import Path +import re +import secrets +import shutil +import subprocess +import sys + +ROOT = Path(os.environ['ROBORTO_PROJECT_ROOT']).resolve() +RUN = Path(os.environ['ROBORTO_RUN_DIR']).resolve() +TASK = os.environ['ROBORTO_TASK_ID'] +SNAPSHOT = Path(os.environ['ROBORTO_WORKTREE']) +COMMON = Path(subprocess.check_output(['git', '-C', str(ROOT), 'rev-parse', '--path-format=absolute', '--git-common-dir'], text=True).strip()) +SHARED = COMMON.parent +MARKER = '.testtask-owner' +EXCLUDED_DIRS = {'.git', '.worktrees', '.test-worktrees', '.venv', 'venv', 'node_modules', 'share', 'instance', '__pycache__', '.pytest_cache', 'dist', 'dist-ssr', 'build', 'coverage', 'snapshots', 'logs'} +SUFFIXES = ('.pyc', '.pyo', '.log', '.zip', '.db', '.sqlite', '.sqlite3', '.pem', '.key', '.p12', '.pfx') + + +def fail(message): + raise RuntimeError(message) + + +def source(): + entries = subprocess.check_output(['git', '-C', str(ROOT), 'worktree', 'list', '--porcelain', '-z']).decode().split('\0') + found, path = [], None + for entry in entries: + if entry.startswith('worktree '): + path = Path(entry[9:]) + if entry.startswith('branch refs/heads/') and re.fullmatch(r'(?:task/TASK-' + TASK + r'-[\w-]+)', entry[18:]): + found.append(path) + if len(found) != 1: + fail(f'Expected exactly one checked-out task/TASK-{TASK}-* branch; found {len(found)}') + return found[0] + + +def safe_files(src): + names = subprocess.check_output(['git', '-C', str(src), 'ls-files', '-z', '--cached', '--others', '--exclude-standard']).split(b'\0') + result = {} + for raw in names: + if not raw: + continue + relative = Path(os.fsdecode(raw)) + path = src / relative + if any(part in EXCLUDED_DIRS for part in relative.parts): + continue + if any(part.startswith('.') and part not in {'.gitignore', '.roborto'} for part in relative.parts): + continue + if relative.name.lower().startswith(('credentials', 'id_rsa', 'id_ed25519')) or relative.name.lower().endswith(SUFFIXES): + continue + if any(parent.is_symlink() for parent in [path, *path.parents]) or not path.is_file(): + continue + result[relative.as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() + return result + + +def dependencies(): + node = os.environ.get('FOLDERSHARE_TEST_NODE') or shutil.which('node') + if not node: + candidates = list((Path.home() / '.nvm/versions/node').glob('v*/bin/node')) + candidates.sort(key=lambda p: tuple(int(n) for n in p.parents[1].name[1:].split('.'))) + node = str(candidates[-1]) if candidates else None + vite = SHARED / 'react/node_modules/vite/bin/vite.js' + if not node or not Path(node).is_file() or not vite.is_file(): + fail('Need Node >=18 and existing react/node_modules; install dependencies separately') + version = subprocess.check_output([node, '-p', 'process.versions.node'], text=True) + if int(version.split('.')[0]) < 18: + fail('Node >=18 required; set FOLDERSHARE_TEST_NODE') + return node, vite + + +def validate(): + if not re.fullmatch(r'\d{3}', TASK): + fail('Task ID must contain three digits') + expected = ROOT / '.test-worktrees' / ('task-' + TASK) + if SNAPSHOT != expected or SNAPSHOT.parent.is_symlink() or SNAPSHOT.is_symlink(): + fail('Unexpected or symlinked snapshot path') + if SNAPSHOT.exists(): + fail('Snapshot already exists; preserve it and stop its owning session first') + src = source() + # Older application settings must never silently fall back to a local DB. + if 'FOLDERSHARE_DATABASE_URI' not in (src / 'api/settings.py').read_text(): + fail('Candidate lacks isolated database configuration (TASK-002 prerequisite)') + dependencies() + import flask, flask_sqlalchemy, flask_httpauth, flask_migrate, sqlalchemy_serializer # noqa: F401 + print(f'Validated source {src}', file=sys.stderr) + + +def prepare(): + validate() + src = source() + manifest = safe_files(src) + SNAPSHOT.parent.mkdir(exist_ok=True) + SNAPSHOT.mkdir(mode=0o700) + (SNAPSHOT / MARKER).write_text(str(RUN)) + for name in manifest: + dest = SNAPSHOT / name + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src / name, dest) + copied = {name: hashlib.sha256((SNAPSHOT / name).read_bytes()).hexdigest() for name in manifest} + if copied != manifest or safe_files(src) != manifest: + fail('Source changed during snapshot creation; rerun with a stable candidate') + (RUN / 'manifest.json').write_text(json.dumps({'source': str(src), 'files': manifest}, indent=2)) + (SNAPSHOT / 'react/node_modules').symlink_to(SHARED / 'react/node_modules', target_is_directory=True) + (SNAPSHOT / 'react/testtask.vite.config.mjs').write_text('''import base from './vite.config.js'; +export default {...base, cacheDir: process.env.FOLDERSHARE_TEST_CACHE, +server: {...base.server, host: '127.0.0.1', port: 5503, strictPort: true, +proxy: {'/api': 'http://127.0.0.1:5502'}}}; +''') + media = RUN / 'media' + (media / 'friends').mkdir(parents=True) + (media / 'friends/sample.txt').write_text('Disposable test media only.\n') + (RUN / 'password').write_text(secrets.token_urlsafe(18)) + print(f'Snapshot verified: {len(manifest)} source files from {src}', file=sys.stderr) + + +def start_backend(): + env = os.environ.copy() + env.update(FOLDERSHARE_DATABASE_URI='sqlite:///' + str(RUN / 'accounts.sqlite'), ROOT_PATH=str(RUN / 'media'), PYTHON_DOTENV_DISABLED='1', DEBUG='False', SQLALCHEMY_ECHO='False', PYTHONPATH=str(SNAPSHOT / 'api')) + bootstrap = '''from pathlib import Path +from settings import app, db +from models.user import User +import os +assert app.config['SQLALCHEMY_DATABASE_URI'] == os.environ['FOLDERSHARE_DATABASE_URI'], 'Unsafe database configuration' +with app.app_context(): + db.create_all() + for name, admin, root in [('captain', True, None), ('friend', False, '/friends'), ('unassigned', False, None), ('disabled', False, '/friends')]: + user = User(username=name, is_admin=admin, root=root, login_disabled=name == 'disabled') + user.set_password(Path(os.environ['ROBORTO_RUN_DIR'], 'password').read_text()) + db.session.add(user) + user.get_token() + db.session.commit() +import api +app.run(host='127.0.0.1', port=5502, debug=False, use_reloader=False) +''' + os.chdir(SNAPSHOT / 'api') + os.execve(sys.executable, [sys.executable, '-c', bootstrap], env) + + +def start_frontend(): + node, vite = dependencies() + env = os.environ.copy() + env['FOLDERSHARE_TEST_CACHE'] = str(RUN / 'vite-cache') + os.chdir(SNAPSHOT / 'react') + os.execve(node, [node, str(vite), '--config', 'testtask.vite.config.mjs'], env) + + +def credentials(): + # Real HTTP checks, in addition to engine port checks. + from urllib.request import Request, urlopen + from urllib.error import HTTPError + for base in ['http://127.0.0.1:5502', 'http://127.0.0.1:5503']: + try: + urlopen(base + '/api/file/root', timeout=5) + fail('Protected API unexpectedly allowed an anonymous request') + except HTTPError as error: + if error.code != 401: + raise + password = (RUN / 'password').read_text() + for name in ['captain', 'friend', 'unassigned', 'disabled']: + basic = base64.b64encode(f'{name}:{password}'.encode()).decode() + request = Request('http://127.0.0.1:5503/api/auth/token', method='POST', headers={'Authorization': 'Basic ' + basic}) + try: + with urlopen(request, timeout=5) as response: + data = json.load(response) + if name == 'disabled' or not data.get('token'): + fail('Disposable login fixture failed') + except HTTPError as error: + if name != 'disabled' or error.code != 401: + raise + manifest = json.loads((RUN / 'manifest.json').read_text()) + if safe_files(Path(manifest['source'])) != manifest['files']: + fail('Candidate changed since snapshot creation; stop and rerun before testing') + with urlopen('http://127.0.0.1:5503', timeout=5) as response: + if response.status != 200: + fail('Frontend HTTP check failed') + print('HTTP readiness passed. Disposable accounts: captain (admin), friend, unassigned, disabled.') + print('Shared session password:', (RUN / 'password').read_text()) + print('Candidate snapshot:', SNAPSHOT) + print('Source must remain unchanged while testing; Ctrl-C stops servers and removes this snapshot.') + + +def cleanup(): + expected = ROOT / '.test-worktrees' / ('task-' + TASK) + if SNAPSHOT != expected or SNAPSHOT.parent.is_symlink(): + fail('Refusing cleanup outside the owned snapshot path') + marker = SNAPSHOT / MARKER + if not SNAPSHOT.is_symlink() and marker.is_file() and marker.read_text() == str(RUN): + shutil.rmtree(SNAPSHOT) + + +if __name__ == '__main__': + try: + actions = {'validate': validate, 'prepare': prepare, 'start-backend': start_backend, 'start-frontend': start_frontend, 'credentials': credentials, 'cleanup': cleanup} + actions[sys.argv[1]]() + except Exception as error: + print(f'testtask: {error}', file=sys.stderr) + sys.exit(1)