diff --git a/distribution/testtask/testtask.sh b/distribution/testtask/testtask.sh new file mode 100755 index 0000000..81216b2 --- /dev/null +++ b/distribution/testtask/testtask.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +exec python3 "$script_dir/testtask_runner.py" "$@" diff --git a/distribution/testtask/testtask_runner.py b/distribution/testtask/testtask_runner.py new file mode 100755 index 0000000..93c581e --- /dev/null +++ b/distribution/testtask/testtask_runner.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Run a repository-configured test command in an existing branch worktree.""" +import json +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +HEADING = re.compile(r"^## ([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)\s+[—-]", re.M) +LABEL = re.compile(r"(?:Task )?[Bb]ranch(?:/worktree)?:\s*`([^`]+)`") + + +def fail(message, code=2): + print(f"testtask: {message}", file=sys.stderr) + return code + + +def git(*args): + return subprocess.check_output(["git", "-C", str(ROOT), *args], text=True).strip() + + +def tasks(): + path = ROOT / "docs/TASKS.md" + if not path.is_file(): + return {} + content = path.read_text(encoding="utf-8") + headings = list(HEADING.finditer(content)) + result = {} + for index, match in enumerate(headings): + end = headings[index + 1].start() if index + 1 < len(headings) else len(content) + result.setdefault(match.group(1), []).append(content[match.end():end]) + return result + + +def task_branches(task_id, section, branches): + slug = task_id.lower() + found = {branch for branch in branches if re.search(rf"(^|[-/]){re.escape(slug)}($|[-/])", branch.lower())} + found.update(branch for branch in LABEL.findall(section) if branch in branches) + return found + + +def resolve(identifier): + branches = set(git("for-each-ref", "--format=%(refname:short)", "refs/heads").splitlines()) + records = tasks() + if identifier in records: + if len(records[identifier]) != 1: + raise ValueError(f"ambiguous task ID {identifier}: multiple task records") + matches = task_branches(identifier, records[identifier][0], branches) + if not matches: + raise ValueError(f"task {identifier} has no recorded local branch") + if len(matches) != 1: + raise ValueError(f"ambiguous task {identifier}: branches {', '.join(sorted(matches))}") + branch = next(iter(matches)) + task_id = identifier + elif identifier in branches: + branch = identifier + matches = [task_id for task_id, sections in records.items() + if any(branch in task_branches(task_id, section, branches) for section in sections)] + if len(matches) > 1 or (matches and len(records[matches[0]]) > 1): + raise ValueError(f"ambiguous branch {branch}: task records {', '.join(sorted(matches))}") + task_id = matches[0] if matches else None + else: + raise ValueError(f"unknown task ID or branch: {identifier}") + paths = [] + for block in git("worktree", "list", "--porcelain").split("\n\n"): + lines = block.splitlines() + if f"branch refs/heads/{branch}" in lines: + path = next((Path(line[9:]) for line in lines if line.startswith("worktree ")), None) + if path and path.is_dir(): + paths.append(path) + if not paths: + raise ValueError(f"branch {branch} has no existing worktree") + if len(paths) != 1: + raise ValueError(f"ambiguous branch {branch}: multiple worktrees") + return task_id, branch, paths[0] + + +def configured_command(worktree): + path = worktree / ".bortstack/testtask.json" + if not path.is_file(): + raise FileNotFoundError(f"testing unavailable: missing {path}") + try: + config = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise ValueError(f"invalid test configuration {path}: {exc}") from exc + if not isinstance(config, dict) or set(config) != {"command"}: + raise ValueError(f"invalid test configuration {path}: expected only a command field") + command = config["command"] + if not isinstance(command, list) or not command or any(not isinstance(arg, str) or not arg for arg in command): + raise ValueError(f"invalid test configuration {path}: command must be a nonempty string array") + return command + + +def main(argv): + if argv == ["--help"]: + print("Usage: scripts/testtask.sh ") + print("Runs .bortstack/testtask.json command from the resolved branch worktree.") + return 0 + if len(argv) != 1 or not argv[0] or argv[0].startswith("-"): + return fail("Usage: scripts/testtask.sh ") + try: + task_id, branch, worktree = resolve(argv[0]) + command = configured_command(worktree) + except FileNotFoundError as exc: + return fail(str(exc), 3) + except (ValueError, subprocess.CalledProcessError) as exc: + return fail(str(exc)) + print(f"task: {task_id or '(none)'}\nbranch: {branch}\nworktree: {worktree}\ntests: {command!r}", flush=True) + try: + result = subprocess.run(command, cwd=worktree, check=False) + except OSError as exc: + return fail(f"could not start configured tests: {exc}", 3) + print(f"testtask: tests exited {result.returncode}", file=sys.stderr) + return result.returncode + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index e6fcbd5..422e0bd 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -1,5 +1,7 @@ # Current state +FORGE-F014's isolated candidate provides a portable testtask runner and existing-project installer. A target worktree must explicitly configure its test command. A disposable PitchInvader-shaped fixture is the validation target; PitchInvader itself has not been tested or modified. Human acceptance and Windows validation remain pending. + FORGE-F001, FORGE-F002, FORGE-F006, and FORGE-F007 were human accepted and are present on `codex`. F003 and F004 candidates are integrated locally with external validation and acceptance pending. The Captain-authorised F004 lifecycle follow-up from `codex-forge-f004-lifecycle` was integrated into `codex` at `727a64e` after combined Forge checks; it extends F002's accepted context contract without reopening F002. FORGE-F011 is a planned visual design quality follow-up to F003; image-to-editable-Penpot reconstruction remains unproven and requires investigation. F006 provides an independent Flask/React template package and generator, with SQLite, PostgreSQL, MySQL, and MariaDB migrations verified in disposable Docker containers. Windows generation remains untested. The original bootstrap repository remains available; no external retirement was performed. Explicit business/personal profile configuration is implemented. `bortstack-context`, `bortstack-contributor`, and `bortstack-design` packages are present; one skill directory remains reserved. The repository `testtask` entry point is provisioned but blocked because Forge has no application runtime or manual-test hook. No cross-template generator or active legacy-skill migration has been implemented. Captain reports successful external validation of local Penpot 2.18 Docker and integrated MCP, but this session has no Penpot connector/browser. JJ's hands-on and Windows workflow has not been tested. Decisions FORGE-001 through FORGE-011 remain accepted. FORGE-008 authorises direct `codex` work generally; Captain explicitly requested isolation for the F004 lifecycle follow-up. FORGE-F012's editor-connection preflight and recovery guidance were fast-forward integrated into local `codex` at `075e2f3` after Captain authorisation and combined checks. Its isolated worktree `/tmp/bortstack-forge-f012` remains preserved; human acceptance is pending. The Captain explicitly requested isolation for F012; FORGE-008 remains the general direct-`codex` policy. No live Penpot behavior is claimed by this documentation change. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index f749342..107e37d 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,5 +1,7 @@ # Handoff +FORGE-F014 candidate: isolated branch `codex-forge-f014` at `/tmp/bortstack-forge-f014`, based on `860d6d4`. Portable distribution is under `distribution/testtask`; `scripts/install-testtask.py` installs it without replacing existing files. Each target branch worktree needs `.bortstack/testtask.json` with an explicit command array. Review the candidate, test installation in an application-owned disposable checkout, and obtain Captain acceptance before marking the task complete. No PitchInvader files were changed. Windows and real PitchInvader validation remain open. + Current work: Captain authorised and completed integration of the contributor lifecycle follow-up from `codex-forge-f004-lifecycle` (`c2d4561`) into `codex` at merge commit `727a64e`. The source worktree is `/tmp/bortstack-forge-f004-lifecycle`, baseline `934e62c`; the target had advanced to `900bd6c` with FORGE-F011 planning. F002 remains Complete. F004 is integrated locally but still pending JJ's external validation and human acceptance. The original F004 worktree remains preserved. Implementation: `bortstack-context/references/task-lifecycle.md` is the canonical state, transition, evidence, identifier and integration contract. Contributor starts finalisation from natural completion language and owns ordinary-language review handoff. Captain approval, combined checks and human closure are separate gates. `docs/validation/contributor-lifecycle.md` covers acceptance scenarios A-I. FORGE-F011 remains Planned with its design-quality investigation and outstanding decisions intact. No external project, provider setting, production infrastructure or installed skill was modified. diff --git a/docs/TASKS.md b/docs/TASKS.md index d8bb863..bc4650c 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -125,6 +125,10 @@ Scope: Resolve an existing task ID, including legacy IDs, or an exact local bran Implementation and validation (2026-11-18): `testtask.sh` delegates read-only lookup to `resolve_testtask.py`; task headings and local branch/worktree inventory are checked before the unchanged blocked-runtime outcome. Tests cover both formats, historical IDs, unknown and malformed input, ambiguous task/branch references, and a missing worktree. On the isolated candidate and merged `codex`, 21 tests passed, all three skills validated, installer dry-run passed, and task ID audit passed; diff check passed on the candidate. A live `testtask.sh FORGE-F013` resolved the current task and exited 3 with the expected blocked-runtime message. Windows and a manual-test runtime remain unverified. Human acceptance is pending; preserve the task worktree. +## FORGE-F014 — Reusable testtask for Existing Projects +Status: Implementation Complete; human acceptance pending. Owner: Codex. Branch/worktree: `codex-forge-f014` at `/tmp/bortstack-forge-f014`; baseline `860d6d4`. This maintenance task extends F013 resolution and F001 distribution without changing their accepted scope. Add a portable runner and conflict-safe existing-repository installer, leaving Forge's own blocked runtime and `bortstack-context` task ownership intact. Validate with a disposable PitchInvader-shaped repository, including its local `codex` worktree and configured command. No PitchInvader repository is modified. Linux tests and diff check are required; Windows and a real PitchInvader run remain pending. Human acceptance is required before Complete. + ## Scheduling + Start with F002. F003 and F004 can follow F002 independently; F006 can proceed after F001. F007 follows F002. F005 follows F002, F006, and F007. F008 follows F006. F010 follows F002 and F004. F011 builds on F003 without closing its separate acceptance checks. F009 remains deferred until after F005. Dependency readiness does not authorise implementation. diff --git a/docs/specifications/skill-distribution.md b/docs/specifications/skill-distribution.md index 81e7c59..69f762c 100644 --- a/docs/specifications/skill-distribution.md +++ b/docs/specifications/skill-distribution.md @@ -7,3 +7,13 @@ Linux: `python3 scripts/install-skills.py --list`, `--dry-run`, `--install NAME` Update procedure: identify and record the target Forge commit, validate and test that revision, inspect the installed package, move its destination to a user-controlled backup, install the selected new package, restart Codex if needed, test activation and compatibility, then delete the backup only after acceptance. On failure, remove the new package and restore the backup. The installer itself never removes old packages. Migration plan: inventory actual installed `roborto-*` directories and internal references on each machine; map `roborto-project-context` to `bortstack-context`, `roborto-new-project` to `bortstack-new`, and `roborto-contributor` to `bortstack-contributor`. `bortstack-design` is new. Preserve context, task, handoff, snapshot, contributor permission, Captain/Commander, and Docker manual-testing behavior. Update internal cross-skill references only after matching implementations exist. Test legacy/new interaction in isolation before exposing both as active, then test Linux installation and JJ's Windows installation separately. Keep old installations until consumer references and user workflows pass; roll back by restoring backups and references. Retire old names only by separate accepted task. FORGE-F001 performs none of this migration. + +## Existing-project testtask entry point + +From a validated Forge checkout, run `python3 scripts/install-testtask.py /path/to/existing/repository --dry-run`, then omit `--dry-run` to install. This copies `scripts/testtask.sh` and `scripts/testtask_runner.py` into the existing repository; it does not run a generator or change application code. Commit these files in the application repository only under that project's authority. Repeatable updates use `--update` after inspecting the Forge revision and target diff. The installer refuses an existing script, an altered prior installation, or a missing prior installation for `--update`. It records file hashes in `scripts/.forge-testtask-install.json`. Keep a backup and restore it if an update fails application validation. + +If `scripts/testtask.sh` already exists, inspect its behavior and test commands. Retain it if it works. To adopt the Forge runner, agree on a reconciliation that preserves its custom commands in `.bortstack/testtask.json`, save the old entry point outside the install destinations, then install and validate in a disposable checkout before applying to the real repository. The installer never overwrites the old script automatically. + +Each branch worktree must provide `.bortstack/testtask.json` with an explicit argument array, for example `{"command": ["make", "test"]}`. The command runs from that worktree root with its existing environment and exit code. Choose the command from the application's documented test workflow; configure required services, dependencies, and environment there. The runner never infers a test command from framework files. It reports unavailable testing when configuration is absent. Task IDs use `docs/TASKS.md` headings and branch references; exact local branch names work without task records. An existing worktree is required, and the runner never creates one or changes branches. This command executes automated tests; project-specific interactive/manual runtime preparation remains separately documented. + +Linux requires Git, Python 3, and a POSIX shell. On Windows use Git Bash or WSL for `scripts/testtask.sh`, with Python 3 on that shell's PATH; PowerShell alone does not execute the shell entry point. Windows behavior remains to be validated on an actual Windows machine. diff --git a/scripts/install-testtask.py b/scripts/install-testtask.py new file mode 100755 index 0000000..23e3d6f --- /dev/null +++ b/scripts/install-testtask.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Safely install Forge's portable testtask entry point in an existing repository.""" +import argparse +import hashlib +import json +import shutil +import subprocess +import sys +from pathlib import Path + +SOURCE = Path(__file__).resolve().parents[1] / "distribution/testtask" +FILES = ("testtask.sh", "testtask_runner.py") + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("repository", type=Path) + parser.add_argument("--update", action="store_true", help="update an unmodified prior Forge installation") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + root = args.repository.resolve() + probe = subprocess.run(["git", "-C", str(root), "rev-parse", "--show-toplevel"], capture_output=True, text=True) + if not root.is_dir() or probe.returncode or Path(probe.stdout.strip()).resolve() != root: + parser.error("repository must be an existing Git checkout") + target = root / "scripts" + if target.is_symlink(): + parser.error("scripts directory is a symlink; reconcile manually") + manifest = target / ".forge-testtask-install.json" + previous = None + if manifest.exists(): + try: + previous = json.loads(manifest.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + parser.error("invalid installation manifest; reconcile manually") + if args.update and previous is None: + parser.error("no prior Forge installation; reconcile existing scripts manually") + if not args.update and previous is not None: + parser.error("Forge testtask already installed; use --update") + for name in FILES: + dest = target / name + if args.update: + if dest.is_symlink() or not dest.is_file() or previous.get(name) != digest(dest): + parser.error(f"modified or missing installed file: {dest}; reconcile manually") + elif dest.exists() or dest.is_symlink(): + parser.error(f"installation conflict: {dest}; reconcile manually") + if not args.update and manifest.exists(): + parser.error(f"installation conflict: {manifest}") + print(f"{'Update' if args.update else 'Install'} testtask in {root}") + for name in FILES: + print(f" {target / name}") + if args.dry_run: + return 0 + target.mkdir(parents=True, exist_ok=True) + for name in FILES: + shutil.copy2(SOURCE / name, target / name) + manifest.write_text(json.dumps({name: digest(target / name) for name in FILES}, indent=2) + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_portable_testtask.py b/tests/test_portable_testtask.py new file mode 100644 index 0000000..f9f8e03 --- /dev/null +++ b/tests/test_portable_testtask.py @@ -0,0 +1,77 @@ +import json +import subprocess +import tempfile +import unittest +from pathlib import Path + +SOURCE = Path(__file__).resolve().parents[1] +INSTALLER = SOURCE / "scripts/install-testtask.py" + + +def run(*args, cwd=None): + return subprocess.run(args, cwd=cwd, capture_output=True, text=True) + + +class PortableTesttaskTests(unittest.TestCase): + def test_existing_repository(self): + with tempfile.TemporaryDirectory() as temp: + repo = Path(temp) / "pitchinvader-fixture" + repo.mkdir() + self.assertEqual(run("git", "init", "-q", str(repo)).returncode, 0) + (repo / "docs").mkdir() + (repo / "docs/TASKS.md").write_text("## PI-001 — Fixture\nBranch/worktree: `feature-pi-001`\n") + (repo / "scripts").mkdir() + (repo / "scripts/run-tests.py").write_text("from pathlib import Path\nimport sys\nPath('test-ran').write_text(Path.cwd().name)\nsys.exit(int(Path('test-exit').read_text()) if Path('test-exit').exists() else 0)\n") + run("git", "add", ".", cwd=repo) + run("git", "-c", "user.name=Test", "-c", "user.email=test@example.org", "commit", "-qm", "base", cwd=repo) + self.assertEqual(run("git", "branch", "codex", cwd=repo).returncode, 0) + tree = Path(temp) / "pitchinvader-codex" + self.assertEqual(run("git", "worktree", "add", "-q", str(tree), "codex", cwd=repo).returncode, 0) + config = tree / ".bortstack/testtask.json" + config.parent.mkdir() + config.write_text(json.dumps({"command": ["python3", "scripts/run-tests.py"]})) + install = run("python3", str(INSTALLER), str(repo)) + self.assertEqual(install.returncode, 0, install.stderr) + script = str(repo / "scripts/testtask.sh") + result = run(script, "codex") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("branch: codex", result.stdout) + self.assertIn(str(tree), result.stdout) + self.assertEqual((tree / "test-ran").read_text(), tree.name) + (tree / "test-exit").write_text("7") + self.assertEqual(run("sh", script, "codex").returncode, 7) + self.assertEqual(run("sh", script, "unknown").returncode, 2) + self.assertEqual(run("sh", script, "PI-001").returncode, 2) + config.write_text("not json") + self.assertIn("invalid test configuration", run("sh", script, "codex").stderr) + config.unlink() + self.assertEqual(run("sh", script, "codex").returncode, 3) + self.assertEqual(run("python3", str(INSTALLER), str(repo)).returncode, 2) + self.assertEqual(run("python3", str(INSTALLER), str(repo), "--update").returncode, 0) + (repo / "scripts/testtask.sh").write_text("custom\n") + self.assertEqual(run("python3", str(INSTALLER), str(repo), "--update").returncode, 2) + + def test_task_id_and_missing_worktree(self): + with tempfile.TemporaryDirectory() as temp: + repo = Path(temp) / "repo" + repo.mkdir() + run("git", "init", "-q", str(repo)) + (repo / "docs").mkdir() + (repo / "docs/TASKS.md").write_text("## PI-001 — Fixture\nBranch/worktree: `feature-pi-001`\n") + run("git", "add", ".", cwd=repo) + run("git", "-c", "user.name=Test", "-c", "user.email=test@example.org", "commit", "-qm", "base", cwd=repo) + run("git", "branch", "feature-pi-001", cwd=repo) + run("python3", str(INSTALLER), str(repo)) + script = str(repo / "scripts/testtask.sh") + self.assertIn("no existing worktree", run("sh", script, "PI-001").stderr) + tree = Path(temp) / "task-tree" + run("git", "worktree", "add", "-q", str(tree), "feature-pi-001", cwd=repo) + (tree / ".bortstack").mkdir() + (tree / ".bortstack/testtask.json").write_text(json.dumps({"command": ["true"]})) + result = run("sh", script, "PI-001") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("task: PI-001", result.stdout) + + +if __name__ == "__main__": + unittest.main()