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
205 changes: 205 additions & 0 deletions client/cli/bake_state.py
Original file line number Diff line number Diff line change
@@ -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())
100 changes: 100 additions & 0 deletions client/tests/test_bake_state.py
Original file line number Diff line number Diff line change
@@ -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()
2 changes: 1 addition & 1 deletion client/tests/test_reds_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 20 additions & 0 deletions doc/source/start/container_run.rst
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,26 @@ container reaches it through an SSH tunnel you open on your machine.

$ scripts/docker/add-claude.sh <registry>/spear:<version>-<entity>

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 <registry>/spear:<version>-<name>
registry 1 added: <corpus>
index <collection> (<n> chunks)
knowledge <n> active records
built <registry>/spear:<version>-<name>

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.
Expand Down
5 changes: 3 additions & 2 deletions docker/Dockerfile.harness
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions docker/spear-bake-state
Original file line number Diff line number Diff line change
@@ -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 "$@"
Loading
Loading