Merge TASK-007 manual testing adapter into codex
This commit is contained in:
@@ -1,2 +1,8 @@
|
|||||||
/docs/snapshots/
|
/docs/snapshots/
|
||||||
/.worktrees/
|
/.worktrees/
|
||||||
|
|
||||||
|
# Disposable manual-test snapshots
|
||||||
|
/.test-worktrees/
|
||||||
|
|
||||||
|
# Python validation caches
|
||||||
|
__pycache__/
|
||||||
|
|||||||
Executable
+6
@@ -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" "$@"
|
||||||
@@ -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)
|
||||||
@@ -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.
|
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
|
## Task lifecycle and handoff
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ This reconciliation adds Context System 1.0 and Workflow 2.0 documentation only.
|
|||||||
- TASK-001 is Complete. Captain accepted the snapshot script on 2026-11-04 after running it from the project root. The script writes ZIPs to ignored `docs/snapshots/`; `.worktrees/` is also ignored.
|
- TASK-001 is Complete. Captain accepted the snapshot script on 2026-11-04 after running it from the project root. The script writes ZIPs to ignored `docs/snapshots/`; `.worktrees/` is also ignored.
|
||||||
- No application tests, lint, build, or runtime checks were run as part of this documentation reconciliation.
|
- No application tests, lint, build, or runtime checks were run as part of this documentation reconciliation.
|
||||||
- Captain approved TASK-001's branch/worktree convention. Future-task, general merge, and release conventions remain pending in `DECISIONS.md`.
|
- Captain approved TASK-001's branch/worktree convention. Future-task, general merge, and release conventions remain pending in `DECISIONS.md`.
|
||||||
- No manual-test/testtask adapter was found in tracked repository files.
|
- The initial reconciliation predated the manual-test adapter.
|
||||||
|
|
||||||
## Known limitations of this record
|
## Known limitations of this record
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ Captain accepted TASK-002 on 2026-11-07 and authorized its local integration int
|
|||||||
- Login issues access tokens on first sign-in and after logout, and the login and refresh responses agree on user identity. The Users page now shows loading, empty and request-error states.
|
- Login issues access tokens on first sign-in and after logout, and the login and refresh responses agree on user identity. The Users page now shows loading, empty and request-error states.
|
||||||
- The authentication checks require `login_disabled = false`. Rows left `NULL` by the old nullable migration are denied authentication. Existing invalid or host-absolute folder assignments require admin reassignment to virtual paths. TASK-002 includes no data migration, and local account and assignment data were not inspected.
|
- The authentication checks require `login_disabled = false`. Rows left `NULL` by the old nullable migration are denied authentication. Existing invalid or host-absolute folder assignments require admin reassignment to virtual paths. TASK-002 includes no data migration, and local account and assignment data were not inspected.
|
||||||
- On 2026-11-25, all ten API tests passed with disposable SQLite and media fixtures. Python syntax checks, frontend production build and diff checks passed. Frontend lint could not run because ESLint configuration is missing. Python datetime and Sass deprecation warnings remain.
|
- On 2026-11-25, all ten API tests passed with disposable SQLite and media fixtures. Python syntax checks, frontend production build and diff checks passed. Frontend lint could not run because ESLint configuration is missing. Python datetime and Sass deprecation warnings remain.
|
||||||
- TASK-003 covers ordinary-user browsing, TASK-004 covers download grants and resume, and TASK-005 covers the rest of the admin workflow. Target-Pi deployment and cookie/TLS configuration remain unverified. TASK-007's manual-test adapter awaits separate Captain validation in its own worktree.
|
- TASK-003 covers ordinary-user browsing, TASK-004 covers download grants and resume, and TASK-005 covers the rest of the admin workflow. Target-Pi deployment and cookie/TLS configuration remain unverified. TASK-007 records the manual-test adapter separately.
|
||||||
|
|
||||||
## TASK-003 assigned-folder browsing
|
## TASK-003 assigned-folder browsing
|
||||||
|
|
||||||
@@ -53,3 +53,7 @@ Captain accepted TASK-002 on 2026-11-07 and authorized its local integration int
|
|||||||
- The API returns one directory at a time and verifies the current assignment on each call. The server reports a missing media root or storage I/O errors as unavailable. Detecting a disconnected mount that still looks like a readable local directory requires deployment-level mount checks under TASK-006.
|
- The API returns one directory at a time and verifies the current assignment on each call. The server reports a missing media root or storage I/O errors as unavailable. Detecting a disconnected mount that still looks like a readable local directory requires deployment-level mount checks under TASK-006.
|
||||||
- All 15 API tests, Python syntax, production build and diff checks passed. Frontend lint is still blocked by the absent ESLint configuration. Chromium exercised the isolated snapshot at 1280 × 800 and 375 × 812. The existing header references a missing `/logo.png` asset in both views.
|
- All 15 API tests, Python syntax, production build and diff checks passed. Frontend lint is still blocked by the absent ESLint configuration. Chromium exercised the isolated snapshot at 1280 × 800 and 375 × 812. The existing header references a missing `/logo.png` asset in both views.
|
||||||
- The TASK-007 adapter produced and verified the snapshot. Its readiness HTTP check timed out on concurrent cold frontend and browser startup, so the successful QA run delayed the adapter's Firefox launch. The candidate passed Chromium browser QA and the disposable session cleaned up. The TASK-003 snapshot was absent at integration preflight.
|
- The TASK-007 adapter produced and verified the snapshot. Its readiness HTTP check timed out on concurrent cold frontend and browser startup, so the successful QA run delayed the adapter's Firefox launch. The candidate passed Chromium browser QA and the disposable session cleaned up. The TASK-003 snapshot was absent at integration preflight.
|
||||||
|
|
||||||
|
## TASK-007 isolated manual testing
|
||||||
|
|
||||||
|
Captain accepted the graphical Firefox test with TASK-002 on 2026-11-25. The adapter verified snapshot hashes and HTTP readiness. Shutdown removed the owned snapshot. All six adapter tests passed. The integrated entry point is `./scripts/testtask.sh NNN`. See `scripts/README.md` for prerequisites and the session lifecycle.
|
||||||
|
|||||||
@@ -94,3 +94,10 @@ The 2026-11-04 snapshot references work on `codex` while the existing proposal s
|
|||||||
- Success returns `{root, dirs, files}` for the requested folder's direct children. `root` is the requested virtual path. `dirs` contains directory names. `files` contains `{name, size, ref}` entries with byte sizes and slash-delimited virtual references such as `/folder/video.mp4`. The client URL-encodes the query value once. The server resolves the assigned root and requested directory on each call without following symlinks. Success responses specify `Cache-Control: no-store`.
|
- Success returns `{root, dirs, files}` for the requested folder's direct children. `root` is the requested virtual path. `dirs` contains directory names. `files` contains `{name, size, ref}` entries with byte sizes and slash-delimited virtual references such as `/folder/video.mp4`. The client URL-encodes the query value once. The server resolves the assigned root and requested directory on each call without following symlinks. Success responses specify `Cache-Control: no-store`.
|
||||||
- The endpoint returns 401 for invalid authentication, 403 for a missing or unusable assignment, 400 for invalid virtual path structure, 404 for a folder missing within the assignment, and 503 for unavailable media or storage errors. A readable empty folder returns 200 with empty arrays. Sign-in omits the stored assignment from the session payload.
|
- The endpoint returns 401 for invalid authentication, 403 for a missing or unusable assignment, 400 for invalid virtual path structure, 404 for a folder missing within the assignment, and 503 for unavailable media or storage errors. A readable empty folder returns 200 with empty arrays. Sign-in omits the stored assignment from the session payload.
|
||||||
- TASK-004 may use `ref` as a file reference in its grant request body. The download-grant endpoint must recheck current ownership, containment and file existence. The opaque download URL follows PRD-003.
|
- TASK-004 may use `ref` as a file reference in its grant request body. The download-grant endpoint must recheck current ownership, containment and file existence. The opaque download URL follows PRD-003.
|
||||||
|
|
||||||
|
## WF-005: 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.
|
||||||
|
|||||||
+4
-4
@@ -6,16 +6,16 @@ The implementation came from `.worktrees/TASK-003` on `task/TASK-003-secure-brow
|
|||||||
|
|
||||||
## Repeatable browser check
|
## Repeatable browser check
|
||||||
|
|
||||||
From the primary repository root, launch the exact candidate with the TASK-007 adapter. Both loopback ports 5502 and 5503 must be free.
|
From the primary repository root, launch the exact candidate with the integrated TASK-007 adapter. Both loopback ports 5502 and 5503 must be free.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
PATH="$HOME/.local/bin:$PATH" ./.worktrees/TASK-007/scripts/testtask.sh 003
|
PATH="$HOME/.local/bin:$PATH" ./scripts/testtask.sh 003
|
||||||
```
|
```
|
||||||
|
|
||||||
Choose Firefox and use the disposable accounts and password printed by the launcher at `http://127.0.0.1:5503/`. The adapter starts with `sample.txt` at the assigned root. To exercise nested and empty-folder navigation, add fixtures in a second terminal from the primary root after the adapter reports readiness.
|
Choose Firefox and use the disposable accounts and password printed by the launcher at `http://127.0.0.1:5503/`. The adapter starts with `sample.txt` at the assigned root. To exercise nested and empty-folder navigation, add fixtures in a second terminal from the primary root after the adapter reports readiness.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
task_run=$(cat .worktrees/TASK-007/.test-worktrees/task-003/.testtask-owner) &&
|
task_run=$(cat .test-worktrees/task-003/.testtask-owner) &&
|
||||||
mkdir -p -- "$task_run/media/friends/Series/Season 1" "$task_run/media/friends/Empty" &&
|
mkdir -p -- "$task_run/media/friends/Series/Season 1" "$task_run/media/friends/Empty" &&
|
||||||
printf 'Disposable QA fixture\n' > "$task_run/media/friends/Series/Season 1/episode.txt"
|
printf 'Disposable QA fixture\n' > "$task_run/media/friends/Series/Season 1/episode.txt"
|
||||||
```
|
```
|
||||||
@@ -28,4 +28,4 @@ Stop the owned test session using Ctrl-C in its terminal. The adapter removes th
|
|||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
|
||||||
All 15 API tests, Python syntax, production frontend build and whitespace checks passed again before integration. The build and tests retain existing Sass and datetime deprecation warnings. ESLint configuration is absent. Headless Chromium previously verified the disposable candidate at widths of 1280 and 375 pixels, including keyboard navigation, share outage and retry, a removed folder, unassigned access, and admin folder navigation. The header's existing `/logo.png` asset is missing. The adapter's cold startup can time out while Vite and Firefox start together. Agent QA delayed Firefox startup and verified adapter readiness and cleanup. TASK-007 still awaits separate Captain acceptance.
|
All 15 API tests, Python syntax, production frontend build and whitespace checks passed again before integration. The build and tests retain existing Sass and datetime deprecation warnings. ESLint configuration is absent. Headless Chromium previously verified the disposable candidate at widths of 1280 and 375 pixels, including keyboard navigation, share outage and retry, a removed folder, unassigned access, and admin folder navigation. The header's existing `/logo.png` asset is missing. The adapter's cold startup can time out while Vite and Firefox start together. Agent QA delayed Firefox startup and verified adapter readiness and cleanup. Captain separately accepted TASK-007 after the graphical TASK-002 test on 2026-11-25.
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ The repository contains a folder-sharing web application. `react/` is a React 18
|
|||||||
- `react/package.json` defines `npm run dev`, `npm run build`, `npm run lint`, and `npm run preview`.
|
- `react/package.json` defines `npm run dev`, `npm run build`, `npm run lint`, and `npm run preview`.
|
||||||
- `react/vite.config.js` defines the development API proxy.
|
- `react/vite.config.js` defines the development API proxy.
|
||||||
- `api/config/requirements.txt` lists Python dependencies. Run `python -m unittest discover -s api/tests -v` from the repository root with the API environment to exercise the tracked API regression suite.
|
- `api/config/requirements.txt` lists Python dependencies. Run `python -m unittest discover -s api/tests -v` from the repository root with the API environment to exercise the tracked API regression suite.
|
||||||
- No tracked CI, container, deployment, Git workflow, or manual-test/testtask documentation was found during reconciliation.
|
- No tracked CI, container or deployment configuration was found during initial reconciliation. The installed manual-test adapter is described below.
|
||||||
- Existing UI styling references are `react/src/styles/` and component `*.module.scss` files; no separate style guide is tracked.
|
- Existing UI styling references are `react/src/styles/` and component `*.module.scss` files; no separate style guide is tracked.
|
||||||
|
|
||||||
Local environment files and runtime data under `api/` are ignored by Git. Their contents are not part of this overview.
|
Local environment files and runtime data under `api/` are ignored by Git. Their contents are not part of this overview.
|
||||||
@@ -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)
|
## 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.
|
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
|
||||||
|
|
||||||
|
`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.
|
||||||
|
|||||||
@@ -101,3 +101,19 @@ The scopes below translate Captain's explicit product requirements into implemen
|
|||||||
## Future feature concept (no numbered task yet)
|
## 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.
|
- 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.
|
||||||
|
|||||||
@@ -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/`.
|
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.
|
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
|
||||||
|
```
|
||||||
|
|||||||
@@ -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()
|
||||||
Executable
+5
@@ -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 "$@"
|
||||||
@@ -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)
|
||||||
Reference in New Issue
Block a user