diff --git a/client/cli/bake_state.py b/client/cli/bake_state.py new file mode 100644 index 0000000..49cb278 --- /dev/null +++ b/client/cli/bake_state.py @@ -0,0 +1,205 @@ +"""What a user's state adds to an image, written into the image itself. + +A session in a container registers trees, indexes them and records what it +learned, all in the user's state directory. Baked, that becomes part of a new +image, so someone else picks the work up with nothing but the image and a +checkout of the tree: + + the corpora the user registered -> the image's registry + their index -> the image's index + the knowledge that was accepted -> the image's common knowledge + +Run as root in a container of the image, with the state mounted; the launcher +then commits that container (spear-run.sh --build). + +A corpus path under the user's home is rewritten relative to it, which is how +an image names its trees: whoever has the same checkout at the same place +under their own home gets the index. +""" + +from __future__ import annotations + +import json +import os +import shutil +import sqlite3 +import sys +import tempfile + +BATCH = 500 + + +def bake_registry(user, shipped, home, collection_name_for): + """The shipped registry with the user's corpora added; the names added. + + Each entry is given its collection by name: derived from the path, it + would not survive the path being rewritten. + """ + merged, added = dict(shipped), [] + prefix = home.rstrip("/") + "/" if home else None + + for name, spec in sorted(user.items()): + if name in shipped or not isinstance(spec, dict) or "path" not in spec: + continue + + entry = dict(spec) + entry["collection"] = collection_name_for(spec) + + if prefix and spec["path"].startswith(prefix): + entry["path"] = spec["path"][len(prefix):] + + merged[name] = entry + added.append(name) + + return merged, added + + +def bake_index(own, shipped, wanted): + """Copy the named collections of `own` into `shipped`, vectors included. + {name: chunks}; a collection the user's index does not have is left out.""" + copied = {} + + for name in sorted(wanted): + try: + source = own.get_collection(name) + except Exception: + continue + + try: + shipped.delete_collection(name) + except Exception: + pass + + target = shipped.create_collection(name=name, metadata=source.metadata or None) + total = source.count() + + for offset in range(0, total, BATCH): + rows = source.get(limit=BATCH, offset=offset, + include=["documents", "metadatas", "embeddings"]) + + if rows["ids"]: + target.add(ids=rows["ids"], documents=rows["documents"], + metadatas=rows["metadatas"], embeddings=rows["embeddings"]) + + copied[name] = total + + return copied + + +def bake_knowledge(source, target, schema, active): + """Add the user's active records to the common store; how many. + + Ad hoc workspaces stay behind: they are named after a path of one machine. + """ + if not os.path.isfile(source): + return 0 + + reader = sqlite3.connect(f"file:{source}?mode=ro", uri=True) + os.makedirs(os.path.dirname(target), exist_ok=True) + writer = sqlite3.connect(target) + writer.executescript(schema) + + try: + rows = reader.execute( + "SELECT record_id, workspace_id, lifecycle, body FROM records " + "WHERE lifecycle = ? AND workspace_id NOT LIKE 'adhoc:%'", (active,)).fetchall() + except sqlite3.Error: + rows = [] + + for record_id, workspace_id, lifecycle, body in rows: + record = json.loads(body) + writer.execute("INSERT OR REPLACE INTO records VALUES (?, ?, ?, ?)", + (record_id, workspace_id, lifecycle, body)) + writer.execute("INSERT OR REPLACE INTO versions VALUES (?, ?, ?, ?)", + (record_id, record["version"], record["updated_at"], body)) + + writer.commit() + writer.close() + reader.close() + + return len(rows) + + +def _read(path): + try: + with open(path) as handle: + data = json.load(handle) + except (OSError, ValueError): + return {} + + return data if isinstance(data, dict) else {} + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + + if len(argv) != 2: + print("usage: spear-bake-state STATE_DIR HOME_OF_THE_USER", file=sys.stderr) + + return 2 + + state, home = argv + + import chromadb + + from cli import chat_settings, corpus_registry, corpus_search + from context import workspace_knowledge as wk + from runtime import state_paths + + shipped_registry = _read(corpus_registry.PROJECTS_FILE) + merged, added = bake_registry(_read(f"{state}/projects.json"), shipped_registry, + home, corpus_search.collection_name_for) + + with open(corpus_registry.PROJECTS_FILE, "w") as handle: + json.dump(merged, handle, indent=2) + + print(f" registry {len(added)} added" + (f": {', '.join(added)}" if added else "")) + + # Every collection a registered corpus names, the shipped ones included: a + # corpus of the image that the user indexed again is baked as they left it. + + copied = {} + + if chat_settings.SHIPPED_DB_PATH and os.path.isdir(f"{state}/chromadb"): + wanted = {spec["collection"] for spec in merged.values() + if isinstance(spec, dict) and spec.get("collection")} + + # Chroma opens its files for writing even to read them, and the state + # is mounted read-only: it reads a copy. + + with tempfile.TemporaryDirectory() as scratch: + shutil.copytree(f"{state}/chromadb", f"{scratch}/chromadb") + copied = bake_index(chromadb.PersistentClient(path=f"{scratch}/chromadb"), + chromadb.PersistentClient(path=chat_settings.SHIPPED_DB_PATH), + wanted) + + for name, chunks in copied.items(): + print(f" index {name} ({chunks} chunks)") + + if not copied: + print(" index nothing of the user's to add") + + common = state_paths.common_dir() + records = 0 + + if common: + records = bake_knowledge(f"{state}/knowledge.sqlite3", str(common / "knowledge.sqlite3"), + wk._SCHEMA, wk.Lifecycle.ACTIVE) + + print(f" knowledge {records} active records") + + # The image is run as whoever launches it. + + for root in filter(None, (chat_settings.SHIPPED_DB_PATH, str(common or ""))): + for directory, _, files in os.walk(root): + os.chmod(directory, 0o777) + + for name in files: + os.chmod(os.path.join(directory, name), 0o666) + + return 0 + + +if __name__ == "__main__": + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) + sys.exit(main()) diff --git a/client/tests/test_bake_state.py b/client/tests/test_bake_state.py new file mode 100644 index 0000000..29ba01a --- /dev/null +++ b/client/tests/test_bake_state.py @@ -0,0 +1,100 @@ +"""A user's state, written into an image: registry, index, knowledge.""" + +import json +import os +import sqlite3 +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import chromadb + +from cli import bake_state +from context import workspace_knowledge as wk + + +class Registry(unittest.TestCase): + def bake(self, user, shipped): + return bake_state.bake_registry(user, shipped, "/home/me", + lambda spec: "named_" + os.path.basename(spec["path"])) + + def test_a_path_under_the_home_becomes_relative_and_keeps_its_collection(self): + merged, added = self.bake({"tht": {"path": "/home/me/work/tht", "kind": "generic"}}, {}) + + self.assertEqual(added, ["tht"]) + self.assertEqual(merged["tht"], {"path": "work/tht", "kind": "generic", + "collection": "named_tht"}) + + def test_a_path_elsewhere_is_kept(self): + merged, _ = self.bake({"x": {"path": "/srv/x"}}, {}) + + self.assertEqual(merged["x"]["path"], "/srv/x") + + def test_a_shipped_entry_is_not_replaced(self): + shipped = {"tht": {"path": "a/b", "collection": "c"}} + merged, added = self.bake({"tht": {"path": "/home/me/other"}}, shipped) + + self.assertEqual((merged, added), (shipped, [])) + + +class Index(unittest.TestCase): + def test_the_named_collections_are_copied_with_their_vectors(self): + with tempfile.TemporaryDirectory() as tmp: + own = chromadb.PersistentClient(path=f"{tmp}/own") + shipped = chromadb.PersistentClient(path=f"{tmp}/shipped") + source = own.create_collection("mine", metadata={"embed_model": "m"}) + source.add(ids=["a", "b"], documents=["one", "two"], + metadatas=[{"filepath": "x"}, {"filepath": "y"}], + embeddings=[[1.0, 0.0], [0.0, 1.0]]) + own.create_collection("unnamed") + stale = shipped.create_collection("mine") + stale.add(ids=["old"], documents=["old"], embeddings=[[1.0, 1.0]]) + + copied = bake_state.bake_index(own, shipped, {"mine", "absent"}) + baked = shipped.get_collection("mine") + rows = baked.get(ids=["b"], include=["documents", "metadatas", "embeddings"]) + + self.assertEqual(copied, {"mine": 2}) + self.assertEqual(baked.count(), 2) + self.assertEqual(baked.metadata["embed_model"], "m") + self.assertEqual(rows["documents"], ["two"]) + self.assertEqual(rows["metadatas"], [{"filepath": "y"}]) + self.assertEqual([round(v) for v in rows["embeddings"][0]], [0, 1]) + self.assertEqual([c.name for c in shipped.list_collections()], ["mine"]) + + +class Knowledge(unittest.TestCase): + def test_active_records_of_named_workspaces_are_added(self): + with tempfile.TemporaryDirectory() as tmp: + source = sqlite3.connect(f"{tmp}/user.sqlite3") + source.executescript(wk._SCHEMA) + + for ident, workspace, lifecycle in (("r1", "tht", wk.Lifecycle.ACTIVE), + ("r2", "adhoc:tmp", wk.Lifecycle.ACTIVE), + ("r3", "tht", "proposed")): + body = json.dumps({"version": 1, "updated_at": "t"}) + source.execute("INSERT INTO records VALUES (?, ?, ?, ?)", + (ident, workspace, lifecycle, body)) + + source.commit() + source.close() + + count = bake_state.bake_knowledge(f"{tmp}/user.sqlite3", f"{tmp}/common/knowledge.sqlite3", + wk._SCHEMA, wk.Lifecycle.ACTIVE) + common = sqlite3.connect(f"{tmp}/common/knowledge.sqlite3") + + self.assertEqual(count, 1) + self.assertEqual(common.execute("SELECT record_id FROM records").fetchall(), [("r1",)]) + self.assertEqual(common.execute("SELECT record_id FROM versions").fetchall(), [("r1",)]) + common.close() + + def test_no_store_adds_nothing(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(bake_state.bake_knowledge(f"{tmp}/absent", f"{tmp}/c/k.sqlite3", + wk._SCHEMA, wk.Lifecycle.ACTIVE), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/client/tests/test_reds_image.py b/client/tests/test_reds_image.py index bc982b4..4eeedb2 100644 --- a/client/tests/test_reds_image.py +++ b/client/tests/test_reds_image.py @@ -427,7 +427,7 @@ def docker_recording(self, tmp): (bin_dir / "docker").write_text( "#!/bin/bash\n" "case \"$*\" in\n" - " *projects.json*) echo name some/tree ;;\n" + " *projects.json*) echo name some/tree; echo other some/other ;;\n" f" run*) printf '%s\\n' \"$@\" > {tmp}/run ;;\n" "esac\n") (bin_dir / "docker").chmod(0o755) diff --git a/doc/source/start/container_run.rst b/doc/source/start/container_run.rst index 03f159b..d15ed53 100644 --- a/doc/source/start/container_run.rst +++ b/doc/source/start/container_run.rst @@ -193,6 +193,26 @@ container reaches it through an SSH tunnel you open on your machine. $ scripts/docker/add-claude.sh /spear:- +7. **Hand your work on** as an image. What a session registers, indexes and + records stays in your state directory (``~/.spear/state``): the corpora + added with ``/corpus add``, the index ``/reindex`` builds, the knowledge + you accepted. ``--build`` writes all of it into a new image: + + .. code-block:: console + + $ spear-run.sh --build /spear:- + registry 1 added: + index ( chunks) + knowledge active records + built /spear:- + + The source trees are not copied. A corpus whose tree is under your home + is named by its path relative to it, so whoever runs the new image from a + checkout at the same place under their own home, or names it with + ``--tree``, gets its index and picks the work up. A tree that was only + opened, never registered, is left out: its index is tied to its path on + your machine. + The ``--ask`` at the end is the permission mode (:ref:`usage`): confirm each edit and command. ``--safe`` is read-only, ``--auto`` runs without asking. Everything a session accumulates stays in ``~/.spear/state`` on your machine. diff --git a/docker/Dockerfile.harness b/docker/Dockerfile.harness index c9dea96..93ea688 100644 --- a/docker/Dockerfile.harness +++ b/docker/Dockerfile.harness @@ -101,11 +101,12 @@ COPY --from=repo docker/spear-claude-export /usr/local/bin/spear-claude-export # the corpus. The latter is only the preparation; docker/Dockerfile.claude # adds the program itself to the images that are to carry it. -COPY --from=repo docker/spear-shell docker/spear-chat docker/spear-where /usr/local/bin/ +COPY --from=repo docker/spear-shell docker/spear-chat docker/spear-where \ + docker/spear-bake-state /usr/local/bin/ COPY --from=repo docker/claude-launcher /usr/local/bin/claude RUN chmod +x /opt/spear/entrypoint.sh /opt/spear/spear-run.sh /usr/local/bin/spear-mcp \ /usr/local/bin/spear-claude-export /usr/local/bin/spear-shell /usr/local/bin/spear-chat \ - /usr/local/bin/spear-where /usr/local/bin/claude + /usr/local/bin/spear-where /usr/local/bin/spear-bake-state /usr/local/bin/claude ENV SPEAR_COMMON_STATE_DIR=/opt/spear/common ENV SPEAR_STANDARDS_ROOT=/opt/spear/common/standards diff --git a/docker/spear-bake-state b/docker/spear-bake-state new file mode 100755 index 0000000..3f9b561 --- /dev/null +++ b/docker/spear-bake-state @@ -0,0 +1,5 @@ +#!/bin/bash +# Write a user's state into this image's registry, index and common +# knowledge; spear-run.sh --build runs it and commits the result. + +exec /opt/spear/client/bin/python /opt/spear/client/cli/bake_state.py "$@" diff --git a/scripts/docker/spear-run.sh b/scripts/docker/spear-run.sh index 9e3bf56..e489299 100755 --- a/scripts/docker/spear-run.sh +++ b/scripts/docker/spear-run.sh @@ -15,7 +15,7 @@ # [--reds USER@HOST [--key FILE] [--port N] | --endpoint URL # | --provider anthropic [--model NAME]] # [--tree NAME | --corpus PATH] -# [--mount HOST_DIR:PATH]... [--state DIR] +# [--mount HOST_DIR:PATH]... [--state DIR] [--build TAG] # [-- harness args, e.g. --ask, --auto, --fresh] # # --image the image to run; default ghcr.io/smartobjectoriented/spear-reds @@ -38,6 +38,11 @@ # --state where conversations, knowledge, audit and the logins land on # this machine (default ~/.spear/state) # --list print the image's corpora and exit +# --build make a new image, TAG, out of the image and your state: the +# corpora you registered, their index and the knowledge you +# recorded become part of it, without the source trees. Someone +# who runs TAG from a checkout of the same tree picks the work +# up where it is. # --install copy this script to ~/.local/bin and, when there is none yet, # write the configuration file with the image named by --image; # nothing is run @@ -90,10 +95,11 @@ TREE="" PULL=0 LIST=0 INSTALL=0 +BUILD="" MOUNTS=() ARGS=() -usage() { sed -n '2,62p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; } +usage() { sed -n '2,67p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; } die() { echo "spear-run: $*" >&2; exit 1; } while [ $# -gt 0 ]; do @@ -112,6 +118,7 @@ while [ $# -gt 0 ]; do --state) STATE="$2"; shift 2 ;; --list) LIST=1; shift ;; --install) INSTALL=1; shift ;; + --build) BUILD="$2"; shift 2 ;; -h|--help) usage ;; --) shift; ARGS=("$@"); break ;; *) ARGS+=("$1"); shift ;; @@ -164,6 +171,26 @@ command -v docker >/dev/null || die "docker is not installed" [ "$PULL" = 1 ] && docker pull "$IMAGE" docker image inspect "$IMAGE" >/dev/null 2>&1 || die "no image $IMAGE here; add --pull, or docker login first" +if [ -n "$BUILD" ]; then + [ -d "$STATE" ] || die "no state at $STATE: nothing to add to $IMAGE" + NAME="spear-build-$$" + + # As root, since the registry and the index of an image are not the + # user's; the state is only read. + + docker run --name "$NAME" --user 0 -v "$STATE:/state:ro" \ + --entrypoint spear-bake-state "$IMAGE" /state "$HOME" \ + || { docker rm -f "$NAME" >/dev/null 2>&1; die "the image could not take the state"; } + + # The container was started on another program than the image's own. + + docker commit --change 'ENTRYPOINT ["/opt/spear/entrypoint.sh"]' --change 'CMD []' \ + --change 'USER root' "$NAME" "$BUILD" >/dev/null + docker rm "$NAME" >/dev/null + echo "built $BUILD" + exit 0 +fi + # The image's corpora: a name and a path under /corpora on each line. REGISTRY="$(docker run --rm --entrypoint /opt/spear/client/bin/python "$IMAGE" -c ' import json @@ -257,7 +284,12 @@ done if [ -n "$CORPUS" ]; then WORKDIR="/corpora/${CORPUS#/corpora/}" elif [ -n "$TREE" ]; then - rel="$(while read -r name path; do [ "$name" = "$TREE" ] && echo "$path"; done <<< "$REGISTRY")" + rel="" + + while read -r name path; do + if [ "$name" = "$TREE" ]; then rel="$path"; fi + done <<< "$REGISTRY" + [ -n "$rel" ] || die "the image has no corpus named '$TREE' (--list names them)" BINDS+=(-v "$PWD:/corpora/$rel") WORKDIR="/corpora/$rel"