diff --git a/.github/workflows/offline-checks.yml b/.github/workflows/offline-checks.yml index 1068e8f..fcd77f3 100644 --- a/.github/workflows/offline-checks.yml +++ b/.github/workflows/offline-checks.yml @@ -22,6 +22,7 @@ jobs: run: | python3 -m unittest discover -s tests -p 'test_selected_catalog.py' python3 -m unittest discover -s tests -p 'test_publisher.py' + python3 -m unittest discover -s tests -p 'test_vault*.py' - name: Test CPU transcription admission run: python3 -m unittest discover -s tests -p 'test_whisper_cpu.py' - name: Check the outcome benchmark grader diff --git a/README.md b/README.md index 3662edc..1421f66 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ cd Stack-Plus [Rehearse in a disposable home](docs/ONBOARDING.md#try-the-installation-and-its-rollback) first. The rehearsal profile should list exactly one skill, `01`, and gives you a rollback command. When you're ready, [install into your own setup](docs/ONBOARDING.md#use-it-in-your-project). If you have existing skills, review the replacement and backup guidance before changing your selection. +During first-time setup you can skip knowledge storage, choose an existing Obsidian folder, or create a vault with starter notes. To set up the folder separately, run `./stack+ vault` from this checkout. [Set up a knowledge base](docs/ONBOARDING.md#optional-obsidian-knowledge-base) + In a project chat, select **`$01` in Codex** or **`@01` in OpenCode** and describe the result you want. Follow-ups retain the selection in that chat. Say **turn 01 off** to end it. [OpenCode setup and compatibility](docs/OPENCODE.md) · [Restore a prior setup](docs/RESTORE.md) diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md index 1c74daf..f121b3e 100644 --- a/docs/CLAUDE.md +++ b/docs/CLAUDE.md @@ -105,3 +105,5 @@ Host contracts were checked against Anthropic's official [skill documentation](https://code.claude.com/docs/en/skills) and [instruction-file documentation](https://code.claude.com/docs/en/memory), including the [configuration-directory override](https://code.claude.com/docs/en/settings). + +To prepare a knowledge folder for this host, run `./stack+ vault` in the Stack+ checkout. Choose an existing Obsidian folder, create one with starter notes, or skip. The host keeps its own permission settings. [Knowledge base setup](ONBOARDING.md#optional-obsidian-knowledge-base) diff --git a/docs/EVERYDAY_SETUP.md b/docs/EVERYDAY_SETUP.md index 5e13357..6e3af87 100644 --- a/docs/EVERYDAY_SETUP.md +++ b/docs/EVERYDAY_SETUP.md @@ -136,7 +136,9 @@ reacquirable compilers/build caches can use non-synced temporary storage. ## Canonical knowledge vault -Choose one existing, explicitly authorized vault. `--vault /absolute/vault` only +Run `./stack+ vault` to use an existing folder or create a starter vault. [First-time setup](ONBOARDING.md#optional-obsidian-knowledge-base) + +Choose one explicitly authorized vault. `--vault /absolute/vault` only writes its location into owned guidance; it does not import notes or initialize an arbitrary directory. `templates/vault` is a clean starting structure with Home, Library, Templates, Archive, a Base and Canvas. Copy only to a new destination or diff --git a/docs/ONBOARDING.md b/docs/ONBOARDING.md index 719f2bd..c7ccd19 100644 --- a/docs/ONBOARDING.md +++ b/docs/ONBOARDING.md @@ -9,7 +9,7 @@ Run these commands from the Stack+ checkout in Bash or zsh, using Git, Python 3. ```sh preview=$(mktemp -d) preview=$(cd "$preview" && pwd -P) -python3 native_setup.py install --only 01 \ +python3 native_setup.py install --only 01 --skip-vault \ --home "$preview/home" --codex-home "$preview/home/.codex" --state "$preview/state" python3 -m json.tool "$preview/state/native-profile.json" "$preview/state/rollback.sh" @@ -36,3 +36,11 @@ mkdir -p "$library" For OpenCode, add `--host opencode` to the find command and its subsequent readback. Reopen a result with the same project, host and bundle, replacing the query and `--json` with `--method --read MATCH_ID`. The shared skill root still exposes only 01. Specialist dependencies belong in the project that needs them. For an existing collection, inspect your shared and personal skill roots and retain a backup before replacing anything. Replacing a managed selection can retire omitted entries. Rehearse all additions you intend to retain together. The native installer accepts a custom `--codex-home` or the current `CODEX_HOME`. Keep project-specific skills and connectors in their owning project. [Selection and staging](stackplus-selections.md) · [Existing native profiles and optional bootstrap](REGISTRY.md) · [Recovery](RESTORE.md) + +## Optional Obsidian knowledge base + +A vault is a local folder of Markdown files. During first-time interactive native installation, choose **Skip**, **Use a folder I already have**, or **Create a vault with starter notes**. When installing for someone in chat, offer those same choices and ask for a folder only if they want one. Pass `--skip-vault`, `--vault "/path/to/Existing Vault"`, or `--create-vault "/path/to/New Vault"` with their native install command. An unattended install can omit all three. + +To prepare the folder separately, run `./stack+ vault` in this checkout. You can also run `./stack+ vault --existing "/path/to/Existing Vault"` or `./stack+ vault --create "/path/to/New Vault"`. Choose a new name inside an existing parent folder. Existing vaults keep their own layout. New vaults include a home note, library, note template, index and canvas. For private knowledge, choose a location outside your public checkouts. + +In Obsidian's vault switcher, choose **Open folder as vault** and select the folder shown by setup. In a new vault, open **Home**, follow **Library**, then copy **Templates/Knowledge Note.md** into **Library** to record a decision and its source. The notes also open in a Markdown editor. The standalone folder command is local. During native installation the selected path appears in the standard knowledge guidance. Host permissions govern access, and configuring the private writer is a separate opt-in. [Obsidian’s vault guide](https://help.obsidian.md/vault) · [Private knowledge writer](../integrations/knowledge-continuity/README.md) diff --git a/docs/OPENCODE.md b/docs/OPENCODE.md index 9d5adc6..f21c7ad 100644 --- a/docs/OPENCODE.md +++ b/docs/OPENCODE.md @@ -210,3 +210,5 @@ Sources: [OpenCode agents](https://opencode.ai/docs/agents/), The optional `--rea` shared method appears as `rea-software-analysis`. Its [private pinned CLI](REA.md) needs no OpenCode provider or global MCP entry. + +To prepare a knowledge folder for this host, run `./stack+ vault` in the Stack+ checkout. Choose an existing Obsidian folder, create one with starter notes, or skip. The host keeps its own permission settings. [Knowledge base setup](ONBOARDING.md#optional-obsidian-knowledge-base) diff --git a/docs/stackplus-selections.md b/docs/stackplus-selections.md index 0e94501..10f0c3c 100644 --- a/docs/stackplus-selections.md +++ b/docs/stackplus-selections.md @@ -18,9 +18,9 @@ python3 xfactor.py report research-runs/smoke The stage destination must be new. The Stack+ staging command uses Python 3.11 or newer. The staged X Factor workspace requires Python 3.10 or newer on macOS or Linux. The smoke test uses the shipped checker and should report `verified`. -To use an existing model CLI, run `./research "Your question" --model YOUR_COMMAND` inside the staged package. For a first checked run, the [model connection guide](https://github.com/nazeeh111/X-Factor/blob/f7a00959e1fcc94356864bf11250bd22b38cf26e/docs/connect.md) includes a working tool and verifier. +To use an existing model CLI, run `./research "Your question" --model YOUR_COMMAND` inside the staged package. For a first checked run, the [model connection guide](https://github.com/nazeeh111/X-Factor/blob/61e7e5827f6ccdf90da204025fbee0dea071d1b2/docs/connect.md) includes a working tool and verifier. -To install the staged engine in an existing research project, run its `research --setup --project /path/to/project`. Setup remembers when you want explanations and when you want to be consulted. It also offers three optional Stack+ skills for that project. Choose any, or skip to research. Use `--skills-dir DIR` when your host reads a different project skill directory. A host can run the staged skill on the original objective using the sibling engine. With Stack+ already installed, run `stack+ find --bundle x-factor --json "persistent X Factor investigation"` from the staged project. Use `stack+ find --bundle x-factor --instructions --read MATCH_ID` to reopen the skill. Keep the skill with its sibling engine and keep the resulting research runs with that project. +To install the staged engine in an existing research project, run its `research --setup --project /path/to/project`. Setup remembers when you want explanations and when you want to be consulted. You can connect an existing Obsidian vault, create a new one, or skip it. For a shared notebook with Stack+ starter notes, create it once with `./stack+ vault` in the Stack+ checkout, then select that folder in X Factor. After research, `research --save-note RUN` saves the checked result. Setup also offers three optional Stack+ skills for that project. Choose any, or skip to research. Use `--skills-dir DIR` when your host reads a different project skill directory. A host can run the staged skill on the original objective using the sibling engine. With Stack+ already installed, run `stack+ find --bundle x-factor --json "persistent X Factor investigation"` from the staged project. Use `stack+ find --bundle x-factor --instructions --read MATCH_ID` to reopen the skill. Keep the skill with its sibling engine and keep the resulting research runs with that project. If your installed `stack+ find --help` lists `--root`, you can open the staged skill from a different project while honoring that project's skill rules: diff --git a/lib/vault_setup.py b/lib/vault_setup.py new file mode 100644 index 0000000..4820c0f --- /dev/null +++ b/lib/vault_setup.py @@ -0,0 +1,94 @@ +"""Set up a local folder for Obsidian using the shipped Stack+ notes.""" + +import argparse +import json +from pathlib import Path +import shutil +import sys +from tempfile import TemporaryDirectory + +TEMPLATE = Path(__file__).resolve().parents[1] / "templates" / "vault" + + +def choose(existing=None, create=None, *, interactive=False): + """Return a selected folder or None. Only an explicit create choice writes files.""" + if existing is None and create is None and interactive: + print("Would you like an Obsidian knowledge base?\n" + " 1. Skip\n 2. Use a folder I already have\n 3. Create a vault with starter notes", + file=sys.stderr) + try: + while True: + print("Choose 1–3 [Skip]: ", end="", file=sys.stderr, flush=True) + answer = input().strip().casefold() + if answer in ("", "1", "skip"): + return None + if answer in ("2", "existing", "3", "create", "new"): + break + print("Folder path (Enter to skip): ", end="", file=sys.stderr, flush=True) + path = input().strip() + if not path: + return None + if answer in ("2", "existing"): + existing = path + else: + create = path + except EOFError: + return None + + selected = create if create is not None else existing + if selected is None: + return None + if not str(selected).strip() or not str(selected).isprintable(): + raise ValueError("Choose a folder with a printable path.") + path = Path(selected).expanduser() + if create is not None: + if path.exists() or path.is_symlink(): + raise ValueError(f"{path} already exists. Choose the existing-folder option or a new folder name.") + parent = path.parent.resolve(strict=True) + path = parent / path.name + with TemporaryDirectory(prefix=".stack-vault-", dir=parent) as staging: + starter = Path(staging) / "notes" + shutil.copytree(TEMPLATE, starter) + starter.chmod(0o700) + # Reserve the new name before publishing the complete starter tree. + # rename refuses if someone has added files to our empty reservation. + path.mkdir(mode=0o700) + try: + starter.rename(path) + except OSError: + if path.is_dir() and not path.is_symlink(): + try: + path.rmdir() + except OSError: + pass # Another user has already added files. + raise + print(f"Created {path}. In Obsidian, choose “Open folder as vault” and select this folder.\n" + "Open Home, then use Templates/Knowledge Note.md for your first source-backed note.", file=sys.stderr) + else: + path = path.resolve(strict=True) + if not path.is_dir(): + raise ValueError(f"Choose a folder. {path} is a file.") + print(f"Selected {path}. To open it in Obsidian, choose “Open folder as vault”.", file=sys.stderr) + return path + + +def arguments(parser): + group = parser.add_mutually_exclusive_group() + group.add_argument("--existing", metavar="FOLDER", help="Use an existing folder with its current notes") + group.add_argument("--create", metavar="FOLDER", help="Create a new folder with the Stack+ starter notes") + group.add_argument("--skip", action="store_true", help="Skip vault setup") + + +def command(args): + folder = choose(args.existing, args.create, interactive=not args.skip and sys.stdin.isatty() and sys.stderr.isatty()) + print(json.dumps({"vault": str(folder) if folder else None})) + return 0 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + arguments(parser) + try: + sys.exit(command(parser.parse_args())) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") diff --git a/native_setup.py b/native_setup.py index ca92af0..668c443 100644 --- a/native_setup.py +++ b/native_setup.py @@ -277,7 +277,14 @@ def guidance(current, state, vault): # Replace only the previous generated publisher and project-record paragraphs. # User-owned text outside this block and newer plugin/vault choices survive. body = re.sub(r"(?m)^Use the project-bound publisher's activate_leaf[^\n]*\n\n", "", body) - body = re.sub(r"(?m)^Keep source-backed, correctable knowledge in the owning project's canonical records\.[^\n]*", knowledge_guidance(vault), body) + if vault: + generated_location = (r"(?m)^(?:Use only the user's explicitly authorized canonical Markdown/Git vault" + r"|Canonical knowledge uses the authorized Markdown/Git vault at [^\n]+?" + r"|Canonical knowledge uses Markdown and private local Git (?:at [^\n]+?|in the user's explicitly authorized vault))" + r"\.(?= Keep source ownership, scope, stable note ID, revision/hash,)") + body = re.sub(generated_location, lambda _: f"Canonical knowledge uses the authorized Markdown/Git vault at {vault}.", body) + body = re.sub(r"(?m)^Keep source-backed, correctable knowledge in the owning project's canonical records\.[^\n]*", + lambda _: knowledge_guidance(vault), body) if KNOWLEDGE_ROUTINE not in body: body = body.rstrip() + "\n\n" + KNOWLEDGE_ROUTINE + "\n" return current[:a] + body + current[b:] @@ -428,7 +435,14 @@ def apply(args): derived_before = fingerprint(agents) if derived_before["kind"] not in ("absent", "file"): raise ValueError("AGENTS must be a regular file or absent") - content = guidance(agents.read_text() if agents.exists() else "", state, args.vault) + from lib.vault_setup import choose + first_setup = not profile.exists() and not getattr(args, "skip_vault", False) + interactive = first_setup and sys.stdin.isatty() and sys.stderr.isatty() + same_release = target.is_symlink() and os.readlink(target) == str(release / "skills") + if (target.exists() or target.is_symlink()) and not same_release and not args.replace: + raise ValueError("Existing user skill root: inspect it, then pass --replace to back it up and replace it") + folder = choose(args.vault, getattr(args, "create_vault", None), interactive=interactive) + content = guidance(agents.read_text() if agents.exists() else "", state, str(folder) if folder else None) same(agents, derived_before) index_bytes = (json.dumps(index, sort_keys=True, indent=2) + "\n").encode() profile_bytes = (json.dumps({"release": str(release), "home": str(home), "codex_home": str(codex_home), "names": [r["name"] for r in index]}, @@ -462,22 +476,33 @@ def apply(args): parent_identity(target, binding) same(target, row["after"]) return {"changed": True, "repaired_removed_entry": True, "skills": len(index), "release": str(release)} - if target.is_symlink() and os.readlink(target) == str(release / "skills") and all( + if same_release and all( p.is_file() and not p.is_symlink() and p.read_bytes() == data for p, data in desired.items() ): return {"changed": False, "skills": len(index), "release": str(release)} - if (target.exists() or target.is_symlink()) and not args.replace: + # An explicit vault change on an otherwise identical profile updates only + # the generated guidance. Its own rollback must restore the preceding note path. + vault_update = folder is not None and same_release and all( + p.is_file() and not p.is_symlink() and p.read_bytes() == desired[p] for p in (index_path, profile) + ) + if (target.exists() or target.is_symlink()) and not (args.replace or vault_update): raise ValueError("Existing user skill root: inspect it, then pass --replace to back it up and replace it") code = profile_install.stage(state) - run = state / "runs" / ("native-" + release.name[:16]) + if vault_update: + desired = {agents: desired[agents]} + run = P(tempfile.mkdtemp(prefix="native-vault-", dir=state / "runs")) run.mkdir(mode=0o700, parents=True, exist_ok=True) tx = Transaction(run) with tx.lock(): same(agents, derived_before) + if vault_update and (not target.is_symlink() or os.readlink(target) != str(release / "skills") + or index_path.read_bytes() != index_bytes or profile.read_bytes() != profile_bytes): + raise ValueError("The native profile changed while choosing a vault. Run setup again.") preflight(allowed, run) if profile.is_file() and json.loads(profile.read_text()).get("home") != str(home): raise ValueError("Native state belongs to another home") - before = {p: fingerprint(p) for p in [target, *desired]} + targets = list(desired) if vault_update else [target, *desired] + before = {p: fingerprint(p) for p in targets} before[agents] = derived_before for i, (p, old) in enumerate(before.items()): if old["kind"] != "absent": @@ -516,14 +541,16 @@ def apply(args): raise ValueError("Unexpected pending recovery pointer") temp_pointer.symlink_to(helper) os.replace(temp_pointer, pointer) - tx.link(target, release / "skills", expected=before[target]) + if not vault_update: + tx.link(target, release / "skills", expected=before[target]) for p, data in desired.items(): tx.replace_file(p, data, modes[p], expected=before[p], prepared=prepared[p]) - after_link = run / "root-after" - if after_link.exists() or after_link.is_symlink(): - tx.preserve_attempt(after_link, "previous-root-after") - copy(target, after_link) - same(after_link, fingerprint(target)) + if not vault_update: + after_link = run / "root-after" + if after_link.exists() or after_link.is_symlink(): + tx.preserve_attempt(after_link, "previous-root-after") + copy(target, after_link) + same(after_link, fingerprint(target)) return {"changed": True, "skills": len(index), "release": str(release), "run": str(run), "rollback": str(pointer)} def rollback(run, chain): @@ -585,7 +612,10 @@ def main(): a.add_argument("--skillspector", action="store_true", help="Add NVIDIA SkillSpector source-audit method; pinned static runtime commissioned explicitly") a.add_argument("--roast-room", action="store_true", help="Add the upstream Roast Room critique method and support; private source pack commissioned explicitly") a.add_argument("--council-of-high-intelligence", action="store_true", help="Add the upstream historical-persona Council method and complete support") - a.add_argument("--vault", help="Existing user-authorized vault path; does not create a vault") + vault = a.add_mutually_exclusive_group() + vault.add_argument("--vault", help="Use an existing Obsidian vault for knowledge guidance") + vault.add_argument("--create-vault", metavar="FOLDER", help="Create an Obsidian vault with starter notes") + vault.add_argument("--skip-vault", action="store_true", help="Skip the first-install vault question") sub.add_parser("list") a = sub.add_parser("rollback") a.add_argument("run") diff --git a/nstack.py b/nstack.py index f77eea5..a5d4deb 100755 --- a/nstack.py +++ b/nstack.py @@ -270,10 +270,11 @@ def main(): if sys.argv[1:2]==['selections']: from lib.selected_catalog import main as selections_main return selections_main(sys.argv[2:]) - from lib import review_packets + from lib import review_packets, vault_setup sys.path.insert(0,str(ROOT/'addons/01/scripts')) import project_find p=argparse.ArgumentParser(description='Find reviewed capabilities and inspect their routes before use.',epilog='Start read-only: ./stack+ search web-ui-design --brief, then ./stack+ show COMPONENT_ID. Search and show do not install or activate anything.');sub=p.add_subparsers(dest='cmd',required=True,metavar='COMMAND') + vault_setup.arguments(sub.add_parser('vault',help='Use an existing Obsidian vault or create one with starter notes')) sub.add_parser('selections', help='Inspect portable scope and pinned sources for selected methods') project_find.arguments(sub.add_parser('find',help='Search eligible project skill instructions and references')) review_packets.add_arguments(sub.add_parser('review', help='Pin, read and verify local Elephant–Goldfish review packets')) @@ -300,6 +301,7 @@ def main(): a=sub.add_parser('knowledge',help='Read or update project-scoped knowledge');a.add_argument('action',choices=['set','read','delete']);a.add_argument('project');a.add_argument('id');a.add_argument('--claim');a.add_argument('--source');a.add_argument('--expected-generation',type=int,default=0) args=p.parse_args() try: + if args.cmd=='vault':return vault_setup.command(args) if args.cmd=='review':return review_packets.command(args) if args.cmd=='find':return project_find.run(args,sys.modules[__name__]) if args.cmd=='search': diff --git a/registry/stackplus-selections.json b/registry/stackplus-selections.json index 87a0b74..57a5535 100644 --- a/registry/stackplus-selections.json +++ b/registry/stackplus-selections.json @@ -2328,7 +2328,7 @@ "scope": "Project-scoped persistent research, replication, and independent verification", "source": { "repository": "nazeeh111/X-Factor", - "revision": "f7a00959e1fcc94356864bf11250bd22b38cf26e", + "revision": "61e7e5827f6ccdf90da204025fbee0dea071d1b2", "path": ".agents/skills/x-factor/SKILL.md" }, "leaf": ".agents/skills/x-factor", diff --git a/tests/test_vault_setup.py b/tests/test_vault_setup.py new file mode 100644 index 0000000..3c6c19d --- /dev/null +++ b/tests/test_vault_setup.py @@ -0,0 +1,103 @@ +import contextlib +import io +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from lib import vault_setup + + +ROOT = Path(__file__).resolve().parents[1] + + +class VaultSetupTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name).resolve() + self.vault = self.root / "Lab notes" + + def cli(self, *options, check=True): + return subprocess.run([str(ROOT / "stack+"), "vault", *options], stdin=subprocess.DEVNULL, + cwd=self.root, capture_output=True, text=True, check=check) + + def test_create_and_open_existing_preserve_notes_and_configuration(self): + created = self.cli("--create", self.vault) + self.assertEqual(json.loads(created.stdout)["vault"], str(self.vault)) + self.assertIn("Open folder as vault", created.stderr) + files = {p.relative_to(vault_setup.TEMPLATE) for p in vault_setup.TEMPLATE.rglob("*") if p.is_file()} + self.assertEqual({p.relative_to(self.vault) for p in self.vault.rglob("*") if p.is_file()}, files) + for path in files: + self.assertEqual((self.vault / path).read_bytes(), (vault_setup.TEMPLATE / path).read_bytes()) + self.assertEqual(self.vault.stat().st_mode & 0o077, 0) + (self.vault / "Home.md").write_text("My lab notebook") + settings = self.vault / ".obsidian/community-plugins.json" + settings.parent.mkdir() + settings.write_text('["my-plugin"]') + self.assertEqual(json.loads(self.cli("--existing", self.vault).stdout)["vault"], str(self.vault)) + self.assertNotEqual(self.cli("--create", self.vault, check=False).returncode, 0) + self.assertEqual((self.vault / "Home.md").read_text(), "My lab notebook") + self.assertEqual(settings.read_text(), '["my-plugin"]') + + def test_unanswered_skip_and_conflicts(self): + for flags in ([], ["--skip"]): + self.assertIsNone(json.loads(self.cli(*flags).stdout)["vault"]) + self.assertEqual(list(self.root.iterdir()), []) + self.vault.symlink_to(self.root / "missing") + self.assertNotEqual(self.cli("--create", self.vault, check=False).returncode, 0) + self.assertTrue(self.vault.is_symlink()) + self.assertFalse(self.vault.exists()) + self.assertNotEqual(self.cli("--existing", self.vault, check=False).returncode, 0) + + def test_interrupted_copy_and_concurrent_editor_preserve_user_contents(self): + with patch.object(vault_setup.shutil, "copytree", side_effect=OSError("interrupted copy")): + with self.assertRaises(OSError): + vault_setup.choose(create=self.vault) + self.assertFalse(self.vault.exists()) + self.assertEqual(list(self.root.iterdir()), []) + rename = Path.rename + def concurrent_note(starter, target): + (target / "My note.md").write_text("Keep my note") + return rename(starter, target) + with patch.object(Path, "rename", concurrent_note), self.assertRaises(OSError): + vault_setup.choose(create=self.vault) + self.assertEqual([f.name for f in self.vault.iterdir()], ["My note.md"]) + self.assertEqual((self.vault / "My note.md").read_text(), "Keep my note") + + def test_wizard_handles_skip_cancel_and_new_folder(self): + for answers in ([""], ["2", ""], [EOFError]): + with self.subTest(answers=answers), patch("builtins.input", side_effect=answers), contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(vault_setup.choose(interactive=True)) + with patch("builtins.input", side_effect=["invalid", "3", str(self.vault)]), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(vault_setup.choose(interactive=True), self.vault) + self.assertTrue((self.vault / "Home.md").is_file()) + + def test_native_install_connects_and_preserves_outside_guidance(self): + home = self.root / "home" + args = [sys.executable, str(ROOT / "native_setup.py"), "install", "--only", "01", + "--home", str(home), "--codex-home", str(home / ".codex"), "--state", str(self.root / "state")] + agents = home / ".codex/AGENTS.md" + agents.parent.mkdir(parents=True) + agents.write_text("Our lab's existing instructions.\n") + def install(*flags): + return subprocess.run([*args, *flags], cwd=self.root, stdin=subprocess.DEVNULL, + capture_output=True, text=True, check=True) + install("--skip-vault") + before = agents.read_bytes() + self.assertFalse(self.vault.exists()) + skills = home / ".agents/skills" + binding = skills.lstat() + change = json.loads(install("--create-vault", self.vault).stdout) + self.assertIn(str(self.vault), agents.read_text()) + self.assertTrue(agents.read_text().startswith("Our lab's existing instructions.\n")) + saved = agents.read_text() + install() + self.assertEqual(agents.read_text(), saved) + self.assertEqual(binding.st_ino, skills.lstat().st_ino) + subprocess.run([sys.executable, str(ROOT / "native_setup.py"), "rollback", change["run"]], check=True, capture_output=True) + self.assertEqual(agents.read_bytes(), before) + self.assertEqual((self.vault / "Home.md").read_bytes(), (vault_setup.TEMPLATE / "Home.md").read_bytes())