Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
Unreleased

• /cd <dir> 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
Expand Down
67 changes: 59 additions & 8 deletions client/cli/corpus_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <name> (or --here) wins;
Expand Down Expand Up @@ -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 <name> 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.
Expand Down
7 changes: 6 additions & 1 deletion client/cli/corpus_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []

Expand Down
6 changes: 3 additions & 3 deletions client/cli/operator_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down
75 changes: 61 additions & 14 deletions client/cli/rag_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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...")

Expand Down
4 changes: 2 additions & 2 deletions client/tests/test_corpus_behaviour_is_declared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
73 changes: 73 additions & 0 deletions client/tests/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
15 changes: 13 additions & 2 deletions doc/source/using/projects.rst
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,20 @@ Indexing

.. code-block:: text

/cd <dir> move the session's corpus to <dir>, inside the
launch directory
/reindex rebuild the index for the current corpus
/corpus list and manage the registry (switching is
spear-chat --corpus <name>)
/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 <retrieval>` for what
it measurably buys, and :ref:`Troubleshooting <troubleshooting>` for the
Expand Down
Loading