From fa5fe4e4a48296e38a2608bfbcfca5a7518e7506 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 21 Nov 2026 10:45:54 +0100 Subject: [PATCH 1/2] Give a prompt of the other assistant what a SPEAR request gets In an image, the second assistant started from the rules of rules.d and the skills only, and searched the index when it chose to. A SPEAR turn starts from more, and does not leave retrieval to the model. The export now also lays out, as rule files, the rules learned on the machine, the corpus's map (the tree's own, else the shipped one) and what the project declares: identity, build and test commands. A guide rule says what arrives with a request and names the tools. A hook on every prompt prints the passages retrieved from the index and the workspace's recorded knowledge, through the functions a turn uses. The session's MCP server answers it on a private socket, so the embedder is loaded once; without a server the hook does the work itself. spear-knowledge becomes a program of the container, reading and proposing in the store SPEAR uses. --- CHANGELOG | 7 + client/cli/claude_context.py | 256 ++++++++++++++++++++++++++++ client/cli/claude_export.py | 106 +++++++++++- client/cli/corpus_mcp.py | 43 ++++- client/tests/test_claude_context.py | 151 ++++++++++++++++ client/tests/test_claude_export.py | 59 ++++++- client/tests/test_reds_image.py | 14 ++ doc/source/start/container_run.rst | 26 +++ docker/Dockerfile.harness | 6 +- docker/claude-launcher | 20 ++- docker/spear-claude-context | 6 + docker/spear-knowledge | 9 + 12 files changed, 685 insertions(+), 18 deletions(-) create mode 100644 client/cli/claude_context.py create mode 100644 client/tests/test_claude_context.py create mode 100755 docker/spear-claude-context create mode 100755 docker/spear-knowledge diff --git a/CHANGELOG b/CHANGELOG index e11e282..9776510 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -18,6 +18,13 @@ Unreleased volume, own checkouts over the baked trees. It is copied into the image. + • In an image, Claude Code starts from what a SPEAR request starts + from: beside the rules and skills, the learned rules, the corpus's + map and the project's build and test commands are laid out as rule + files, and a hook gives every prompt the passages retrieved from + the index and the workspace's recorded knowledge. spear-knowledge + is a command of the container. + v0.3.0 (8 oct 2026) First stable release of the 0.3 line: v0.3.0-rc1, below, with the fixes and diff --git a/client/cli/claude_context.py b/client/cli/claude_context.py new file mode 100644 index 0000000..68b28a4 --- /dev/null +++ b/client/cli/claude_context.py @@ -0,0 +1,256 @@ +"""What SPEAR adds to every request, handed to Claude Code the same way. + +SPEAR does not leave retrieval to the model: each request is searched in the +corpus index and shown with the knowledge recorded for the workspace. Claude +Code runs a hook on every prompt and reads what it prints, so the hook prints +that same text, built by the same functions: + + ## Retrieved Context corpus_search.retrieve_context, on the prompt + ## Workspace knowledge workspace_knowledge.select, on the prompt + +The embedder takes seconds to load, which a hook started afresh on each +prompt would pay each time. The MCP server of the session is already there +with it loaded, so it also answers on a socket (corpus_mcp --context-socket) +and the hook asks it; without a server, the hook does the work itself. + + spear-claude-context [--socket PATH] [--corpus NAME] the hook + spear-knowledge list | show | propose '' the records +""" + +from __future__ import annotations + +import json +import os +import shlex +import socket +import sys +import threading + +RETRIEVED_HEADER = "## Retrieved Context" +RETRIEVED_NOTE = ("Passages of the indexed corpus that match this request, each headed by " + "its path relative to the corpus root.") +ANSWER_TIMEOUT = 120 + + +def workspace(corpus, cwd, projects): + """(workspace id, root) as SPEAR names them: a registered corpus by its + name, any other tree by where it is.""" + if corpus and corpus in projects: + return corpus, os.path.realpath(projects[corpus]["path"]) + + root = os.path.realpath(cwd or ".") + + return f"adhoc:{root}", root + + +def retrieved(index, prompt, corpus): + """The retrieved passages of a prompt, or "" when the corpus has no index.""" + if index is None or not corpus or corpus not in index.names(): + return "" + + context = index.context(prompt, corpus) + + if not context or not context.strip(): + return "" + + return f"{RETRIEVED_HEADER}\n\n{RETRIEVED_NOTE}\n\n{context}" + + +def knowledge(prompt, workspace_id, root): + """The workspace's active records, selected for a prompt as a turn's are.""" + from context import workspace_knowledge + + store = workspace_knowledge.KnowledgeStore( + workspace_knowledge.default_path(), + common=workspace_knowledge.default_common_path()) + + try: + store.validate(workspace_id, root) + records = store.list(workspace_id, (workspace_knowledge.Lifecycle.ACTIVE,)) + + return workspace_knowledge.select(records, prompt).text.strip() + finally: + store.close() + + +def compose(index, prompt, corpus, cwd, projects): + """Everything a prompt is shown, as one text; "" when there is nothing.""" + parts = [] + + for part in (lambda: retrieved(index, prompt, corpus), + lambda: knowledge(prompt, *workspace(corpus, cwd, projects))): + try: + text = part() + except Exception as exc: + print(f"spear-claude-context: {type(exc).__name__}: {exc}", file=sys.stderr) + text = "" + + if text: + parts.append(text) + + return "\n\n".join(parts) + + +# ── the session's server answers the hook ──────────────────────────── + +def serve(index, path, projects): + """Answer the hook on a socket at `path`, from a thread, until the process + ends. One request per connection: a JSON object, then the text.""" + try: + os.unlink(path) + except OSError: + pass + + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + listener.bind(path) + os.chmod(path, 0o600) + listener.listen(4) + + def loop(): + while True: + connection, _ = listener.accept() + + with connection: + try: + request = json.loads(_read(connection)) + text = compose(index, str(request.get("prompt") or ""), + request.get("corpus"), request.get("cwd"), projects) + connection.sendall(text.encode("utf-8")) + except Exception as exc: + print(f"spear-claude-context: {type(exc).__name__}: {exc}", + file=sys.stderr) + + threading.Thread(target=loop, daemon=True).start() + + # The first question should not be the one that waits for the embedder. + + if index.default: + threading.Thread(target=lambda: index.context("warm up", index.default), + daemon=True).start() + + return listener + + +def _read(connection): + chunks = [] + + while True: + chunk = connection.recv(65536) + + if not chunk: + return b"".join(chunks).decode("utf-8") + + chunks.append(chunk) + + +def ask(path, request): + """The server's answer, or None when nobody answers at `path`.""" + try: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: + connection.settimeout(ANSWER_TIMEOUT) + connection.connect(path) + connection.sendall(json.dumps(request).encode("utf-8")) + connection.shutdown(socket.SHUT_WR) + + return _read(connection) + except OSError: + return None + + +# ── the commands ───────────────────────────────────────────────────── + +def _option(argv, flag): + return argv[argv.index(flag) + 1] if flag in argv[:-1] else None + + +def _alone(prompt, corpus, cwd): + from cli import corpus_mcp, corpus_registry + + projects = corpus_registry.load_projects() + index = None + + if corpus: + try: + index = corpus_mcp.CorpusIndex(corpus) + except Exception: + index = None + + return compose(index, prompt, corpus, cwd, projects) + + +def hook(argv, stdin, out): + """Claude Code's UserPromptSubmit hook: the event on stdin, the context on + stdout. It never fails a prompt: with nothing to add it prints nothing.""" + try: + event = json.loads(stdin.read() or "{}") + except ValueError: + event = {} + + prompt = str(event.get("prompt") or "").strip() + + if not prompt: + return 0 + + path, corpus = _option(argv, "--socket"), _option(argv, "--corpus") + request = {"prompt": prompt, "corpus": corpus, "cwd": event.get("cwd") or os.getcwd()} + text = ask(path, request) if path else None + + if text is None: + # The libraries under the search print; the hook's stdout is read as + # context, so it is kept for the result alone. + + saved = os.dup(1) + os.dup2(2, 1) + + try: + text = _alone(prompt, corpus, request["cwd"]) + except Exception as exc: + print(f"spear-claude-context: {type(exc).__name__}: {exc}", file=sys.stderr) + text = "" + finally: + sys.stdout.flush() + os.dup2(saved, 1) + os.close(saved) + + if text: + out.write(text + "\n") + out.flush() + + return 0 + + +def knowledge_command(argv, out): + """`spear-knowledge` as SPEAR's own turns have it, for the tree the + current directory is in.""" + from cli import corpus_registry + from context import workspace_knowledge + + projects = corpus_registry.load_projects() + workspace_id, _ = workspace(corpus_registry.detect_project(projects), os.getcwd(), projects) + store = workspace_knowledge.KnowledgeStore( + workspace_knowledge.default_path(), + common=workspace_knowledge.default_common_path()) + + try: + code, text = workspace_knowledge.Door(store, workspace_id).run( + shlex.join([workspace_knowledge.COMMAND, *argv])) + finally: + store.close() + + out.write(text + "\n") + + return code + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + + if argv[:1] == ["knowledge"]: + return knowledge_command(argv[1:], sys.stdout) + + return hook(argv, sys.stdin, sys.stdout) + + +if __name__ == "__main__": + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) + sys.exit(main()) diff --git a/client/cli/claude_export.py b/client/cli/claude_export.py index 3fc3b3f..7fb53ad 100644 --- a/client/cli/claude_export.py +++ b/client/cli/claude_export.py @@ -16,6 +16,14 @@ Only what applies to the named corpus is written; without --corpus, only what applies to every tree. A rule scoped to a path is left out: the tree it names is one of this machine, not of the reader's. + +What a SPEAR turn is shown beside rules.d goes along, each as a rule of its +own, so that both assistants start from the same text: + + spear.learned.md the rules learned on this machine + spear.corpus-map.md the corpus's map, the tree's own or the shipped one + spear.project.md what the project declares: identity, build, test + spear.knowledge-base.md what reaches a request by itself, and the tools """ from __future__ import annotations @@ -28,6 +36,7 @@ import time RULE_PREFIX = "spear-" +CORPUS_RULES_FILE = ".edgem-rules.md" DESCRIPTION_MAX = 300 @@ -98,6 +107,76 @@ def export_skills(skills, names): return files +def export_session(candidates): + """{path: text} for the candidates a turn gets beside rules.d, as + context_sources builds them: (file name, candidates) pairs.""" + files = {} + + for name, found in candidates: + text = "".join(item.text for item in found).strip() + + if text: + files[f".claude/rules/{name}"] = text + "\n" + + return files + + +def corpus_map(tree, root, corpus, shipped): + """(label, text) of the corpus's map as a turn finds it: the file the tree + carries, at the working directory then at the corpus root, else the one + shipped under the corpus's name.""" + seen = set() + + for where in (tree, root): + path = os.path.realpath(os.path.join(where, CORPUS_RULES_FILE)) if where else "" + + if not path or path in seen or not os.path.isfile(path): + continue + + seen.add(path) + + with open(path, "r", encoding="utf-8") as handle: + text = handle.read().strip() + + if text: + return os.path.basename(os.path.realpath(where)), text + + path = os.path.join(shipped, f"{corpus}.md") if corpus else "" + + if path and os.path.isfile(path): + with open(path, "r", encoding="utf-8") as handle: + text = handle.read().strip() + + if text: + return f"{corpus}, shipped", text + + return "", "" + + +def knowledge_base(corpus): + """The rule that says what this session shares with SPEAR and how it + arrives.""" + tree = f"the corpus `{corpus}`" if corpus else "this tree" + + return ( + "# Shared knowledge base\n\n" + f"This session works on {tree} with the knowledge base SPEAR uses for it: " + "the rules beside this one, the skills, the corpus index and the knowledge " + "recorded for the workspace.\n\n" + "- A request arrives with a `Retrieved Context` section when the corpus is " + "indexed: the passages that match it, each headed by its path relative to " + "the corpus root. Start from them; open the files they name rather than " + "searching the tree again.\n" + "- `search_corpus` (MCP server `spear-corpus`) searches the same index. Use " + "it for what the retrieved context does not cover, before grep or a walk " + "through the tree; `list_corpora` names what is indexed.\n" + "- A `Workspace knowledge` section carries what has been recorded about " + "this workspace. `spear-knowledge list` and `spear-knowledge show ` " + "print the records; `spear-knowledge propose ''` suggests one, with " + "`kind`, `subject` and `statement`, which is used only once the operator " + "accepts it.\n") + + def write_tar(files, out): now = time.time() @@ -133,16 +212,19 @@ def _option(argv, flag): def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) corpus, directory = _option(argv, "--corpus"), _option(argv, "--out") + tree = _option(argv, "--tree") or os.getcwd() if "-h" in argv or "--help" in argv: - print("usage: spear-claude-export [--corpus NAME] [--out DIR]", file=sys.stderr) + print("usage: spear-claude-export [--corpus NAME] [--tree DIR] [--out DIR]", + file=sys.stderr) return 2 from cli import corpus_registry - from cli.chat_settings import RULES_DIR, resource_dir - from context import skill_library + from cli.chat_settings import LEARNED_RULES_FILE, RULES_DIR, STATE_DIR, resource_dir + from context import context_sources, skill_library, workspace_context from context.workspace_context import project_families + from evidence import project_build projects = corpus_registry.load_projects() @@ -173,6 +255,24 @@ def main(argv=None): skills = skill_library.load_library(resource_dir("SPEAR_SKILLS_DIR", "skills")) files = {**export_rules(rules, names), **export_skills(skills, names)} + # The rest of what a turn starts from, read as a turn reads it. + + spec = projects.get(corpus) or {} + root = os.path.realpath(spec["path"]) if corpus else "" + commands = project_build.commands( + tree, spec=spec, cache_dir=f"{STATE_DIR}/projects/{corpus.replace('/', '_')}" + ) if corpus else None + here = workspace_context.from_session( + project=corpus or "", spec=spec, registered=bool(corpus), project_root=tree, + corpus_root=root or tree, project_commands=commands) + label, text = corpus_map(tree, root, corpus, os.path.join(RULES_DIR, "corpora")) + files.update(export_session(( + ("spear.learned.md", context_sources.learned_candidate(LEARNED_RULES_FILE)), + ("spear.corpus-map.md", context_sources.corpus_rule_candidates( + [(label, text, ())] if text else [])), + ("spear.project.md", context_sources.metadata_candidates(here))))) + files[".claude/rules/spear.knowledge-base.md"] = knowledge_base(corpus) + if directory: write_tree(files, directory) else: diff --git a/client/cli/corpus_mcp.py b/client/cli/corpus_mcp.py index f043976..c8b6312 100644 --- a/client/cli/corpus_mcp.py +++ b/client/cli/corpus_mcp.py @@ -11,6 +11,10 @@ ssh host docker run --rm -i --entrypoint spear-mcp IMAGE --corpus NAME +The one exception is local: with --context-socket PATH the server also +answers Claude Code's prompt hook on a socket of this machine, private to the +user (cli/claude_context.py). + Two tools: `list_corpora` and `search_corpus`. Paths in a result are relative to the root of the corpus that was asked for, which is how the client's own checkout names the same files. @@ -21,6 +25,7 @@ import json import os import sys +import threading SERVER_NAME = "spear-corpus" @@ -91,6 +96,7 @@ def __init__(self, default=None): self._projects = corpus_registry.load_projects() self._client = corpus_search._db() self._collections = {} + self._lock = threading.Lock() self.default = default def _collection(self, name): @@ -151,6 +157,27 @@ def search(self, query, corpus=None, top_k=TOP_K): raise ToolError(f"no indexed corpus named '{name}'; " f"list_corpora names the ones there are") + with self._lock: + context, _ = self._search.retrieve_context(self._corpora(name), query, top_k) + + if not context or not context.strip(): + return "(no match)" + + if len(context) > MAX_CHARS: + context = context[:MAX_CHARS] + "\n… (truncated; ask a narrower query)" + + return context + + def context(self, query, name): + """What a SPEAR turn retrieves for a request, unasked: the corpus and + the ones attached to it, at the breadth a turn uses.""" + with self._lock: + context, _ = self._search.retrieve_context(self._corpora(name), query) + + return context + + def _corpora(self, name): + """(collection, path prefix) for a corpus and the ones searched with it.""" root = os.path.realpath(self._projects[name]["path"]) corpora = [(self._collection(name), "")] @@ -160,15 +187,7 @@ def search(self, query, corpus=None, top_k=TOP_K): corpora.append((self._collection(other), os.path.relpath(path, root) if inside else path)) - context, _ = self._search.retrieve_context(corpora, query, top_k) - - if not context or not context.strip(): - return "(no match)" - - if len(context) > MAX_CHARS: - context = context[:MAX_CHARS] + "\n… (truncated; ask a narrower query)" - - return context + return corpora def call_tool(index, name, arguments): @@ -321,6 +340,12 @@ def main(argv=None): return 2 + if "--context-socket" in argv[:-1]: + from cli import claude_context + + claude_context.serve(index, argv[argv.index("--context-socket") + 1], + index._projects) + serve(index, sys.stdin, out) return 0 diff --git a/client/tests/test_claude_context.py b/client/tests/test_claude_context.py new file mode 100644 index 0000000..9f79689 --- /dev/null +++ b/client/tests/test_claude_context.py @@ -0,0 +1,151 @@ +"""What a prompt of Claude Code is given: the text of a SPEAR turn, by a hook.""" + +from __future__ import annotations + +import io +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +from cli import claude_context # noqa: E402 +from context import workspace_knowledge # noqa: E402 + + +class FakeIndex: + default = "alpha" + + def __init__(self, context="# File: src/a.c\nint a;"): + self.asked, self._context = [], context + + def names(self): + return ["alpha"] + + def context(self, query, name): + self.asked.append((query, name)) + + return self._context + + +class Base(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp() + self.db = os.path.join(self.dir, "knowledge.sqlite3") + self.projects = {"alpha": {"path": self.dir}} + patch = mock.patch.dict(os.environ, {"SPEAR_KNOWLEDGE_DB": self.db}) + patch.start() + self.addCleanup(patch.stop) + + def record(self, workspace_id, statement): + store = workspace_knowledge.KnowledgeStore(self.db) + store.add(workspace_id, kind=workspace_knowledge.Kind.PROJECT_FACT, subject="modem", + statement=statement, provenance=workspace_knowledge.Provenance.USER_CONFIRMED) + store.close() + + +class WhatAPromptIsShown(Base): + def test_the_passages_retrieved_for_it_and_the_workspaces_knowledge(self): + self.record("alpha", "The modem is on UART2.") + index = FakeIndex() + + text = claude_context.compose(index, "where is a?", "alpha", self.dir, self.projects) + + self.assertEqual(index.asked, [("where is a?", "alpha")]) + self.assertIn(claude_context.RETRIEVED_HEADER, text) + self.assertIn("# File: src/a.c", text) + self.assertIn("## Workspace knowledge", text) + self.assertIn("The modem is on UART2.", text) + + def test_nothing_from_a_corpus_that_has_no_index(self): + index = FakeIndex() + + self.assertEqual( + claude_context.compose(index, "q", "beta", self.dir, {"beta": {"path": self.dir}}), + "") + self.assertEqual(index.asked, []) + + def test_a_tree_nobody_registered_is_known_by_where_it_is(self): + root = os.path.realpath(self.dir) + self.record(f"adhoc:{root}", "Built with ninja.") + + text = claude_context.compose(None, "how is it built?", None, self.dir, {}) + + self.assertIn("Built with ninja.", text) + self.assertNotIn(claude_context.RETRIEVED_HEADER, text) + + def test_a_search_that_fails_leaves_the_knowledge(self): + self.record("alpha", "The modem is on UART2.") + index = FakeIndex() + index.context = mock.Mock(side_effect=RuntimeError("index gone")) + + with mock.patch("sys.stderr", io.StringIO()): + text = claude_context.compose(index, "q", "alpha", self.dir, self.projects) + + self.assertIn("The modem is on UART2.", text) + + +class TheHook(Base): + def run_hook(self, argv, event): + out = io.StringIO() + code = claude_context.hook(argv, io.StringIO(json.dumps(event)), out) + + return code, out.getvalue() + + def test_it_asks_the_sessions_server_and_prints_its_answer(self): + path = os.path.join(self.dir, "socket") + index = FakeIndex() + listener = claude_context.serve(index, path, self.projects) + self.addCleanup(listener.close) + + code, text = self.run_hook(["--socket", path, "--corpus", "alpha"], + {"prompt": "where is a?", "cwd": self.dir}) + + self.assertEqual(code, 0) + self.assertIn("# File: src/a.c", text) + self.assertIn(("where is a?", "alpha"), index.asked) + self.assertEqual(os.stat(path).st_mode & 0o777, 0o600) + + def test_without_a_server_it_does_the_work_itself(self): + with mock.patch.object(claude_context, "_alone", return_value="the context") as alone: + code, text = self.run_hook(["--socket", os.path.join(self.dir, "nobody"), + "--corpus", "alpha"], + {"prompt": "q", "cwd": self.dir}) + + self.assertEqual((code, text), (0, "the context\n")) + alone.assert_called_once_with("q", "alpha", self.dir) + + def test_it_never_fails_a_prompt(self): + with mock.patch.object(claude_context, "_alone", side_effect=RuntimeError("broken")), \ + mock.patch("sys.stderr", io.StringIO()): + self.assertEqual(self.run_hook([], {"prompt": "q", "cwd": self.dir}), (0, "")) + + self.assertEqual(self.run_hook([], {"prompt": " "}), (0, "")) + self.assertEqual(claude_context.hook([], io.StringIO("not json"), io.StringIO()), 0) + + +class TheKnowledgeCommand(Base): + def test_it_reads_and_proposes_for_the_tree_it_is_run_in(self): + root = os.path.realpath(self.dir) + self.record(f"adhoc:{root}", "Built with ninja.") + out = io.StringIO() + + with mock.patch("os.getcwd", return_value=root), \ + mock.patch("cli.corpus_registry.load_projects", return_value={}): + listed = claude_context.knowledge_command(["list"], out) + proposed = claude_context.knowledge_command( + ["propose", json.dumps({"subject": "flash", "statement": "Flashed over USB."})], + out) + + self.assertEqual((listed, proposed), (0, 0)) + self.assertIn("Built with ninja.", out.getvalue()) + self.assertIn("proposed", out.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/client/tests/test_claude_export.py b/client/tests/test_claude_export.py index 7a9f80e..863c803 100644 --- a/client/tests/test_claude_export.py +++ b/client/tests/test_claude_export.py @@ -3,8 +3,10 @@ from __future__ import annotations import io +import os import sys import tarfile +import tempfile import unittest from pathlib import Path @@ -12,7 +14,7 @@ sys.path.insert(0, str(ROOT)) from cli import claude_export # noqa: E402 -from context import skill_library # noqa: E402 +from context import context_sources, skill_library # noqa: E402 RULES = { "10-global.md": "---\nscope: global\npaths: doc/**, src/**\n---\nAlways build before you claim.", @@ -99,6 +101,61 @@ def test_a_long_description_is_cut(self): self.assertLessEqual(len(line), len('description: ""') + claude_export.DESCRIPTION_MAX) +class WhatATurnStartsFromBesideTheRules(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp() + self.tree = os.path.join(self.dir, "tree") + self.shipped = os.path.join(self.dir, "corpora") + os.makedirs(self.tree) + os.makedirs(self.shipped) + + def write(self, path, text): + with open(path, "w", encoding="utf-8") as handle: + handle.write(text) + + def test_the_map_is_the_trees_own_before_the_shipped_one(self): + self.write(os.path.join(self.shipped, "alpha.md"), "Shipped map.") + + self.assertEqual( + claude_export.corpus_map(self.tree, self.tree, "alpha", self.shipped), + ("alpha, shipped", "Shipped map.")) + + self.write(os.path.join(self.tree, claude_export.CORPUS_RULES_FILE), "Its own map.") + + self.assertEqual( + claude_export.corpus_map(self.tree, self.tree, "alpha", self.shipped), + ("tree", "Its own map.")) + + def test_a_tree_without_a_map_gets_none(self): + self.assertEqual(claude_export.corpus_map(self.tree, "", None, self.shipped), ("", "")) + + def test_the_map_file_is_the_one_a_turn_reads(self): + from cli import turn_context + + self.assertEqual(claude_export.CORPUS_RULES_FILE, turn_context.CORPUS_RULES_FILE) + + def test_each_source_is_a_rule_file_holding_the_text_a_turn_is_shown(self): + learned = os.path.join(self.dir, "rules-learned.md") + self.write(learned, "Never push to main.") + found = context_sources.learned_candidate(learned) + + files = claude_export.export_session(( + ("spear.learned.md", found), + ("spear.corpus-map.md", context_sources.corpus_rule_candidates([])))) + + self.assertEqual(list(files), [".claude/rules/spear.learned.md"]) + self.assertEqual(files[".claude/rules/spear.learned.md"], found[0].text.strip() + "\n") + + def test_the_guide_names_what_arrives_and_the_tools(self): + text = claude_export.knowledge_base("alpha") + + for word in ("`alpha`", "Retrieved Context", "search_corpus", "Workspace knowledge", + "spear-knowledge"): + self.assertIn(word, text) + + self.assertIn("this tree", claude_export.knowledge_base(None)) + + class Archive(unittest.TestCase): def test_the_tar_holds_every_file(self): out = io.BytesIO() diff --git a/client/tests/test_reds_image.py b/client/tests/test_reds_image.py index 2ad9c0e..b395a71 100644 --- a/client/tests/test_reds_image.py +++ b/client/tests/test_reds_image.py @@ -528,6 +528,20 @@ def test_install_removes_the_launcher_under_its_former_name(self): self.assertFalse(former.exists()) self.assertTrue((Path(tmp) / ".local/bin/spear").exists()) + def test_the_image_gives_a_prompt_of_the_other_assistant_what_a_turn_gets(self): + harness = (REPO / "docker" / "Dockerfile.harness").read_text() + launcher = (REPO / "docker" / "claude-launcher").read_text() + + for command in ("spear-claude-context", "spear-knowledge"): + self.assertIn(f"docker/{command}", harness) + self.assertIn(f"/usr/local/bin/{command}", harness) + self.assertTrue(os.access(REPO / "docker" / command, os.X_OK)) + + self.assertIn('"UserPromptSubmit"', launcher) + self.assertIn('spear-claude-context --socket $SOCKET', launcher) + self.assertIn('--context-socket "$SOCKET"', launcher) + self.assertIn('--settings "$SETTINGS"', launcher) + def test_the_image_carries_it(self): dockerfile = (REPO / "docker" / "Dockerfile").read_text() diff --git a/doc/source/start/container_run.rst b/doc/source/start/container_run.rst index 156e1f3..d980add 100644 --- a/doc/source/start/container_run.rst +++ b/doc/source/start/container_run.rst @@ -187,6 +187,32 @@ container reaches it through an SSH tunnel you open on your machine. and the corpus index is its ``spear-corpus`` MCP server (:ref:`mcp_server`). + It works from the knowledge base ``spear-chat`` works from, and gets it + the same way: + + .. list-table:: + :header-rows: 1 + :widths: 34 66 + + * - What a SPEAR request starts from + - How Claude Code gets it + * - the rules of ``rules.d`` that apply to the corpus, the rules + learned with ``/recall``, the corpus's map, the project's + identity and its build and test commands + - rule files in ``~/.claude/rules``, loaded with every session + * - the skills whose scope covers the corpus + - ``~/.claude/skills``, offered by their description + * - the passages retrieved from the index for the request + - printed by a hook on every prompt; ``search_corpus`` searches + further + * - the knowledge recorded for the workspace + - printed by the same hook; ``spear-knowledge`` lists the + records and proposes new ones + + Retrieval is not left to the model's choice in either: the hook runs + SPEAR's own search on each prompt. ``/memory``, ``/skills`` and + ``/mcp`` show, inside Claude Code, what a session was given. + An image gains Claude Code as one more layer, once it is built: .. code-block:: console diff --git a/docker/Dockerfile.harness b/docker/Dockerfile.harness index 55770ed..d69438a 100644 --- a/docker/Dockerfile.harness +++ b/docker/Dockerfile.harness @@ -102,11 +102,13 @@ COPY --from=repo docker/spear-claude-export /usr/local/bin/spear-claude-export # adds the program itself to the images that are to carry it. COPY --from=repo docker/spear-shell docker/spear-chat docker/spear-where \ - docker/spear-bake-state /usr/local/bin/ + docker/spear-bake-state docker/spear-claude-context docker/spear-knowledge \ + /usr/local/bin/ COPY --from=repo docker/claude-launcher /usr/local/bin/claude RUN chmod +x /opt/spear/entrypoint.sh /opt/spear/spear /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/spear-bake-state /usr/local/bin/claude + /usr/local/bin/spear-where /usr/local/bin/spear-bake-state /usr/local/bin/claude \ + /usr/local/bin/spear-claude-context /usr/local/bin/spear-knowledge ENV SPEAR_COMMON_STATE_DIR=/opt/spear/common ENV SPEAR_STANDARDS_ROOT=/opt/spear/common/standards diff --git a/docker/claude-launcher b/docker/claude-launcher index 3e1825f..b39ca14 100755 --- a/docker/claude-launcher +++ b/docker/claude-launcher @@ -1,7 +1,9 @@ #!/bin/bash # Claude Code on this image's corpora, installed as `claude`: the rules and # skills of the corpus the current directory is in are laid out where it reads -# them, the corpus index is its MCP server, and it starts. +# them, the corpus index is its MCP server, and it starts. Each prompt then +# gets what a SPEAR request gets by itself, through a hook: the passages +# retrieved from the index and the workspace's recorded knowledge. # # Everything is written under HOME, never in the tree: a checkout bound into # the container stays as git left it. HOME is expected to outlive the @@ -45,7 +47,19 @@ trap - EXIT # The index is registered for the user, so it is there whatever follows on # the command line. +# The hook asks the session's MCP server, which has the embedder loaded, on +# a socket of this session's own. + +SOCKET="$(mktemp -u "${TMPDIR:-/tmp}/spear-context-XXXXXX")" +SETTINGS="$SOCKET.json" + +cat > "$SETTINGS" </dev/null 2>&1 || true -"$REAL" mcp add --scope user spear-corpus -- spear-mcp ${CORPUS:+--corpus "$CORPUS"} >/dev/null +"$REAL" mcp add --scope user spear-corpus -- spear-mcp ${CORPUS:+--corpus "$CORPUS"} \ + --context-socket "$SOCKET" >/dev/null -exec "$REAL" "$@" +exec "$REAL" --settings "$SETTINGS" "$@" diff --git a/docker/spear-claude-context b/docker/spear-claude-context new file mode 100755 index 0000000..7a8fa13 --- /dev/null +++ b/docker/spear-claude-context @@ -0,0 +1,6 @@ +#!/bin/bash +# Claude Code's prompt hook in this image: what SPEAR adds to a request by +# itself -- the passages retrieved from the corpus index and the workspace's +# recorded knowledge -- printed for the prompt read on stdin. + +exec /opt/spear/client/bin/python /opt/spear/client/cli/claude_context.py "$@" diff --git a/docker/spear-knowledge b/docker/spear-knowledge new file mode 100755 index 0000000..b754fad --- /dev/null +++ b/docker/spear-knowledge @@ -0,0 +1,9 @@ +#!/bin/bash +# The knowledge recorded for the tree the current directory is in: +# +# spear-knowledge list | show | propose '' +# +# SPEAR answers this command itself inside its own turns; here it is a +# program, so that any other assistant in the container reads the same store. + +exec /opt/spear/client/bin/python /opt/spear/client/cli/claude_context.py knowledge "$@" From 9a8d5e2a18ca3ce30582d06248236985b4ab3bef Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 21 Nov 2026 11:03:44 +0100 Subject: [PATCH 2/2] Carry what a user learns into the image, for every client The hook that gives a prompt its retrieved passages and the workspace's knowledge is now declared by the image itself, so the second assistant gets it however it is started, from a terminal or from an editor attached to the container. One server per user answers it; it takes the corpus from the directory of the request. What it prints stays under the size that is read in full: knowledge first, then the passages that fit. Preparing the home (rules, skills, the index's server) is a command of its own, run by the shell at its start as well as by the launcher, and the container gets a name that says what it is. In a container a saved skill was written into the image's library, which the user cannot write: it now goes to the state directory, over the shipped library. Building an image from the state adds the saved skills and the learned rules to the registry, index and knowledge it already took. That build changed the mode of every file of the index and of the common state, which copied all of them into the new layer; only a file that lacks the mode is touched now. --- CHANGELOG | 11 ++- client/cli/bake_state.py | 69 +++++++++++++++- client/cli/claude_context.py | 124 +++++++++++++++++++--------- client/cli/claude_export.py | 3 +- client/cli/corpus_mcp.py | 20 +++-- client/cli/corpus_registry.py | 4 +- client/cli/knowledge_commands.py | 18 ++-- client/cli/rag_chat.py | 4 +- client/context/skill_library.py | 40 +++++++++ client/tests/test_bake_state.py | 82 +++++++++++++++++- client/tests/test_claude_context.py | 59 ++++++++++--- client/tests/test_reds_image.py | 19 +++-- client/tests/test_skill_library.py | 43 ++++++++++ doc/source/start/container_run.rst | 24 +++++- docker/Dockerfile.harness | 6 +- docker/claude-launcher | 66 ++------------- docker/claude-managed-settings.json | 15 ++++ docker/spear-claude-setup | 50 +++++++++++ docker/spear-shell | 5 ++ scripts/docker/spear | 6 +- 20 files changed, 525 insertions(+), 143 deletions(-) create mode 100644 docker/claude-managed-settings.json create mode 100755 docker/spear-claude-setup diff --git a/CHANGELOG b/CHANGELOG index 9776510..0eee1a0 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -22,8 +22,15 @@ Unreleased from: beside the rules and skills, the learned rules, the corpus's map and the project's build and test commands are laid out as rule files, and a hook gives every prompt the passages retrieved from - the index and the workspace's recorded knowledge. spear-knowledge - is a command of the container. + the index and the workspace's recorded knowledge. The hook is the + image's, so an editor attached to the container gets it too. + spear-knowledge is a command of the container. + + • In a container a saved skill goes to the state directory, over the + image's library, instead of being lost with the container. spear + --build also writes the saved skills and the learned rules into the + new image, and no longer copies the files of the image it starts + from into the new layer. v0.3.0 (8 oct 2026) diff --git a/client/cli/bake_state.py b/client/cli/bake_state.py index d24fe06..ac25bdc 100644 --- a/client/cli/bake_state.py +++ b/client/cli/bake_state.py @@ -8,6 +8,8 @@ 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 + the skills that were saved -> the image's skills + the rules that were learned -> a rule of the image, for every tree Run as root in a container of the image, with the state mounted; the launcher then commits that container (spear --build). @@ -120,6 +122,59 @@ def bake_knowledge(source, target, schema, active): return len(rows) +def bake_skills(source, target): + """Copy the user's skills over the image's; their names.""" + if not os.path.isdir(source): + return [] + + os.makedirs(target, exist_ok=True) + names = sorted(name for name in os.listdir(source) if name.endswith(".md")) + + for name in names: + shutil.copyfile(os.path.join(source, name), os.path.join(target, name)) + + return [name[:-3] for name in names] + + +LEARNED_RULE = "90-learned-shared.md" +LEARNED_HEADER = "---\nscope: global\ntasks: implementation, mixed, general\n---\n" + + +def bake_learned_rules(source, rules_dir): + """Add the rules the user taught to the image's rule of learned ones, which + reaches the turns a learned rule reaches; how many were new.""" + try: + with open(source, encoding="utf-8") as handle: + taught = [line.rstrip() for line in handle if line.strip()] + except OSError: + return 0 + + path, kept = os.path.join(rules_dir, LEARNED_RULE), [] + + if os.path.isfile(path): + with open(path, encoding="utf-8") as handle: + kept = [line.rstrip() for line in handle.read().split("---\n")[-1].splitlines() + if line.strip()] + + new = [line for line in taught if line not in kept] + + if new: + os.makedirs(rules_dir, exist_ok=True) + + with open(path, "w", encoding="utf-8") as handle: + handle.write(LEARNED_HEADER + "\n".join(kept + new) + "\n") + + return len(new) + + +def _open(path, mode): + """Give everyone `mode` on a path that lacks some of it.""" + held = os.stat(path).st_mode & 0o777 + + if held & mode != mode: + os.chmod(path, held | mode) + + def _read(path): try: with open(path) as handle: @@ -188,14 +243,22 @@ def main(argv=None): print(f" knowledge {records} active records") - # The image is run as whoever launches it. + from cli.chat_settings import RULES_DIR, resource_dir + + skills = bake_skills(f"{state}/skills", resource_dir("SPEAR_SKILLS_DIR", "skills")) + print(f" skills {len(skills)} added" + (f": {', '.join(skills)}" if skills else "")) + print(f" rules {bake_learned_rules(f'{state}/rules-learned.md', RULES_DIR)} learned") + + # The image is run as whoever launches it. Only what is not open yet is + # touched: changing a file's mode copies it into the new layer, and the + # index of an image is most of its size. for root in filter(None, (chat_settings.SHIPPED_DB_PATH, str(common or ""))): for directory, _, files in os.walk(root): - os.chmod(directory, 0o777) + _open(directory, 0o777) for name in files: - os.chmod(os.path.join(directory, name), 0o666) + _open(os.path.join(directory, name), 0o666) return 0 diff --git a/client/cli/claude_context.py b/client/cli/claude_context.py index 68b28a4..06a004b 100644 --- a/client/cli/claude_context.py +++ b/client/cli/claude_context.py @@ -10,10 +10,15 @@ The embedder takes seconds to load, which a hook started afresh on each prompt would pay each time. The MCP server of the session is already there -with it loaded, so it also answers on a socket (corpus_mcp --context-socket) -and the hook asks it; without a server, the hook does the work itself. +with it loaded, so it also answers on a socket (corpus_mcp --context) and the +hook asks it; without a server, the hook does the work itself. - spear-claude-context [--socket PATH] [--corpus NAME] the hook +The hook is declared for the whole image (docker/claude-managed-settings.json), +so it runs for every client of Claude Code there, a terminal or an editor. +What it prints is kept under the size Claude Code reads in full: passages are +left out from the end, never cut, and `search_corpus` finds the rest. + + spear-claude-context the hook spear-knowledge list | show | propose '' the records """ @@ -24,13 +29,26 @@ import shlex import socket import sys +import tempfile import threading +import time RETRIEVED_HEADER = "## Retrieved Context" RETRIEVED_NOTE = ("Passages of the indexed corpus that match this request, each headed by " "its path relative to the corpus root.") ANSWER_TIMEOUT = 120 +#: Claude Code shows a hook's output in full up to 10 000 characters, and only +#: its beginning past that. +OUTPUT_CHARS = 9500 +SEPARATOR = "\n\n---\n\n" +TAKEOVER_SECONDS = 20 + + +def socket_path(): + """Where a user's session server answers the hook.""" + return os.path.join(tempfile.gettempdir(), f"spear-context-{os.getuid()}.sock") + def workspace(corpus, cwd, projects): """(workspace id, root) as SPEAR names them: a registered corpus by its @@ -43,8 +61,9 @@ def workspace(corpus, cwd, projects): return f"adhoc:{root}", root -def retrieved(index, prompt, corpus): - """The retrieved passages of a prompt, or "" when the corpus has no index.""" +def retrieved(index, prompt, corpus, room): + """The retrieved passages of a prompt that fit in `room` characters, or "" + when the corpus has no index.""" if index is None or not corpus or corpus not in index.names(): return "" @@ -53,7 +72,17 @@ def retrieved(index, prompt, corpus): if not context or not context.strip(): return "" - return f"{RETRIEVED_HEADER}\n\n{RETRIEVED_NOTE}\n\n{context}" + text = f"{RETRIEVED_HEADER}\n\n{RETRIEVED_NOTE}\n" + kept = 0 + + for passage in context.split(SEPARATOR): + if len(text) + len(SEPARATOR) + len(passage) > room: + break + + text += (SEPARATOR if kept else "\n") + passage + kept += 1 + + return text if kept else "" def knowledge(prompt, workspace_id, root): @@ -73,12 +102,17 @@ def knowledge(prompt, workspace_id, root): store.close() -def compose(index, prompt, corpus, cwd, projects): - """Everything a prompt is shown, as one text; "" when there is nothing.""" +def compose(index, prompt, cwd, projects): + """Everything a prompt is shown, as one text; "" when there is nothing. + The knowledge comes first: it is short, and what is cut is retrieval.""" + from cli import corpus_registry + + corpus = corpus_registry.detect_project(projects, cwd) parts = [] - for part in (lambda: retrieved(index, prompt, corpus), - lambda: knowledge(prompt, *workspace(corpus, cwd, projects))): + for part in (lambda: knowledge(prompt, *workspace(corpus, cwd, projects)), + lambda: retrieved(index, prompt, corpus, + OUTPUT_CHARS - sum(len(text) + 2 for text in parts))): try: text = part() except Exception as exc: @@ -93,33 +127,52 @@ def compose(index, prompt, corpus, cwd, projects): # ── the session's server answers the hook ──────────────────────────── -def serve(index, path, projects): - """Answer the hook on a socket at `path`, from a thread, until the process - ends. One request per connection: a JSON object, then the text.""" - try: - os.unlink(path) - except OSError: - pass +def serve(index, projects, path=None): + """Answer the hook on the user's socket, from a thread, until the process + ends. One request per connection: a JSON object, then the text. - listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - listener.bind(path) - os.chmod(path, 0o600) - listener.listen(4) + One server answers for all the sessions of a user: a second one waits, and + takes over when the first is gone. + """ + path = path or socket_path() - def loop(): + def answer(listener): while True: connection, _ = listener.accept() with connection: try: request = json.loads(_read(connection)) - text = compose(index, str(request.get("prompt") or ""), - request.get("corpus"), request.get("cwd"), projects) + prompt = str(request.get("prompt") or "") + + # No prompt: another server asking whether this one lives. + + text = compose(index, prompt, request.get("cwd"), projects) if prompt else "" connection.sendall(text.encode("utf-8")) except Exception as exc: print(f"spear-claude-context: {type(exc).__name__}: {exc}", file=sys.stderr) + def loop(): + while ask(path, {}) is not None: + time.sleep(TAKEOVER_SECONDS) + + try: + os.unlink(path) + except OSError: + pass + + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + + try: + listener.bind(path) + except OSError: + return + + os.chmod(path, 0o600) + listener.listen(4) + answer(listener) + threading.Thread(target=loop, daemon=True).start() # The first question should not be the one that waits for the embedder. @@ -128,8 +181,6 @@ def loop(): threading.Thread(target=lambda: index.context("warm up", index.default), daemon=True).start() - return listener - def _read(connection): chunks = [] @@ -163,19 +214,17 @@ def _option(argv, flag): return argv[argv.index(flag) + 1] if flag in argv[:-1] else None -def _alone(prompt, corpus, cwd): +def _alone(prompt, cwd): from cli import corpus_mcp, corpus_registry projects = corpus_registry.load_projects() - index = None - if corpus: - try: - index = corpus_mcp.CorpusIndex(corpus) - except Exception: - index = None + try: + index = corpus_mcp.CorpusIndex() + except Exception: + index = None - return compose(index, prompt, corpus, cwd, projects) + return compose(index, prompt, cwd, projects) def hook(argv, stdin, out): @@ -191,9 +240,8 @@ def hook(argv, stdin, out): if not prompt: return 0 - path, corpus = _option(argv, "--socket"), _option(argv, "--corpus") - request = {"prompt": prompt, "corpus": corpus, "cwd": event.get("cwd") or os.getcwd()} - text = ask(path, request) if path else None + request = {"prompt": prompt, "cwd": event.get("cwd") or os.getcwd()} + text = ask(_option(argv, "--socket") or socket_path(), request) if text is None: # The libraries under the search print; the hook's stdout is read as @@ -203,7 +251,7 @@ def hook(argv, stdin, out): os.dup2(2, 1) try: - text = _alone(prompt, corpus, request["cwd"]) + text = _alone(prompt, request["cwd"]) except Exception as exc: print(f"spear-claude-context: {type(exc).__name__}: {exc}", file=sys.stderr) text = "" diff --git a/client/cli/claude_export.py b/client/cli/claude_export.py index 7fb53ad..dfc42f2 100644 --- a/client/cli/claude_export.py +++ b/client/cli/claude_export.py @@ -252,7 +252,8 @@ def main(argv=None): with open(path, "r", encoding="utf-8") as handle: rules[fname] = handle.read() - skills = skill_library.load_library(resource_dir("SPEAR_SKILLS_DIR", "skills")) + shipped = resource_dir("SPEAR_SKILLS_DIR", "skills") + skills = skill_library.load_layered(shipped, skill_library.own_directory(shipped, STATE_DIR)) files = {**export_rules(rules, names), **export_skills(skills, names)} # The rest of what a turn starts from, read as a turn reads it. diff --git a/client/cli/corpus_mcp.py b/client/cli/corpus_mcp.py index c8b6312..908d850 100644 --- a/client/cli/corpus_mcp.py +++ b/client/cli/corpus_mcp.py @@ -11,9 +11,9 @@ ssh host docker run --rm -i --entrypoint spear-mcp IMAGE --corpus NAME -The one exception is local: with --context-socket PATH the server also -answers Claude Code's prompt hook on a socket of this machine, private to the -user (cli/claude_context.py). +The one exception is local: with --context the server also answers Claude +Code's prompt hook on a socket of this machine, private to the user +(cli/claude_context.py). Two tools: `list_corpora` and `search_corpus`. Paths in a result are relative to the root of the corpus that was asked for, which is how the client's own @@ -340,11 +340,19 @@ def main(argv=None): return 2 - if "--context-socket" in argv[:-1]: + # Nobody named a corpus: the one the server was started in, if it is + # indexed, so that one registration serves whatever tree a session opens. + + if not default: + from cli import corpus_registry + + here = corpus_registry.detect_project(index._projects) + index.default = here if here in index.names() else None + + if "--context" in argv: from cli import claude_context - claude_context.serve(index, argv[argv.index("--context-socket") + 1], - index._projects) + claude_context.serve(index, index._projects) serve(index, sys.stdin, out) diff --git a/client/cli/corpus_registry.py b/client/cli/corpus_registry.py index cc2211e..49d76a6 100644 --- a/client/cli/corpus_registry.py +++ b/client/cli/corpus_registry.py @@ -174,9 +174,9 @@ def save_projects(projects): f"reached with --corpora instead.") from exc -def detect_project(projects): +def detect_project(projects, cwd=None): """Project whose path contains the cwd, or None.""" - cwd = os.path.realpath(os.getcwd()) + cwd = os.path.realpath(cwd or os.getcwd()) best = None for name, spec in projects.items(): diff --git a/client/cli/knowledge_commands.py b/client/cli/knowledge_commands.py index a0cf5c3..8cb0a09 100644 --- a/client/cli/knowledge_commands.py +++ b/client/cli/knowledge_commands.py @@ -7,7 +7,7 @@ from context.memory_store import MemoryStoreError from runtime.tracing import EventStatus, EventType from cli import session_workspace -from cli.chat_settings import TRACE, resource_dir +from cli.chat_settings import STATE_DIR, TRACE, resource_dir from cli.corpus_registry import load_projects from cli.session_workspace import confirm @@ -18,22 +18,28 @@ # the most similar skills are injected into the prompt on each turn. SKILLS_DIR = resource_dir("SPEAR_SKILLS_DIR", "skills") +OWN_SKILLS_DIR = skill_library.own_directory(SKILLS_DIR, STATE_DIR) + + +def load_skills(): + """The library a session works from: the shipped skills and the user's.""" + return skill_library.load_layered(SKILLS_DIR, OWN_SKILLS_DIR) def skill_save(name, content, description="", scope=(), requires=()): """Write a skill file. Returns a result message.""" try: - skill = skill_library.save(SKILLS_DIR, name, content, - description=description, scope=scope, - requires=requires) + skill = skill_library.save_layered(SKILLS_DIR, OWN_SKILLS_DIR, name, content, + description=description, scope=scope, + requires=requires) except skill_library.SkillError as exc: return f"ERROR: {exc}" revised = f", revision {skill.version}" if skill.version > 1 else "" return (f"OK: skill '{skill.name}' saved{revised} " - f"({len(skill_library.load_library(SKILLS_DIR))} skills in library)") + f"({len(load_skills())} skills in library)") def library_skills(): @@ -47,7 +53,7 @@ def library_skills(): out, as it always was. """ return [(skill.name, skill.document, skill.scope if skill.scope_declared else ()) - for skill in skill_library.load_library(SKILLS_DIR) + for skill in load_skills() if not skill_library.missing_requirements(skill)] diff --git a/client/cli/rag_chat.py b/client/cli/rag_chat.py index b52cdd2..62371f5 100755 --- a/client/cli/rag_chat.py +++ b/client/cli/rag_chat.py @@ -68,7 +68,7 @@ retrieve_context, ) from cli.knowledge_commands import ( - SKILLS_DIR, current_workspace, knowledge_command, knowledge_store, + SKILLS_DIR, current_workspace, knowledge_command, knowledge_store, load_skills, legacy_notes_notice, library_skills, remember_fact, ) from cli.model_io import ( @@ -552,7 +552,7 @@ def read_user_input(): continue if user_input == "/skills": - skills = skill_library.load_library(SKILLS_DIR) + skills = load_skills() if not skills: print("(no skills yet — the model saves them after " diff --git a/client/context/skill_library.py b/client/context/skill_library.py index 8d30402..4d49d15 100644 --- a/client/context/skill_library.py +++ b/client/context/skill_library.py @@ -219,6 +219,46 @@ def load_library(directory: str) -> list[Skill]: return skills +def own_directory(shipped: str, state_dir: str) -> str | None: + """Where skills are saved when the library is not the user's to write: an + image ships it, and what a session learns there goes to the state + directory instead. None when the library itself can be written.""" + + if not os.path.isdir(shipped) or os.access(shipped, os.W_OK): + return None + + return os.path.join(state_dir, "skills") + + +def load_layered(shipped: str, own: str | None = None) -> list[Skill]: + """The shipped library with the user's own over it, by name: a skill the + user saved again answers for the shipped one.""" + + skills = {skill.name: skill for skill in load_library(shipped)} + + if own: + skills.update({skill.name: skill for skill in load_library(own)}) + + return [skills[name] for name in sorted(skills)] + + +def save_layered(shipped: str, own: str | None, name: str, content: str, **details) -> Skill: + """`save` into the user's layer when there is one. A shipped skill saved + again starts from the shipped file, so its history carries over.""" + + if not own: + return save(shipped, name, content, **details) + + filename = f"{normalize_name(name)}.md" + source, target = os.path.join(shipped, filename), os.path.join(own, filename) + + if os.path.isfile(source) and not os.path.exists(target): + os.makedirs(own, exist_ok=True) + shutil.copyfile(source, target) + + return save(own, name, content, **details) + + def missing_requirements(skill: Skill, *, which=shutil.which) -> tuple[str, ...]: """Declared commands this machine does not have. diff --git a/client/tests/test_bake_state.py b/client/tests/test_bake_state.py index 29ba01a..0e392df 100644 --- a/client/tests/test_bake_state.py +++ b/client/tests/test_bake_state.py @@ -1,4 +1,5 @@ -"""A user's state, written into an image: registry, index, knowledge.""" +"""A user's state, written into an image: registry, index, knowledge, skills +and learned rules.""" import json import os @@ -6,6 +7,7 @@ import sys import tempfile import unittest +import unittest.mock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) @@ -96,5 +98,83 @@ def test_no_store_adds_nothing(self): wk._SCHEMA, wk.Lifecycle.ACTIVE), 0) +class SkillsAndLearnedRules(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp() + self.state = os.path.join(self.dir, "state") + self.rules = os.path.join(self.dir, "rules.d") + os.makedirs(os.path.join(self.state, "skills")) + + def write(self, path, text): + with open(path, "w", encoding="utf-8") as handle: + handle.write(text) + + def test_the_users_skills_are_copied_over_the_images(self): + target = os.path.join(self.dir, "skills") + os.makedirs(target) + self.write(os.path.join(target, "flash.md"), "shipped") + self.write(os.path.join(self.state, "skills", "flash.md"), "revised") + self.write(os.path.join(self.state, "skills", "probe.md"), "new") + self.write(os.path.join(self.state, "skills", "notes.txt"), "not a skill") + + self.assertEqual(bake_state.bake_skills(os.path.join(self.state, "skills"), target), + ["flash", "probe"]) + self.assertEqual(sorted(os.listdir(target)), ["flash.md", "probe.md"]) + + with open(os.path.join(target, "flash.md")) as handle: + self.assertEqual(handle.read(), "revised") + + def test_no_skills_of_the_users_adds_nothing(self): + self.assertEqual(bake_state.bake_skills(os.path.join(self.dir, "absent"), self.dir), []) + + def test_learned_rules_become_a_rule_that_reaches_what_a_learned_rule_reaches(self): + from context import context_sources + + learned = os.path.join(self.state, "rules-learned.md") + self.write(learned, "- Never push to main. (2026-01-02)\n") + + self.assertEqual(bake_state.bake_learned_rules(learned, self.rules), 1) + + baked, = context_sources.rule_candidates(self.rules) + own, = context_sources.learned_candidate(learned) + + self.assertIn("Never push to main.", baked.text) + self.assertEqual((baked.scope, baked.tasks), (own.scope, own.tasks)) + + def test_a_second_build_adds_only_what_is_new(self): + learned = os.path.join(self.state, "rules-learned.md") + self.write(learned, "- One.\n") + bake_state.bake_learned_rules(learned, self.rules) + self.write(learned, "- One.\n- Two.\n") + + self.assertEqual(bake_state.bake_learned_rules(learned, self.rules), 1) + self.assertEqual(bake_state.bake_learned_rules(learned, self.rules), 0) + + with open(os.path.join(self.rules, bake_state.LEARNED_RULE)) as handle: + self.assertEqual(handle.read(), bake_state.LEARNED_HEADER + "- One.\n- Two.\n") + + def test_nothing_learned_writes_no_rule(self): + self.assertEqual(bake_state.bake_learned_rules(os.path.join(self.dir, "absent"), + self.rules), 0) + self.assertFalse(os.path.exists(self.rules)) + + +class WhatIsAlreadyOpenIsLeftAlone(unittest.TestCase): + def test_only_a_path_lacking_the_mode_is_changed(self): + directory = tempfile.mkdtemp() + closed, opened = os.path.join(directory, "closed"), os.path.join(directory, "open") + + for path, mode in ((closed, 0o600), (opened, 0o777)): + open(path, "w").close() + os.chmod(path, mode) + + with unittest.mock.patch("os.chmod", wraps=os.chmod) as chmod: + bake_state._open(closed, 0o666) + bake_state._open(opened, 0o666) + + chmod.assert_called_once_with(closed, 0o666) + self.assertEqual(os.stat(opened).st_mode & 0o777, 0o777) + + if __name__ == "__main__": unittest.main() diff --git a/client/tests/test_claude_context.py b/client/tests/test_claude_context.py index 9f79689..83edf78 100644 --- a/client/tests/test_claude_context.py +++ b/client/tests/test_claude_context.py @@ -7,6 +7,7 @@ import os import sys import tempfile +import time import unittest from pathlib import Path from unittest import mock @@ -54,7 +55,7 @@ def test_the_passages_retrieved_for_it_and_the_workspaces_knowledge(self): self.record("alpha", "The modem is on UART2.") index = FakeIndex() - text = claude_context.compose(index, "where is a?", "alpha", self.dir, self.projects) + text = claude_context.compose(index, "where is a?", self.dir, self.projects) self.assertEqual(index.asked, [("where is a?", "alpha")]) self.assertIn(claude_context.RETRIEVED_HEADER, text) @@ -66,7 +67,7 @@ def test_nothing_from_a_corpus_that_has_no_index(self): index = FakeIndex() self.assertEqual( - claude_context.compose(index, "q", "beta", self.dir, {"beta": {"path": self.dir}}), + claude_context.compose(index, "q", self.dir, {"beta": {"path": self.dir}}), "") self.assertEqual(index.asked, []) @@ -74,18 +75,31 @@ def test_a_tree_nobody_registered_is_known_by_where_it_is(self): root = os.path.realpath(self.dir) self.record(f"adhoc:{root}", "Built with ninja.") - text = claude_context.compose(None, "how is it built?", None, self.dir, {}) + text = claude_context.compose(None, "how is it built?", self.dir, {}) self.assertIn("Built with ninja.", text) self.assertNotIn(claude_context.RETRIEVED_HEADER, text) + def test_what_is_printed_stays_under_what_is_read_in_full(self): + self.record("alpha", "The modem is on UART2.") + passages = [f"# File: src/{n}.c\n" + "x" * 3000 for n in range(6)] + index = FakeIndex(claude_context.SEPARATOR.join(passages)) + + text = claude_context.compose(index, "q", self.dir, self.projects) + + self.assertLessEqual(len(text), claude_context.OUTPUT_CHARS) + self.assertIn("The modem is on UART2.", text) + self.assertIn(passages[0], text) + self.assertIn(passages[1], text) + self.assertNotIn("src/5.c", text) + def test_a_search_that_fails_leaves_the_knowledge(self): self.record("alpha", "The modem is on UART2.") index = FakeIndex() index.context = mock.Mock(side_effect=RuntimeError("index gone")) with mock.patch("sys.stderr", io.StringIO()): - text = claude_context.compose(index, "q", "alpha", self.dir, self.projects) + text = claude_context.compose(index, "q", self.dir, self.projects) self.assertIn("The modem is on UART2.", text) @@ -97,33 +111,54 @@ def run_hook(self, argv, event): return code, out.getvalue() + def wait_for(self, path): + for _ in range(200): + if claude_context.ask(path, {}) is not None: + return + + time.sleep(0.01) + + self.fail("no server answered") + def test_it_asks_the_sessions_server_and_prints_its_answer(self): path = os.path.join(self.dir, "socket") index = FakeIndex() - listener = claude_context.serve(index, path, self.projects) - self.addCleanup(listener.close) + claude_context.serve(index, self.projects, path) + self.wait_for(path) - code, text = self.run_hook(["--socket", path, "--corpus", "alpha"], - {"prompt": "where is a?", "cwd": self.dir}) + code, text = self.run_hook(["--socket", path], {"prompt": "where is a?", "cwd": self.dir}) self.assertEqual(code, 0) self.assertIn("# File: src/a.c", text) self.assertIn(("where is a?", "alpha"), index.asked) self.assertEqual(os.stat(path).st_mode & 0o777, 0o600) + def test_a_second_server_leaves_the_socket_to_the_first(self): + path = os.path.join(self.dir, "socket") + first, second = FakeIndex("# File: first"), FakeIndex("# File: second") + first.default = second.default = None + claude_context.serve(first, self.projects, path) + self.wait_for(path) + claude_context.serve(second, self.projects, path) + time.sleep(0.05) + + _, text = self.run_hook(["--socket", path], {"prompt": "q", "cwd": self.dir}) + + self.assertIn("# File: first", text) + def test_without_a_server_it_does_the_work_itself(self): with mock.patch.object(claude_context, "_alone", return_value="the context") as alone: - code, text = self.run_hook(["--socket", os.path.join(self.dir, "nobody"), - "--corpus", "alpha"], + code, text = self.run_hook(["--socket", os.path.join(self.dir, "nobody")], {"prompt": "q", "cwd": self.dir}) self.assertEqual((code, text), (0, "the context\n")) - alone.assert_called_once_with("q", "alpha", self.dir) + alone.assert_called_once_with("q", self.dir) def test_it_never_fails_a_prompt(self): with mock.patch.object(claude_context, "_alone", side_effect=RuntimeError("broken")), \ mock.patch("sys.stderr", io.StringIO()): - self.assertEqual(self.run_hook([], {"prompt": "q", "cwd": self.dir}), (0, "")) + self.assertEqual(self.run_hook(["--socket", os.path.join(self.dir, "nobody")], + {"prompt": "q", "cwd": self.dir}), (0, "")) self.assertEqual(self.run_hook([], {"prompt": " "}), (0, "")) self.assertEqual(claude_context.hook([], io.StringIO("not json"), io.StringIO()), 0) diff --git a/client/tests/test_reds_image.py b/client/tests/test_reds_image.py index b395a71..a1c3d47 100644 --- a/client/tests/test_reds_image.py +++ b/client/tests/test_reds_image.py @@ -530,17 +530,24 @@ def test_install_removes_the_launcher_under_its_former_name(self): def test_the_image_gives_a_prompt_of_the_other_assistant_what_a_turn_gets(self): harness = (REPO / "docker" / "Dockerfile.harness").read_text() - launcher = (REPO / "docker" / "claude-launcher").read_text() + setup = (REPO / "docker" / "spear-claude-setup").read_text() + managed = json.loads((REPO / "docker" / "claude-managed-settings.json").read_text()) - for command in ("spear-claude-context", "spear-knowledge"): + for command in ("spear-claude-context", "spear-knowledge", "spear-claude-setup"): self.assertIn(f"docker/{command}", harness) self.assertIn(f"/usr/local/bin/{command}", harness) self.assertTrue(os.access(REPO / "docker" / command, os.X_OK)) - self.assertIn('"UserPromptSubmit"', launcher) - self.assertIn('spear-claude-context --socket $SOCKET', launcher) - self.assertIn('--context-socket "$SOCKET"', launcher) - self.assertIn('--settings "$SETTINGS"', launcher) + # The hook is the image's, so an editor's own copy of the program + # runs it too; the server it asks is registered with no corpus named. + + self.assertIn("docker/claude-managed-settings.json " + "/etc/claude-code/managed-settings.json", harness) + self.assertEqual(managed["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"], + "spear-claude-context") + self.assertIn("-- spear-mcp --context", setup) + self.assertIn("spear-claude-setup", (REPO / "docker" / "claude-launcher").read_text()) + self.assertIn("spear-claude-setup", (REPO / "docker" / "spear-shell").read_text()) def test_the_image_carries_it(self): dockerfile = (REPO / "docker" / "Dockerfile").read_text() diff --git a/client/tests/test_skill_library.py b/client/tests/test_skill_library.py index ba2010b..8b03fed 100644 --- a/client/tests/test_skill_library.py +++ b/client/tests/test_skill_library.py @@ -1,6 +1,7 @@ import os import tempfile import unittest +from unittest import mock from datetime import datetime from context import skill_library @@ -236,5 +237,47 @@ def test_the_saved_file_reloads_as_the_same_skill(self): self.assertEqual(load_library(self.directory), [saved]) +class LayeredLibraryTests(unittest.TestCase): + """An image ships its library; what a user saves there goes beside it.""" + + def setUp(self): + self.dir = tempfile.mkdtemp() + self.shipped = os.path.join(self.dir, "shipped") + self.own = os.path.join(self.dir, "state", "skills") + skill_library.save(self.shipped, "flash", "Flash over USB.", scope=("alpha",)) + + def test_a_library_the_user_can_write_has_no_other_layer(self): + self.assertIsNone(skill_library.own_directory(self.shipped, self.dir)) + self.assertIsNone(skill_library.own_directory(os.path.join(self.dir, "absent"), self.dir)) + + def test_a_library_the_user_cannot_write_sends_skills_to_the_state(self): + with mock.patch("os.access", return_value=False): + self.assertEqual(skill_library.own_directory(self.shipped, "/state"), + "/state/skills") + + def test_the_users_skill_is_listed_with_the_shipped_ones(self): + skill_library.save_layered(self.shipped, self.own, "probe", "Probe the bus.") + + self.assertEqual([skill.name for skill in + skill_library.load_layered(self.shipped, self.own)], + ["flash", "probe"]) + self.assertEqual(os.listdir(self.shipped), ["flash.md"]) + + def test_a_shipped_skill_saved_again_keeps_its_history_and_answers_for_it(self): + revised = skill_library.save_layered(self.shipped, self.own, "flash", "Flash over JTAG.") + + self.assertEqual((revised.version, revised.scope), (2, ("alpha",))) + + found, = skill_library.load_layered(self.shipped, self.own) + + self.assertEqual(found.body, "Flash over JTAG.") + self.assertEqual(skill_library.load_library(self.shipped)[0].body, "Flash over USB.") + + def test_without_a_layer_the_library_itself_is_written(self): + skill_library.save_layered(self.shipped, None, "probe", "Probe the bus.") + + self.assertEqual(sorted(os.listdir(self.shipped)), ["flash.md", "probe.md"]) + + if __name__ == "__main__": unittest.main() diff --git a/doc/source/start/container_run.rst b/doc/source/start/container_run.rst index d980add..f022623 100644 --- a/doc/source/start/container_run.rst +++ b/doc/source/start/container_run.rst @@ -211,7 +211,18 @@ container reaches it through an SSH tunnel you open on your machine. Retrieval is not left to the model's choice in either: the hook runs SPEAR's own search on each prompt. ``/memory``, ``/skills`` and - ``/mcp`` show, inside Claude Code, what a session was given. + ``/mcp`` show, inside Claude Code, what a session was given. A prompt + is given at most what Claude Code reads in full, some 10 000 + characters: the knowledge, then as many passages as fit. + + **From an editor.** The container is named ``spear--``. + Attach VS Code to it (*Dev Containers: Attach to Running Container*), + open the tree, and install the Claude Code extension in the container. + The extension starts its own copy of the program, which reads the same + home and the same image-wide hook, so its panel works from the same + base as the ``claude`` command; what the shell prepared at its start is + the corpus of the directory it was opened in. ``claude`` in the + editor's terminal is the command above. An image gains Claude Code as one more layer, once it is built: @@ -222,7 +233,9 @@ container reaches it through an SSH tunnel you open on your machine. 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: + you accepted, the skills that were saved and the rules taught with + ``/recall``. ``--build`` writes all of it into a new image, on top of + everything the image you run already holds: .. code-block:: console @@ -230,8 +243,15 @@ container reaches it through an SSH tunnel you open on your machine. registry 1 added: index ( chunks) knowledge active records + skills 1 added: + rules learned built /spear:- + Both assistants then start from it: a colleague who runs the new image + gets these additions in ``spear-chat`` and in ``claude`` alike. Knowledge + an assistant only proposed stays behind until you accept it + (``/knowledge accept `` in ``spear-chat``). + 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 diff --git a/docker/Dockerfile.harness b/docker/Dockerfile.harness index d69438a..d314851 100644 --- a/docker/Dockerfile.harness +++ b/docker/Dockerfile.harness @@ -103,12 +103,14 @@ COPY --from=repo docker/spear-claude-export /usr/local/bin/spear-claude-export COPY --from=repo docker/spear-shell docker/spear-chat docker/spear-where \ docker/spear-bake-state docker/spear-claude-context docker/spear-knowledge \ - /usr/local/bin/ + docker/spear-claude-setup /usr/local/bin/ +COPY --from=repo docker/claude-managed-settings.json /etc/claude-code/managed-settings.json COPY --from=repo docker/claude-launcher /usr/local/bin/claude RUN chmod +x /opt/spear/entrypoint.sh /opt/spear/spear /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/spear-bake-state /usr/local/bin/claude \ - /usr/local/bin/spear-claude-context /usr/local/bin/spear-knowledge + /usr/local/bin/spear-claude-context /usr/local/bin/spear-knowledge \ + /usr/local/bin/spear-claude-setup ENV SPEAR_COMMON_STATE_DIR=/opt/spear/common ENV SPEAR_STANDARDS_ROOT=/opt/spear/common/standards diff --git a/docker/claude-launcher b/docker/claude-launcher index b39ca14..32dc9a2 100755 --- a/docker/claude-launcher +++ b/docker/claude-launcher @@ -1,65 +1,13 @@ #!/bin/bash -# Claude Code on this image's corpora, installed as `claude`: the rules and -# skills of the corpus the current directory is in are laid out where it reads -# them, the corpus index is its MCP server, and it starts. Each prompt then -# gets what a SPEAR request gets by itself, through a hook: the passages -# retrieved from the index and the workspace's recorded knowledge. +# Claude Code on this image's corpora, installed as `claude`: prepared for the +# corpus the current directory is in (spear-claude-setup), then started. # -# Everything is written under HOME, never in the tree: a checkout bound into -# the container stays as git left it. HOME is expected to outlive the -# container, since the login is kept there too. +# What a SPEAR request gets by itself -- the passages retrieved from the index +# and the workspace's recorded knowledge -- reaches each prompt through a hook +# the image declares for every client (/etc/claude-code/managed-settings.json). set -e -REAL=/opt/claude/.local/bin/claude +spear-claude-setup -[ -x "$REAL" ] || { - echo "claude: this image does not carry it; scripts/docker/add-claude.sh adds it" >&2 - exit 1 -} - -CORPUS="$(spear-where)" -CONF="$HOME/.claude" -LIST="$CONF/.spear-exported" -mkdir -p "$CONF" - -# What the previous run exported goes first: another corpus has other rules. - -if [ -f "$LIST" ]; then - while IFS= read -r path; do - rm -f "$CONF/$path" - done < "$LIST" -fi - -STAGE="$(mktemp -d)" -trap 'rm -rf "$STAGE"' EXIT - -spear-claude-export ${CORPUS:+--corpus "$CORPUS"} --out "$STAGE" 2>/dev/null - -if [ -d "$STAGE/.claude" ]; then - (cd "$STAGE/.claude" && find . -type f | sed 's|^\./||') > "$LIST" - cp -r "$STAGE/.claude/." "$CONF/" -fi - -rm -rf "$STAGE" -trap - EXIT - -# The index is registered for the user, so it is there whatever follows on -# the command line. - -# The hook asks the session's MCP server, which has the embedder loaded, on -# a socket of this session's own. - -SOCKET="$(mktemp -u "${TMPDIR:-/tmp}/spear-context-XXXXXX")" -SETTINGS="$SOCKET.json" - -cat > "$SETTINGS" </dev/null 2>&1 || true -"$REAL" mcp add --scope user spear-corpus -- spear-mcp ${CORPUS:+--corpus "$CORPUS"} \ - --context-socket "$SOCKET" >/dev/null - -exec "$REAL" --settings "$SETTINGS" "$@" +exec /opt/claude/.local/bin/claude "$@" diff --git a/docker/claude-managed-settings.json b/docker/claude-managed-settings.json new file mode 100644 index 0000000..d3fe89a --- /dev/null +++ b/docker/claude-managed-settings.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "spear-claude-context", + "timeout": 180 + } + ] + } + ] + } +} diff --git a/docker/spear-claude-setup b/docker/spear-claude-setup new file mode 100755 index 0000000..cde56b6 --- /dev/null +++ b/docker/spear-claude-setup @@ -0,0 +1,50 @@ +#!/bin/bash +# Prepare Claude Code, in this container, for the tree the current directory +# is in: the rules and skills of its corpus are laid out where Claude Code +# reads them, and the corpus index is registered as its MCP server. +# +# Everything is written under HOME, never in the tree: a checkout bound into +# the container stays as git left it. HOME is expected to outlive the +# container, since the login is kept there too. +# +# It serves every client: the `claude` command runs it before starting, and +# the shell runs it once, for an editor attached to the container, whose +# extension starts its own copy of the program. + +set -e + +REAL=/opt/claude/.local/bin/claude + +[ -x "$REAL" ] || { + echo "claude: this image does not carry it; scripts/docker/add-claude.sh adds it" >&2 + exit 1 +} + +CORPUS="$(spear-where)" +CONF="$HOME/.claude" +LIST="$CONF/.spear-exported" +mkdir -p "$CONF" + +# What the previous run exported goes first: another corpus has other rules. + +if [ -f "$LIST" ]; then + while IFS= read -r path; do + rm -f "$CONF/$path" + done < "$LIST" +fi + +STAGE="$(mktemp -d)" +trap 'rm -rf "$STAGE"' EXIT + +spear-claude-export ${CORPUS:+--corpus "$CORPUS"} --out "$STAGE" 2>/dev/null + +if [ -d "$STAGE/.claude" ]; then + (cd "$STAGE/.claude" && find . -type f | sed 's|^\./||') > "$LIST" + cp -r "$STAGE/.claude/." "$CONF/" +fi + +# The index is registered for the user, with no corpus named: the server +# takes the one of the directory it is started in, whatever the client. + +"$REAL" mcp remove --scope user spear-corpus >/dev/null 2>&1 || true +"$REAL" mcp add --scope user spear-corpus -- spear-mcp --context >/dev/null diff --git a/docker/spear-shell b/docker/spear-shell index e57677b..f8219c1 100755 --- a/docker/spear-shell +++ b/docker/spear-shell @@ -25,6 +25,11 @@ echo " ${BOLD}spear-chat${OFF} SPEAR on this tree (--ask, --safe, --auto)" if [ -x /opt/claude/.local/bin/claude ]; then echo " ${BOLD}claude${OFF} Claude Code on this tree" + + # For an editor attached to this container: its extension starts Claude + # Code without the command above. + + (spear-claude-setup >/dev/null 2>&1 &) fi echo diff --git a/scripts/docker/spear b/scripts/docker/spear index 7476055..8f6f920 100755 --- a/scripts/docker/spear +++ b/scripts/docker/spear @@ -316,9 +316,13 @@ fi mkdir -p "$STATE/home" TTY=(-i); [ -t 0 ] && TTY=(-i -t) +# A name that says what the container is, for whoever attaches an editor to it. + +NAME="spear-$(printf '%s' "${WORKDIR##*/}" | tr -c 'A-Za-z0-9_.-' '-')-$$" + # The three --security-opt are what bubblewrap, the harness's sandbox, needs # to start inside a container; without them it refuses every command. -exec docker run --rm "${TTY[@]}" \ +exec docker run --rm --name "$NAME" "${TTY[@]}" \ --security-opt seccomp=unconfined \ --security-opt apparmor=unconfined \ --security-opt systempaths=unconfined \