diff --git a/STARTER.md b/STARTER.md index 8fc837b..fc923fd 100644 --- a/STARTER.md +++ b/STARTER.md @@ -27,6 +27,34 @@ The example GitHub identity and `example.invalid` address are placeholders, not repositories or a deployed service. This example body map is a fixture, not a complete Mind installation. +## Initialize a user-owned configuration directory + +If you already have a canonical Mind `repos.yaml`, the offline initializer saves +copying the preview files by hand. Add your Scientist repository identity to that +map first. Use an intended HTTPS Pages address; it need not be deployed yet. +From the framework checkout: + +```bash +python scripts/starter.py /path/to/new-instance --repos /path/to/Mind/repos.yaml \ + --name "My Scientist" --repo my-scientist \ + --pages-url https://example.invalid/my-scientist/ +``` + +This prints the file plan without writing. Repeat with `--apply` to create +`instance.json`, empty `projects.json` and `SETUP.md`. The destination's parent +must exist; the destination itself must not exist, even as an empty directory or +symlink. An existing instance is resumed, never initialized again. No `--force` +is provided. If a filesystem error interrupts writing, inspect the partial +new directory; the command will refuse to overwrite it on retry. + +`SETUP.md` records local validation commands and a fresh-chat handoff. Keep it +private: it contains paths to your framework and canonical map. It is an ordinary +local note, not an installed agent skill. Moving either checkout or configuration +requires updating these paths. No body map is copied, no remote access is checked, +and no task or knowledge records, project source, harness settings or repositories +are created. Mind/Memory template setup and harness integration remain separate. +Use the existing supported templates for those, rather than copying live records. + ## Configure your instance Copy the example configuration to a directory you own, outside the framework diff --git a/scripts/starter.py b/scripts/starter.py new file mode 100644 index 0000000..e3d9310 --- /dev/null +++ b/scripts/starter.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Initialize user-owned Scientist configuration; offline and non-overwriting.""" + +import argparse +import json +import shlex +from pathlib import Path + +import yaml + +from instance_profile import _identity, _pages, _text + + +def plan(destination, repos_path, name, repo, pages_url): + """Validate inputs without writing, and return the complete file plan.""" + destination = Path(destination).absolute() + if destination.exists() or destination.is_symlink(): + raise ValueError("destination already exists; keep its records and resume from SETUP.md") + if not destination.parent.is_dir(): + raise ValueError("destination parent must already be a directory") + repos_path = Path(repos_path).resolve(strict=True) + body = yaml.safe_load(repos_path.read_text(encoding="utf-8")) + repos = body.get("repos") if isinstance(body, dict) else None + if not isinstance(repos, dict): + raise ValueError("canonical identity map must contain repos") + _identity(repo, repos) + profile = {"schema_version": 1, "name": _text(name, "instance name"), + "repo": repo, "pages_url": _pages(pages_url), + "projects": "projects.json", "organs": {}} + framework = Path(__file__).resolve().parents[1] + command = shlex.join(["python3", str(framework / "scripts/organism_board.py"), + "--instance", str(destination / "instance.json"), + "--repos", str(repos_path)]) + setup = f"""# Resume this Scientist setup + +This directory is user-owned configuration, not a full Scientist installation. +Keep it when upgrading the framework. Do not rerun initialization here or replace +these records with the examples. No organ is connected and no project is assumed. +The intended Pages address is configuration only; nothing has been published. + +## Fresh-chat handoff + +Open a coding-assistant session in this directory and ask: + +> Read SETUP.md and instance.json, then inspect projects.json and the canonical +> repository map named below. Validate offline before suggesting changes. Help +> connect one existing project using the framework's PROJECTS.md and STARTER.md. +> Ask for missing project identity, purpose and visibility. Preserve project-owned +> source; do not assume an assistant exists. Propose changes before applying them. +> Do not provision repositories, install a harness, publish or run science. + +The commands below retain local paths, so keep this file private. If you move the +configuration, framework or Mind checkout, update the command paths before use. +The canonical map is referenced, never copied or rewritten by initialization. + +## Validate and preview + +Ensure Python and PyYAML are available and set PYAUTO_BRAIN to your compatible +Brain checkout (shared presentation). The initializer itself does not need Brain. +Run validation, then render to a new scratch file of your choice: + +```sh +{command} --check-instance +{command} --html +``` + +The second command prints HTML to stdout; save it outside this directory and open +it locally. An empty instance reads no organ feeds. Configuring an organ later +explicitly opts into reading its public feed. + +## Still to set up + +- A working Mind from the supported fresh-slate template, with your own body map + and empty task records. This command assumes an existing canonical map only. +- Optional Memory from its supported template when knowledge needs a home. +- One supported local agent harness and its workflow integration; no global agent + settings or skills were installed here. +- Existing-project connection, optional organ activation and independent hosting. + +Consult the framework STARTER.md for current boundaries. Local instructions are +not evidence that a harness or organ has been installed or tested. +""" + return {"instance.json": json.dumps(profile, indent=2, ensure_ascii=False) + "\n", + "projects.json": json.dumps({"schema_version": 1, "resources": {}, "projects": {}}, indent=2) + "\n", + "SETUP.md": setup} + + +def initialize(destination, files): + """Exclusively create a new directory; never merge into existing state.""" + destination = Path(destination) + destination.mkdir() # Atomic refusal if another invocation got there first. + for name, content in files.items(): + with (destination / name).open("x", encoding="utf-8") as stream: + stream.write(content) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("destination", type=Path) + parser.add_argument("--repos", type=Path, required=True, help="existing canonical Mind repos.yaml") + parser.add_argument("--name", required=True) + parser.add_argument("--repo", required=True, help="stable ID in the canonical map") + parser.add_argument("--pages-url", required=True, help="intended HTTPS board directory") + parser.add_argument("--apply", action="store_true", help="create the new directory (default: preview only)") + args = parser.parse_args(argv) + try: + files = plan(args.destination, args.repos, args.name, args.repo, args.pages_url) + if args.apply: + initialize(args.destination, files) + except (OSError, ValueError, yaml.YAMLError) as exc: + parser.exit(2, f"starter: {exc}\n") + print("Created" if args.apply else "Preview only; pass --apply to create", args.destination) + for name in files: + print(f" {name}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_starter.py b/tests/test_starter.py new file mode 100644 index 0000000..8492b50 --- /dev/null +++ b/tests/test_starter.py @@ -0,0 +1,87 @@ +"""Initialization preserves user records and uses the existing render contract.""" +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +import starter +import instance_profile +import organism_board + + +@pytest.fixture +def inputs(tmp_path): + repos = tmp_path / 'repos.yaml' + repos.write_text('repos:\n researcher:\n github: ExampleResearch/IndependentScience\n') + return tmp_path / 'my scientist', repos + + +def args(inputs): + destination, repos = inputs + return [str(destination), '--repos', str(repos), '--name', 'Independent Science', + '--repo', 'researcher', '--pages-url', 'https://example.invalid/science/'] + + +def test_preview_then_apply_and_repeat_preserves_records(inputs): + destination, repos = inputs + original = repos.read_bytes() + starter.main(args(inputs)) + assert not destination.exists() + starter.main(args(inputs) + ['--apply']) + assert set(p.name for p in destination.iterdir()) == {'instance.json', 'projects.json', 'SETUP.md'} + profile = json.loads((destination / 'instance.json').read_text()) + assert profile['name'] == 'Independent Science' + assert profile['organs'] == {} + (destination / 'projects.json').write_text('user records') + before = {p.name: p.read_bytes() for p in destination.iterdir()} + with pytest.raises(SystemExit) as exc: + starter.main(args(inputs) + ['--apply']) + assert exc.value.code == 2 + assert before == {p.name: p.read_bytes() for p in destination.iterdir()} + assert repos.read_bytes() == original + + +@pytest.mark.parametrize('key,value', [('--repo', 'missing'), ('--pages-url', 'http://bad'), ('--name', '\n')]) +def test_invalid_input_leaves_no_directory(inputs, key, value): + argv = args(inputs) + argv[argv.index(key) + 1] = value + with pytest.raises(SystemExit): + starter.main(argv + ['--apply']) + assert not inputs[0].exists() + + +def test_symlink_destination_refused(inputs): + destination, repos = inputs + destination.symlink_to(destination.parent / 'absent', target_is_directory=True) + with pytest.raises(SystemExit): + starter.main(args(inputs) + ['--apply']) + assert destination.is_symlink() + assert not destination.exists() + + +def test_creation_race_does_not_overwrite(inputs): + destination, repos = inputs + files = starter.plan(destination, repos, 'Independent', 'researcher', 'https://example.invalid') + destination.mkdir() + record = destination / 'instance.json' + record.write_text('existing') + with pytest.raises(FileExistsError): + starter.initialize(destination, files) + assert record.read_text() == 'existing' + + +def test_resume_commands_and_profile_contract(inputs): + destination, repos = inputs + starter.main(args(inputs) + ['--apply']) + # Real loader and renderer consume the generated files, without feed requests. + theme = organism_board.theme() + profile, projects = instance_profile.load(destination / 'instance.json', repos, theme) + assert profile['boards'] == [] + assert projects == destination / 'projects.json' + assert json.loads(projects.read_text())['projects'] == {} + setup = (destination / 'SETUP.md').read_text() + assert str(repos) in setup + assert '--check-instance' in setup + assert 'not a full Scientist installation' in setup