diff --git a/CHANGELOG b/CHANGELOG index 1e0ce1c..7413b16 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,9 @@ Unreleased + • /cd moves the session's corpus -- index, history, memories, + rules -- to a directory inside the launch tree, so /reindex right + after rebuilds that tree. The tools stay in the launch directory. + • Image profile reds, between public and private: the image for the people of one institute. It bakes the corpora named by --bake and is cut to them -- of the index only their collections, of rules, skills diff --git a/client/cli/corpus_registry.py b/client/cli/corpus_registry.py index 49d76a6..3c1c6d3 100644 --- a/client/cli/corpus_registry.py +++ b/client/cli/corpus_registry.py @@ -403,6 +403,64 @@ def offer_workspace_split(path, projects, min_files=300): return None +def umbrella_spec(path, below): + """The session spec of a directory that holds registered corpora.""" + path = os.path.realpath(path) + + return {"name": "workspace:" + (os.path.basename(path) or "root"), + "path": path, "kind": "generic", "corpora": sorted(below), + # Discovered, not declared. Declared federations and shared + # corpora are a deliberate choice and stay attached every turn; + # these are whatever happened to be registered under the + # directory, so they are selected per question instead. + "auto_corpora": sorted(below)} + + +def excludes_path(spec, path): + """Whether `spec` leaves `path`, a directory inside its tree, out of its + index: under one of its path exclusions, or through a bare name.""" + rel = os.path.relpath(os.path.realpath(path), os.path.realpath(spec["path"])) + parts = rel.split(os.sep) + + for e in spec.get("exclude", ()): + if "/" in e: + e = os.path.normpath(e) + + if rel == e or rel.startswith(e + os.sep): + return True + elif e in parts: + return True + + return False + + +def corpus_at(path, projects=None): + """The corpus /cd lands on: the one a session launched in `path` works on. + + Startup's rules without its questions, and one more: a directory its + corpus excludes is not part of that corpus. opencn-ng excludes ./linux, + which is indexed on its own, so /cd linux must not land back on + opencn-ng. + """ + projects = load_projects() if projects is None else projects + path = os.path.realpath(path) + found = detect_project(projects, path) + + if found and os.path.realpath(projects[found]["path"]) == path: + return {"name": found, **projects[found]} + + below = corpora_below(projects, path) + + if below: + return umbrella_spec(path, below) + + if found and not excludes_path(projects[found], path): + return {"name": found, **projects[found]} + + return {"name": "adhoc:" + (os.path.basename(path) or "root"), + "path": path, "kind": "generic"} + + def resolve_project_at_startup(): """The CURRENT directory decides everything — no prompt: 1. explicit --corpus (or --here) wins; @@ -451,18 +509,11 @@ def resolve_project_at_startup(): below = corpora_below(projects) if below: - cwd = os.path.realpath(os.getcwd()) print(f"{C_DIM} ⎿ {len(below)} registered corpora sit under this " f"directory ({', '.join(sorted(below))}) — tools run here, " f"retrieval spans them. --corpus narrows to one.{C_RST}") - return {"name": "workspace:" + (os.path.basename(cwd) or "root"), - "path": cwd, "kind": "generic", "corpora": sorted(below), - # Discovered, not declared. Declared federations and shared - # corpora are a deliberate choice and stay attached every turn; - # these eight are whatever happened to be registered under the - # cwd, so they are selected per question instead. - "auto_corpora": sorted(below)} + return umbrella_spec(os.getcwd(), below) # cwd outside any corpus → ad-hoc on the cwd (no picker). Offer a split # if it is a big multi-component workspace. diff --git a/client/cli/corpus_search.py b/client/cli/corpus_search.py index 8f67b43..7977867 100644 --- a/client/cli/corpus_search.py +++ b/client/cli/corpus_search.py @@ -176,7 +176,12 @@ def init_chromadb(): client = _db() try: - own = [(client.get_collection(name=session_workspace.COLLECTION_NAME), "")] + # After /cd the corpus sits below the directory the tools run in, and + # its chunks are addressed from there like a federated one's. + + prefix = corpus_prefix(session_workspace.CORPUS_ROOT) + own = [(client.get_collection(name=session_workspace.COLLECTION_NAME), + "" if os.path.isabs(prefix) else prefix)] except Exception: own = [] diff --git a/client/cli/operator_input.py b/client/cli/operator_input.py index 21347c2..9d20343 100644 --- a/client/cli/operator_input.py +++ b/client/cli/operator_input.py @@ -310,9 +310,9 @@ def handle_bang_command(cmd_line): #: The slash commands, as the banner lists them and as Tab completes them: #: one list, so a command cannot be completed and go unlisted, or the reverse. -SESSION_COMMANDS = ("/search", "/reindex", "/corpus", "/history", "/skills", - "/remember", "/recall", "/knowledge", "/forget", "/good", "/bad", - "/undo", "/clear", "/model", "/tools") +SESSION_COMMANDS = ("/search", "/cd", "/reindex", "/corpus", "/history", + "/skills", "/remember", "/recall", "/knowledge", "/forget", + "/good", "/bad", "/undo", "/clear", "/model", "/tools") OPERATOR_COMMANDS = ("/standard", "/finetune") diff --git a/client/cli/rag_chat.py b/client/cli/rag_chat.py index 62371f5..ebeacba 100755 --- a/client/cli/rag_chat.py +++ b/client/cli/rag_chat.py @@ -61,7 +61,7 @@ STANDARD_OPERATOR, STANDARD_STORE, STATE_DIR, TRACE, TRAINING_STORE, ) from cli.corpus_registry import ( - handle_corpus_command, load_projects, resolve_project_at_startup, + corpus_at, handle_corpus_command, load_projects, resolve_project_at_startup, ) from cli.corpus_search import ( archive_forget, corpus_property, init_chromadb, reindex_command, @@ -177,19 +177,9 @@ def compaction_policy_from_environment(): return CompactionPolicy() -def main(): - global TRACE_PROVIDER, TRACE_MODEL - - # Before anything with a side effect: --help must not resolve a corpus, - # offer a workspace split, or touch the model server. - - if {"--help", "-h"} & set(sys.argv[1:]): - print_help() - return - - banner_art() - set_project(resolve_project_at_startup()) - init_readline() +def corpus_prompt(): + """The session corpus's prompt and rules, as + (instructions, source, global_rules, corpus_rules).""" # A corpus may declare a domain prompt of its own; otherwise the generic # one. This used to be chosen by corpus KIND, which meant a prompt naming @@ -224,6 +214,29 @@ def main(): global_rules = load_rules() project_rules = load_corpus_rules() + + return system_instructions, system_source, global_rules, project_rules + + +def main(): + global TRACE_PROVIDER, TRACE_MODEL + + # Before anything with a side effect: --help must not resolve a corpus, + # offer a workspace split, or touch the model server. + + if {"--help", "-h"} & set(sys.argv[1:]): + print_help() + return + + banner_art() + set_project(resolve_project_at_startup()) + + # Where /cd resolves a relative path from: the directory it last entered. + + focus = session_workspace.PROJECT_ROOT + init_readline() + + system_instructions, system_source, global_rules, project_rules = corpus_prompt() base_prompt = system_instructions + global_rules + project_rules + TOOL_GUIDE collection = init_chromadb() @@ -484,6 +497,40 @@ def read_user_input(): continue + if user_input == "/cd" or user_input.startswith("/cd "): + # The corpus moves, the tools do not: they keep running in the + # launch directory, whose sandbox already holds every tree /cd can + # reach. What follows the corpus is what belongs to it -- index, + # history, memories, prompt and rules -- so /reindex right after + # rebuilds the tree just entered. + + arg = user_input[3:].strip() or session_workspace.PROJECT_ROOT + target = os.path.realpath(os.path.join(focus, os.path.expanduser(arg))) + launch = os.path.realpath(session_workspace.PROJECT_ROOT) + + if not os.path.isdir(target): + print(f"{C_ERR}/cd: {arg}: no such directory{C_RST}\n") + elif target != launch and not target.startswith(launch + os.sep): + print(f"{C_ERR}/cd: {target} is outside {launch}, where this " + f"session was launched — relaunch spear there{C_RST}\n") + else: + save_history(history) + focus = target + set_project(corpus_at(target)) + (system_instructions, system_source, + global_rules, project_rules) = corpus_prompt() + base_prompt = system_instructions + global_rules + project_rules + TOOL_GUIDE + collection = init_chromadb() + corpus_search.COLLECTION = collection + history = load_history() + print(f"{C_DIM} ⎿ {target}{C_RST}\n" + f"Corpus: {session_workspace.PROJECT} " + f"({session_workspace.CORPUS_ROOT})" + + (f" — {_corpus_summary(collection)}" if collection else "") + + "\n") + + continue + if user_input == "/reindex": print("Reindexing...") diff --git a/client/tests/test_corpus_behaviour_is_declared.py b/client/tests/test_corpus_behaviour_is_declared.py index e63a251..a3d859b 100644 --- a/client/tests/test_corpus_behaviour_is_declared.py +++ b/client/tests/test_corpus_behaviour_is_declared.py @@ -167,10 +167,10 @@ def test_a_corpus_names_its_own(self): "system-prompt.md") def test_the_selection_is_not_a_kind_branch(self): - """Read from main(), which is where the choice is made.""" + """Read from corpus_prompt(), which is where the choice is made.""" import inspect - source = inspect.getsource(rag_chat.main) + source = inspect.getsource(rag_chat.corpus_prompt) self.assertIn('corpus_property("prompt_file")', source) self.assertNotIn('PROJECT_KIND !=', source) diff --git a/client/tests/test_indexing.py b/client/tests/test_indexing.py index 04b5ec2..a3c90af 100644 --- a/client/tests/test_indexing.py +++ b/client/tests/test_indexing.py @@ -334,6 +334,79 @@ def test_a_declared_exclusion_is_not_repeated(self): self.assertEqual(["--exclude", "vendor"], self.corpus_search.reindex_options()) +class CdMovesTheCorpusTest(unittest.TestCase): + """/cd moves the session's corpus inside the launch tree, so /reindex after + it rebuilds the tree just entered. The shape is opencn-ng's: the umbrella + excludes linux/, whose kernel and userspace are corpora of their own.""" + + def setUp(self): + from cli import corpus_registry, corpus_search, session_workspace + self.corpus_registry = corpus_registry + self.corpus_search = corpus_search + self.session_workspace = session_workspace + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = os.path.realpath(self.tmp.name) + "/opencn-ng" + + for d in ("doc", "qemu", "linux/linux", "linux/usr"): + os.makedirs(f"{self.root}/{d}") + + self.addCleanup(setattr, corpus_registry, "PROJECTS_FILE", + corpus_registry.PROJECTS_FILE) + + for name in ("PROJECT", "PROJECT_SPEC", "PROJECT_KIND", "PROJECT_ROOT", + "CORPUS_ROOT", "COLLECTION_NAME", "WORKSPACE", + "HISTORY_FILE", "MEMORIES_FILE"): + self.addCleanup(setattr, session_workspace, name, + getattr(session_workspace, name)) + + corpus_registry.PROJECTS_FILE = os.path.join(self.tmp.name, "projects.json") + self.projects = { + "opencn-ng": {"path": self.root, "kind": "generic", + "exclude": ["./linux", "./qemu"]}, + "opencn-usr": {"path": f"{self.root}/linux/usr", "kind": "generic"}, + "opencn-ng-linux": {"path": f"{self.root}/linux/linux", "kind": "generic"}, + } + + with open(corpus_registry.PROJECTS_FILE, "w") as f: + json.dump(self.projects, f) + + self.addCleanup(os.chdir, os.getcwd()) + os.chdir(self.root) + + def test_a_registered_tree_is_its_corpus(self): + spec = self.corpus_registry.corpus_at(f"{self.root}/linux/linux") + self.assertEqual("opencn-ng-linux", spec["name"]) + + def test_an_excluded_directory_holding_corpora_federates_them(self): + """Not back to opencn-ng, which leaves linux/ out of its index.""" + spec = self.corpus_registry.corpus_at(f"{self.root}/linux") + self.assertEqual("workspace:linux", spec["name"]) + self.assertEqual(["opencn-ng-linux", "opencn-usr"], spec["corpora"]) + + def test_an_excluded_directory_alone_is_ad_hoc(self): + spec = self.corpus_registry.corpus_at(f"{self.root}/qemu") + self.assertEqual(("adhoc:qemu", f"{self.root}/qemu"), + (spec["name"], spec["path"])) + + def test_a_plain_subdirectory_stays_in_its_corpus(self): + self.assertEqual("opencn-ng", + self.corpus_registry.corpus_at(f"{self.root}/doc")["name"]) + + def test_reindex_follows_the_corpus_and_the_tools_stay(self): + self.session_workspace.set_project( + self.corpus_registry.corpus_at(f"{self.root}/linux/linux")) + cmd = self.corpus_search.reindex_command() + self.assertEqual(f"{self.root}/linux/linux", cmd[2]) + self.assertEqual(self.session_workspace.COLLECTION_NAME, + cmd[cmd.index("--collection") + 1]) + self.assertEqual(self.root, self.session_workspace.PROJECT_ROOT) + + def test_cd_is_a_session_command(self): + from cli.operator_input import completion_candidates + self.assertEqual(["/cd"], completion_candidates("/c", "/c")[:1]) + + class CorpusCommandTest(unittest.TestCase): """/corpus and the `spear-corpus` CLI are one implementation. diff --git a/doc/source/using/projects.rst b/doc/source/using/projects.rst index aea14f1..313a62a 100644 --- a/doc/source/using/projects.rst +++ b/doc/source/using/projects.rst @@ -349,9 +349,20 @@ Indexing .. code-block:: text + /cd move the session's corpus to , inside the + launch directory /reindex rebuild the index for the current corpus - /corpus list and manage the registry (switching is - spear-chat --corpus ) + /corpus list and manage the registry + +``/cd`` moves the corpus, not the tools. Launched in ``opencn-ng``, +``/cd linux/linux`` makes the session's index, history, memories and rules +those of ``opencn-ng-linux``, and ``/reindex`` then rebuilds that tree; the +tools keep running in ``opencn-ng``, and retrieved paths come prefixed with +``linux/linux/`` so they open from there. The directory resolves as a launch +there would, except that a directory its corpus excludes is not part of it: +``/cd linux`` federates the corpora below ``linux/`` rather than falling back +on ``opencn-ng``. A target outside the launch directory is refused; ``/cd`` +alone returns to it. Indexing is not optional in practice. See :ref:`Retrieval ` for what it measurably buys, and :ref:`Troubleshooting ` for the