diff --git a/client/normative/normative_precedence.py b/client/normative/normative_precedence.py index 3e9625c..bc404f9 100644 --- a/client/normative/normative_precedence.py +++ b/client/normative/normative_precedence.py @@ -161,6 +161,11 @@ # A question, a quotation of the user, or a statement about what is unknown. _INTERROGATIVE = re.compile(r"\?\s*$") +# A heading names what follows ("## What the standard says about SGIs"), and +# an indirect question asks it; neither states anything the guard could back. +_HEADING = re.compile(r"^\s*#{1,6}\s") +_INDIRECT = re.compile(r"\b(?:what|how|whether|where|which|when)\s+$", re.I) + # How far back a citation still carries. Three sentences reaches the bullet # that stated the rule from the conclusion drawn two sentences later, which is # the shape the model actually writes; it does not reach across a section of @@ -196,10 +201,17 @@ def states_a_requirement(sentence, binding=None): document or merely described -- cannot come to a different answer than this module does. """ - if _INTERROGATIVE.search(sentence) or _NEGATED.search(sentence): + if (_INTERROGATIVE.search(sentence) or _NEGATED.search(sentence) + or _HEADING.match(sentence)): return False - return bool(_subject(binding).search(sentence) or _clause_voiced(sentence)) + spoken = _subject(binding).search(sentence) + + if (spoken and _INDIRECT.search(sentence[:spoken.start()]) + and ":" not in sentence[spoken.end():]): + spoken = None + + return bool(spoken or _clause_voiced(sentence)) def stated_content(sentence, binding=None): diff --git a/client/runtime/agent_finalization.py b/client/runtime/agent_finalization.py index 6d57a05..d846668 100644 --- a/client/runtime/agent_finalization.py +++ b/client/runtime/agent_finalization.py @@ -105,7 +105,7 @@ def _inject_evidence_call(self, context: AgentContext, policy, return False policy.observe_tool_result(injected.tool, envelope.model_content, - origin=injected.origin) + origin=injected.origin, structured=envelope.text) context.conversation.append(ConversationMessage( "assistant", (ToolUseBlock(call_id, injected.tool, dict(injected.arguments)),), diff --git a/client/runtime/agent_runtime.py b/client/runtime/agent_runtime.py index 9695ea2..6abf180 100644 --- a/client/runtime/agent_runtime.py +++ b/client/runtime/agent_runtime.py @@ -930,7 +930,8 @@ def run(self, context: AgentContext, *, defer_completion: bool = False) -> Agent if policy is not None and call.name in policy.STANDARD_TOOLS: policy.observe_tool_result(call.name, - envelope.model_content) + envelope.model_content, + structured=envelope.text) # Every call, for the record of which source files the # turn read. A conformance answer that read none says so. diff --git a/client/runtime/answer_repair.py b/client/runtime/answer_repair.py index 99930bb..6c24aba 100644 --- a/client/runtime/answer_repair.py +++ b/client/runtime/answer_repair.py @@ -210,6 +210,24 @@ def _provision_lines(evidence): lines.append(f" [{cited}] modality: {record.modality}\n" f" {record.text[:400]}") + return lines or _unit_lines(evidence) + + +def _unit_lines(evidence, limit=40): + """The retrieved units themselves, for a document that declares no + provisions: a register description is evidence too, and an empty list + told the model that the fields it had quoted came from nowhere.""" + lines, seen = [], set() + + for unit in evidence.units: + if unit.source_id in seen or len(lines) >= limit: + continue + + seen.add(unit.source_id) + text = " ".join(unit.text.split()) + lines.append(f" [§{unit.section or '?'}, source {unit.source_id}]\n" + f" {text[:400]}") + return lines @@ -222,7 +240,7 @@ def _finding_lines(problems): if kind == normative_claims.UNGROUNDED_IDENTIFIER: lines.append( f" - `{problem['identifier']}` is named in your answer and " - "appears in no provision below. Do not use it again, and do " + "appears in no evidence below. Do not use it again, and do " "not substitute a variant spelling, an expansion or a " "synonym for it. If it was not needed to answer the " "question, leave it out and keep the rest of the answer as " diff --git a/client/standard/standard_answer_policy.py b/client/standard/standard_answer_policy.py index 0e528e2..7b60359 100644 --- a/client/standard/standard_answer_policy.py +++ b/client/standard/standard_answer_policy.py @@ -33,6 +33,7 @@ from evidence import conformance_guard from evidence import conformance_mode from standard import diagram_geometry +from standard import standard_tools from evidence import evidence_bootstrap from evidence import evidence_progress from evidence import evidence_recovery @@ -174,12 +175,16 @@ class StandardAnswerPolicy: # -- observation ------------------------------------------------------ - def observe_tool_result(self, name, text, *, origin=MODEL): + def observe_tool_result(self, name, text, *, origin=MODEL, structured=None): """One tool result, exactly as the model was shown it. Every ledger reads from here and none of them writes anywhere: the payload is parsed, never modified, and a result that is not JSON or is a refusal contributes nothing but its provenance. + + A fetch is shown as rendered text, so its payload is the structured + result (`structured`, the envelope's whole text) cut back to that + rendering. """ self.provenance.observe(text) @@ -188,6 +193,15 @@ def observe_tool_result(self, name, text, *, origin=MODEL): except ValueError: payload = None + if payload is None and structured and name == "standard.fetch": + try: + whole = json.loads(structured) + except ValueError: + whole = None + + if isinstance(whole, dict) and not whole.get("error"): + payload = standard_tools.shown_fetch(whole, text) + empty = False # Which clauses the model was actually shown. A refusal carries none. @@ -321,6 +335,39 @@ def should_stop_for_exhaustion(self, answer=""): # -- the boundary ----------------------------------------------------- + def _rule_guards(self, text): + """The conformance and precedence guards, recorded on the policy.""" + + # A compliance verdict the turn is not entitled to. Between the two + # guards on purpose: it reads the evidence-guarded text, and what it + # writes in place of a verdict is built from the clause ledger, so + # the provenance guard behind it has nothing to find there. + + guarded, findings, replaced, conformance_fired = conformance_guard.guard( + text, self.clauses, standard_id=self.standard_id, + revision=self.revision, binding=self.binding) + self.conformance_fired = conformance_fired + self.conformance_findings = list(findings) + self.replaced_verdicts = list(replaced) + + # ...and the same question on the other subject: a statement of what + # the STANDARD requires, backed by a clause this turn retrieved. + # Beside the conformance guard because they are one idea seen from + # two sides -- what the code does about a rule, and what the rule + # says -- and before the provenance guard for its reason: what it + # writes is built from the ledger, so nothing downstream finds a + # source in it. + + guarded, requirements, replaced_requirements, precedence_fired = ( + normative_precedence.guard( + guarded, self.clauses, standard_id=self.standard_id, + revision=self.revision, binding=self.binding)) + self.precedence_fired = precedence_fired + self.precedence_findings = list(requirements) + self.replaced_requirements = list(replaced_requirements) + + return guarded + def finalize(self, answer, *, rounds=None, stopped_by=None): """The user-visible answer, and only what the evidence supports of it.""" self.raw_answer = answer or "" @@ -349,33 +396,8 @@ def finalize(self, answer, *, rounds=None, stopped_by=None): self.guard_fired = replaced self.guard_violations = list(violations) - # A compliance verdict the turn is not entitled to. Between the two - # guards on purpose: it reads the evidence-guarded text, and what it - # writes in place of a verdict is built from the clause ledger, so - # the provenance guard behind it has nothing to find there. - - guarded, findings, replaced, conformance_fired = conformance_guard.guard( - guarded, self.clauses, standard_id=self.standard_id, - revision=self.revision, binding=self.binding) - self.conformance_fired = conformance_fired - self.conformance_findings = list(findings) - self.replaced_verdicts = list(replaced) - - # ...and the same question on the other subject: a statement of what - # the STANDARD requires, backed by a clause this turn retrieved. - # Beside the conformance guard because they are one idea seen from - # two sides -- what the code does about a rule, and what the rule - # says -- and before the provenance guard for its reason: what it - # writes is built from the ledger, so nothing downstream finds a - # source in it. - - guarded, requirements, replaced_requirements, precedence_fired = ( - normative_precedence.guard( - guarded, self.clauses, standard_id=self.standard_id, - revision=self.revision, binding=self.binding)) - self.precedence_fired = precedence_fired - self.precedence_findings = list(requirements) - self.replaced_requirements = list(replaced_requirements) + evidence_guarded = guarded + guarded = self._rule_guards(guarded) # What the answer CLAIMS, against what the evidence SAYS. The guards # above establish that a supporting clause was retrieved; none of them @@ -397,15 +419,18 @@ def finalize(self, answer, *, rounds=None, stopped_by=None): requested = normative_claims.identifiers_in(self.question) - before_repair = guarded guarded, claim_problems, claims_fired = normative_claims.guard( guarded, self.claim_evidence, question=self.question, permitted=permitted, binding=self.binding, requested=requested) # One constrained rewrite, when the evidence in hand can settle what # was wrong with the prose. No new retrieval, no loop, and the same - # guard again on what comes back -- a repair that fails is withheld - # exactly as the original was. + # guards again on what comes back -- a repair that fails is withheld + # exactly as the original was. It rewrites the answer as the model + # wrote it: handed the rule guards' notes in place of its sentences, + # it kept the notes as prose of its own. + + before_repair = evidence_guarded if (claims_fired and self.repair_ask is not None and answer_repair.is_repairable(claim_problems)): @@ -428,7 +453,8 @@ def finalize(self, answer, *, rounds=None, stopped_by=None): permitted=permitted, binding=self.binding, requested=requested) if not retry_fired: - guarded, claim_problems, claims_fired = checked, [], False + guarded = self._rule_guards(checked) + claim_problems, claims_fired = [], False self.repair_accepted = True else: claim_problems = list(retry_problems) diff --git a/client/standard/standard_tools.py b/client/standard/standard_tools.py index bb6c3e5..9319b42 100644 --- a/client/standard/standard_tools.py +++ b/client/standard/standard_tools.py @@ -251,6 +251,53 @@ def fits(*candidate: str) -> bool: return "\n".join([core] + extras) if extras else core +_INCOMPLETE = re.compile(r"\[INCOMPLETE: characters (\d+)-(\d+) of \d+") +_CONTINUED = re.compile(r"continued from character (\d+) of \d+") + + +def shown_fetch(fetched: Mapping[str, object], rendered: str) -> dict: + """The part of a fetch result the model was actually shown. + + The guards read evidence as structured units, and what reaches the model + is `render_fetch_for_model`'s text, which is not JSON: read as JSON it was + nothing, and a field the model quoted from a fetched unit or from its + neighbours was then judged to come from nowhere. This is the structured + result cut back to that rendering -- the unit's text as far as it was + shown, and the parent, rows, neighbours and cross-references the + rendering kept, each with the preview it was given. + """ + shown = dict(fetched) + unit = dict(fetched.get("unit") or {}) + full = str(unit.get("text") or "") + cut = _INCOMPLETE.search(rendered) + continued = _CONTINUED.search(rendered) + + if cut: + unit["text"] = full[int(cut.group(1)):int(cut.group(2))] + elif continued: + unit["text"] = full[int(continued.group(1)):] + + shown["unit"] = unit + + def kept(item): + if not isinstance(item, Mapping) or str(item.get("source_id") or "") not in rendered: + return None + + item = dict(item) + text = " ".join(str(item.get("text") or "").split()) + item["text"] = text[:_CONTEXT_PREVIEW_CHARS].rstrip() + + return item + + parent = kept(fetched.get("parent")) + shown["parent"] = parent + + for key in ("table_rows", "neighbors", "resolved_cross_references"): + shown[key] = [item for item in map(kept, fetched.get(key) or []) if item] + + return shown + + # How a caller comes by a source id at all. There is no listing of the corpus, # so pointing at one would be inventing a path that does not exist. diff --git a/client/tests/test_fetch_evidence.py b/client/tests/test_fetch_evidence.py new file mode 100644 index 0000000..d331911 --- /dev/null +++ b/client/tests/test_fetch_evidence.py @@ -0,0 +1,109 @@ +"""What a fetch showed the model is what the guards read. + +Seen in use: `standard.fetch` is shown as rendered text, not JSON, and the +policy parsed it as JSON. Every fetch then counted for nothing: a field the +model quoted from the fetched register's neighbours ("RS, bits [47:44] +RangeSelector") was judged to come from nowhere and removed by the repair, +and a miscopied position beside it went unchecked. +""" + +import json +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import synthetic_standard +from standard import standard_answer_policy as sap +from standard.standard_tools import render_fetch_for_model, shown_fetch + +MODE = "WidgetMode, bits [7:4] Widget Mode. Selects how the reply is encoded." +LATE = "WidgetTail, bits [31:28] Widget Tail. Never shown to the model." + + +def fetched(): + found = synthetic_standard.fetch(neighbours=()) + found["unit"]["source_id"] = "std-" + "1" * 32 + found["neighbors"] = [ + {"section": synthetic_standard.SECTION, "source_id": "std-" + "2" * 32, + "text": MODE}, + {"section": synthetic_standard.SECTION, "source_id": "std-" + "3" * 32, + "text": LATE}, + ] + + return found + + +def rendered(found, budget=None): + if budget is None: + budget = len(render_fetch_for_model(found, budget=100000)) - len(LATE) + + return render_fetch_for_model(found, budget=budget) + + +class Shown(unittest.TestCase): + def test_only_the_neighbours_the_rendering_kept_are_evidence(self): + found = fetched() + text = rendered(found) + + self.assertIn("WidgetMode", text) + self.assertNotIn("WidgetTail", text) + self.assertEqual([item["text"] for item in shown_fetch(found, text)["neighbors"]], + [MODE]) + + def test_a_unit_cut_short_counts_as_far_as_it_was_shown(self): + found = fetched() + found["unit"]["text"] = "A" * 400 + " WidgetLate appears only past the cut." + text = render_fetch_for_model(found, budget=600) + + self.assertIn("[INCOMPLETE", text) + self.assertNotIn("WidgetLate", shown_fetch(found, text)["unit"]["text"]) + + +class Policy(unittest.TestCase): + """A register description: a document that declares no provisions.""" + + def policy(self, **options): + policy = sap.policy_for(synthetic_standard.BINDING, "Which fields?", **options) + found = fetched() + found["unit"]["text"] = "Purpose Generates widgets for the current state." + policy.observe_tool_result("standard.fetch", rendered(found), + structured=json.dumps(found)) + + return policy + + def test_a_rendered_fetch_reaches_every_ledger(self): + policy = self.policy() + + self.assertIn("widgetmode", policy.claim_evidence.identifiers()) + self.assertNotIn("widgettail", policy.claim_evidence.identifiers()) + self.assertIn(synthetic_standard.SECTION, policy.clauses.sections) + + def test_the_repair_rewrites_the_answer_not_the_guards_notes(self): + seen = [] + + def ask(text): + seen.append(text) + + return ("WidgetMode, bits [7:4] selects the encoding.\n" + "The standard requires a barrier after the write, as §9.9 says.") + + policy = self.policy(repair_ask=ask) + answer = ("WidgetMode, bits [7:4] selects the encoding, and WidgetBogus " + "picks the target.\n" + "The standard requires a barrier after the write, as §9.9 says.") + + shown = policy.finalize(answer, stopped_by=sap.STOPPED_BY_MODEL) + + self.assertTrue(seen, "the repair was never attempted") + self.assertNotIn("No requirement of", seen[0]) + self.assertIn("requires a barrier", seen[0]) + self.assertIn(MODE[:40], seen[0]) + self.assertNotIn("WidgetBogus", shown) + self.assertIn("No requirement of", shown) + self.assertTrue(policy.precedence_fired) + + +if __name__ == "__main__": + unittest.main() diff --git a/client/tests/test_normative_precedence.py b/client/tests/test_normative_precedence.py index 1d7515a..514c0f3 100644 --- a/client/tests/test_normative_precedence.py +++ b/client/tests/test_normative_precedence.py @@ -177,6 +177,26 @@ def test_existing_behaviour_is_not_a_clearance(self): [conformance_guard.UNSCOPED_VERDICT]) +class TitlesAreNotClaims(unittest.TestCase): + """A heading or an indirect question names a topic; it states nothing. + + Seen in use: "## What the standard says about generating an SGI" opened + a fully cited answer and was replaced by the note. + """ + + def test_a_heading_is_left_alone(self): + answer = "## What the standard says about widgets\n\nSee below." + self.assertEqual(guard(answer, sections=[])[3], False) + + def test_an_indirect_question_is_left_alone(self): + self.assertFalse(normative_precedence.states_a_requirement( + "Here is how the standard defines a widget, clause by clause.", BINDING)) + + def test_a_claim_after_the_colon_is_still_guarded(self): + self.assertTrue(normative_precedence.states_a_requirement( + "This is what the standard requires: every widget shall be blue.", BINDING)) + + class UnsupportedIsNotNonCompliant(unittest.TestCase): """CASE 3 -- the standard defines more than the code claims to support.""" diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base index bca6c85..ee5a2f6 100644 --- a/docker/Dockerfile.base +++ b/docker/Dockerfile.base @@ -1,4 +1,4 @@ -# A company's commons, built on the harness. +# A company's commons, built on the harness runtime. # # It carries what every project of the company needs: the shared build system # and corpora (its family included), the prebuilt index, the @@ -7,10 +7,11 @@ # Dockerfile.project builds one project's delta on top of this. # # Every addition overlays the empty directory the harness created, from a named -# build context staged by scripts/docker/build.sh. +# build context staged by scripts/docker/build-tiered.sh. The result is the +# content image, -content; Dockerfile.code lays the code on it. -ARG HARNESS_IMAGE -FROM ${HARNESS_IMAGE} +ARG RUNTIME_IMAGE +FROM ${RUNTIME_IMAGE} ARG APP=/opt/spear/client diff --git a/docker/Dockerfile.code b/docker/Dockerfile.code new file mode 100644 index 0000000..4fd1a09 --- /dev/null +++ b/docker/Dockerfile.code @@ -0,0 +1,10 @@ +# The harness code laid on a content image (the runtime, a base's or a +# project's), as its last layer. +# +# Every layer below it is content that changes rarely and weighs tens of GB; the +# code changes often and weighs a few MB. Laid last, a new harness is one new +# layer to push and to pull, and the content layers keep their digests. + +ARG CONTENT_IMAGE +FROM ${CONTENT_IMAGE} +COPY --from=code / / diff --git a/docker/Dockerfile.harness b/docker/Dockerfile.harness index d314851..b114eac 100644 --- a/docker/Dockerfile.harness +++ b/docker/Dockerfile.harness @@ -1,15 +1,17 @@ # SPEAR harness — the application only, no content. Public and shippable. # -# First link of the FROM chain: Dockerfile.base builds a company's commons on -# top of this, and Dockerfile.project bakes one project's delta on top of that. -# This image carries the venv, the embedder and the harness code -- the -# expensive layers every image above reuses -- and nothing a deployment could -# not publish: no index, no corpus, no standards, no rules or skills content. +# Three targets. `runtime` is the first link of the FROM chain: the venv and +# the embedder, the expensive layers every image above reuses. Dockerfile.base +# builds a company's commons on it and Dockerfile.project one project's delta +# on that. `code` is the harness code alone, laid last on each of them by +# Dockerfile.code; `harness` is the runtime with the code, and carries nothing +# a deployment could not publish: no index, no corpus, no standards, no rules +# or skills content. # # Default build context is client/ (the harness); `repo` is a named context for # the two files that live outside it. See scripts/docker/build.sh. -FROM ubuntu:24.04 +FROM ubuntu:24.04 AS runtime ENV DEBIAN_FRONTEND=noninteractive @@ -64,7 +66,29 @@ from chromadb.utils.embedding_functions import ONNXMiniLM_L6_V2; \ ONNXMiniLM_L6_V2()(['warm'])" \ && chmod -R a+rX /opt/spear/chroma-home -# The harness code. +# Empty content, corpus and state directories, and an empty registry, so the +# harness finds a directory rather than nothing. A base image fills them. + +RUN mkdir -p "$APP/rules.d" "$APP/skills" "$APP/benches" "$APP/chromadb" \ + /corpora /opt/spear/common/standards /opt/spear/state \ + && printf '{}\n' > "$APP/projects.json" \ + && chmod -R 0777 /corpora /opt/spear/common /opt/spear/state "$APP/chromadb" + +ENV SPEAR_COMMON_STATE_DIR=/opt/spear/common +ENV SPEAR_STANDARDS_ROOT=/opt/spear/common/standards +ENV SPEAR_STATE_DIR=/opt/spear/state +ENV SPEAR_SHIPPED_DB_PATH=$APP/chromadb +ENV SPEAR_CORPUS_ROOT=/corpora +ENV PATH=$APP/bin:$PATH +WORKDIR /corpora +ENTRYPOINT ["/opt/spear/entrypoint.sh"] + +# The code, alone in an image of its own and laid last on every tier, so that +# a change to it replaces one small layer instead of every content layer +# stacked above it. Dockerfile.code lays it on a content image. + +FROM scratch AS code +ARG APP=/opt/spear/client COPY *.md $APP/ COPY agent/ $APP/agent/ @@ -81,42 +105,23 @@ COPY training/ $APP/training/ COPY eval/ $APP/eval/ COPY deploy/ $APP/deploy/ -# Empty content, corpus and state directories, and an empty registry, so the -# harness finds a directory rather than nothing. A base image fills them. - -RUN mkdir -p "$APP/rules.d" "$APP/skills" "$APP/benches" "$APP/chromadb" \ - /corpora /opt/spear/common/standards /opt/spear/state \ - && printf '{}\n' > "$APP/projects.json" \ - && chmod -R 0777 /corpora /opt/spear/common /opt/spear/state "$APP/chromadb" - # The launcher a recipient copies out to run the image, and the entrypoint. # Both live in the repo, not in client/, so they come from the `repo` context. -COPY --from=repo scripts/docker/spear /opt/spear/spear -COPY --from=repo docker/entrypoint.sh /opt/spear/entrypoint.sh -COPY --from=repo docker/spear-mcp /usr/local/bin/spear-mcp -COPY --from=repo docker/spear-claude-export /usr/local/bin/spear-claude-export +COPY --chmod=0755 --from=repo scripts/docker/spear /opt/spear/spear +COPY --chmod=0755 --from=repo docker/entrypoint.sh /opt/spear/entrypoint.sh +COPY --chmod=0755 --from=repo docker/spear-mcp /usr/local/bin/spear-mcp +COPY --chmod=0755 --from=repo docker/spear-claude-export /usr/local/bin/spear-claude-export # What a shell in the container offers: SPEAR, and Claude Code prepared for # 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 \ +COPY --chmod=0755 --from=repo docker/spear-shell docker/spear-chat docker/spear-where \ docker/spear-bake-state docker/spear-claude-context docker/spear-knowledge \ 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-setup +COPY --chmod=0755 --from=repo docker/claude-launcher /usr/local/bin/claude -ENV SPEAR_COMMON_STATE_DIR=/opt/spear/common -ENV SPEAR_STANDARDS_ROOT=/opt/spear/common/standards -ENV SPEAR_STATE_DIR=/opt/spear/state -ENV SPEAR_SHIPPED_DB_PATH=$APP/chromadb -ENV SPEAR_CORPUS_ROOT=/corpora -ENV PATH=$APP/bin:$PATH -WORKDIR /corpora -ENTRYPOINT ["/opt/spear/entrypoint.sh"] +FROM runtime AS harness +COPY --from=code / / diff --git a/docker/Dockerfile.project b/docker/Dockerfile.project index 4fb192a..d41768b 100644 --- a/docker/Dockerfile.project +++ b/docker/Dockerfile.project @@ -9,6 +9,10 @@ # The index context is the FULL index for the commons plus this project's # corpora (stage-index.py bakes it), so it replaces the base's rather than # merging into it. +# +# BASE_IMAGE is the base's content image, -content, not the base itself: +# built on the code layer, every layer here would change with the code. The +# result is -content; Dockerfile.code lays the code on it. ARG BASE_IMAGE FROM ${BASE_IMAGE} diff --git a/docker/README.md b/docker/README.md index 44194ad..a947378 100644 --- a/docker/README.md +++ b/docker/README.md @@ -54,6 +54,14 @@ Two settings in `local.conf` say where an image lives, tried in this order: The tiers themselves — `harness` → `base` → `project` — and what each carries are below under the lower-level `build` commands. +The harness code is the last layer of every tier. Each tier is first built as +a content image, `-content`, on the code-free `spear:-runtime`, +and `docker/Dockerfile.code` lays `spear:-code` on it. A change to the +code alone is then `spear-image build code`: it re-lays the code on the +content images already built, and a pull fetches that one small layer instead +of the whole image. Content tools (Claude Code through `add-claude.sh`, say) +go on the `-content` image, followed by `build code`. + ## Managing images From the repository root, once per shell: diff --git a/scripts/docker/build-tiered.sh b/scripts/docker/build-tiered.sh index b2c6d2c..ea26400 100755 --- a/scripts/docker/build-tiered.sh +++ b/scripts/docker/build-tiered.sh @@ -2,6 +2,7 @@ # Build the tiered images: harness -> base -> project. # # build-tiered.sh harness +# build-tiered.sh code [--tag IMAGE]... # build-tiered.sh base [--commons a,b,c] [--entity NAME] [--licensed] # [--knowledge p,q|all] # build-tiered.sh project [--from spear:-base] [--tree DIR] @@ -16,6 +17,12 @@ # of --standards DIR (a store holding, say, only one private standard), appended over the # base's. So another entity's project image = the reds base + a private standard. # +# Each tier is built as a content image, -content, and the harness code is +# laid on it last (Dockerfile.code): a new harness then changes one small layer +# of the base and of the project, not the tens of GB of content above it. The +# `code` tier does only that: it lays the current code on the content images +# already built, base and project, without restaging any content. +# # This is the FROM chain of PACKAGING-REWORK.md. The legacy flat profiles # (public|reds|private) stay in build.sh, untouched; this script only knows the # three new tiers and leaves everything else alone. @@ -45,9 +52,9 @@ ATTEST=(--provenance=false --sbom=false) TIER="${1:-}"; shift || true case "$TIER" in - harness|base|project) ;; + harness|code|base|project) ;; ""|-h|--help) sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; - *) die "tier must be harness, base or project, not '$TIER'" ;; + *) die "tier must be harness, code, base or project, not '$TIER'" ;; esac # The machine's configuration, exactly as build.sh and the launchers read it: @@ -77,6 +84,7 @@ TAG="${SPEAR_TAG:-}" STANDARDS_STORE="${SPEAR_STANDARDS_STORE:-}" LICENSED="${SPEAR_LICENSED:-0}" TREES=() +LAY=() [ -n "${SPEAR_PROJECT_TREES:-}" ] && IFS=: read -r -a TREES <<<"$SPEAR_PROJECT_TREES" while [ $# -gt 0 ]; do @@ -89,7 +97,7 @@ while [ $# -gt 0 ]; do --tree) TREES+=("$2"); shift 2 ;; --standards) STANDARDS_STORE="$2"; shift 2 ;; --licensed) LICENSED=1; shift ;; - --tag) TAG="$2"; shift 2 ;; + --tag) TAG="$2"; LAY+=("$2"); shift 2 ;; *) die "unknown option: $1" ;; esac done @@ -145,25 +153,73 @@ print(" manifest " + out) PY } -case "$TIER" in +RUNTIME="spear:$VERSION-runtime" +CODE="spear:$VERSION-code" + +# The harness's targets: the runtime, the code alone, and both together. With +# arguments, only those targets: a content tier rebuilds the code, never the +# runtime it was built on. + +build_harness() { + local target tag targets=("$@") + + [ "${#targets[@]}" -gt 0 ] || targets=(runtime code harness) + + for target in "${targets[@]}"; do + tag="spear:$VERSION-$target" + [ "$target" = harness ] && tag="${HARNESS_TAG:-$tag}" + echo "== building $tag ($target) ==" + docker build -f "$REPO/docker/Dockerfile.harness" --target "$target" \ + "${ATTEST[@]}" \ + --build-context "repo=$REPO" \ + --label "$LABEL.profile=harness" \ + --label "$LABEL.built=$(date -Iseconds)" \ + --label "$LABEL.redistributable=true" \ + -t "$tag" "$APP" + done +} -harness) - TAG="${TAG:-spear:$VERSION-harness}" - echo "== building $TAG (harness) ==" - docker build -f "$REPO/docker/Dockerfile.harness" \ +# $1 = the content image, $2 = the image it becomes with the code on top. The +# content image's labels are inherited; only the build date is new, and +# spear.content names the content, so the launcher keeps the index volume it +# filled from it across code updates. + +lay_code() { + echo "== laying $CODE on $1 -> $2 ==" + docker build -f "$REPO/docker/Dockerfile.code" \ "${ATTEST[@]}" \ - --build-context "repo=$REPO" \ - --label "$LABEL.profile=harness" \ + --build-arg "CONTENT_IMAGE=$1" \ + --build-context "code=docker-image://$CODE" \ --label "$LABEL.built=$(date -Iseconds)" \ - --label "$LABEL.redistributable=true" \ - -t "$TAG" "$APP" - echo "built $TAG (harness)" + --label "$LABEL.content=$(docker image inspect -f '{{.Id}}' "$1")" \ + -t "$2" "$EMPTY" + echo "built $2" +} + +case "$TIER" in + +harness) + HARNESS_TAG="${TAG:-}" build_harness + echo "built ${TAG:-spear:$VERSION-harness} (harness)" + ;; + +code) + build_harness + [ "${#LAY[@]}" -gt 0 ] || LAY=("spear:$VERSION-base" "spear:$VERSION-project") + + for image in "${LAY[@]}"; do + if exists "$image-content"; then + lay_code "$image-content" "$image" + else + echo " $image-content not found -- $image left as it is" + fi + done ;; base) [ -n "$COMMONS" ] || die "base needs --commons a,b,c (the common corpora, the build system included)" HARNESS="spear:$VERSION-harness" - exists "$HARNESS" || die "$HARNESS not found — build it first: spear-image build harness" + exists "$RUNTIME" || build_harness TAG="${TAG:-spear:$VERSION-base}" # The registry (whole map), then the commons staged: index cut to them, the @@ -207,7 +263,7 @@ base) echo "== building $TAG (base, entity=$ENTITY, redistributable=$REDIST) ==" docker build -f "$REPO/docker/Dockerfile.base" \ "${ATTEST[@]}" \ - --build-arg "HARNESS_IMAGE=$HARNESS" \ + --build-arg "RUNTIME_IMAGE=$RUNTIME" \ --build-context "repo=$REPO" \ --build-context "index=$STAGE/index" \ --build-context "rules=$STAGE/content/rules.d" \ @@ -222,13 +278,15 @@ base) --label "$LABEL.entity=$ENTITY" \ --label "$LABEL.built=$(date -Iseconds)" \ --label "$LABEL.redistributable=$REDIST" \ - -t "$TAG" "$APP" - echo "built $TAG (base)" + -t "$TAG-content" "$APP" + build_harness code + lay_code "$TAG-content" "$TAG" ;; project) [ -n "$FROM_BASE" ] || FROM_BASE="spear:$VERSION-base" - exists "$FROM_BASE" || die "$FROM_BASE not found — build the base first: spear-image build base ..." + exists "$FROM_BASE-content" \ + || die "$FROM_BASE-content not found — build the base first: spear-image build base ..." [ "${#TREES[@]}" -gt 0 ] || die "project needs --tree DIR (the project's spear-private content)" TAG="${TAG:-spear:$VERSION-project}" HARNESS="" @@ -275,7 +333,7 @@ project) echo "== building $TAG (project, FROM $FROM_BASE) ==" docker build -f "$REPO/docker/Dockerfile.project" \ "${ATTEST[@]}" \ - --build-arg "BASE_IMAGE=$FROM_BASE" \ + --build-arg "BASE_IMAGE=$FROM_BASE-content" \ --build-context "repo=$REPO" \ --build-context "index=$STAGE/index" \ --build-context "rules=$STAGE/content/rules.d" \ @@ -288,7 +346,8 @@ project) --label "$LABEL.entity=$ENTITY" \ --label "$LABEL.built=$(date -Iseconds)" \ --label "$LABEL.redistributable=false" \ - -t "$TAG" "$APP" - echo "built $TAG (project)" + -t "$TAG-content" "$APP" + build_harness code + lay_code "$TAG-content" "$TAG" ;; esac diff --git a/scripts/docker/spear b/scripts/docker/spear index 4f8181f..62c1db7 100755 --- a/scripts/docker/spear +++ b/scripts/docker/spear @@ -340,15 +340,19 @@ MEMORY="${SPEAR_CONTAINER_MEMORY:-$(awk '/^MemTotal:/ { printf "%dm", $2 * 3 / 4 # chromadb opens the image's index read-write, and overlayfs then copies the # whole database into each new container: some 25 GB and tens of seconds at # every start, long enough for chromadb to give up waiting. A named volume -# holds it instead, filled from the image once and reused while the image -# stays the same; volumes of earlier images are removed when not in use. +# holds it instead, filled from the image once and reused while its content +# stays the same -- the content image the code was laid on (spear.content), +# so a new harness alone keeps the volume; volumes of earlier images are +# removed when not in use. INDEX=() SHIPPED="$(docker image inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$IMAGE" 2>/dev/null \ | sed -n 's/^SPEAR_SHIPPED_DB_PATH=//p')" if [ -n "$SHIPPED" ]; then - VOLUME="spear-index-$(docker image inspect -f '{{.Id}}' "$IMAGE" | cut -d: -f2 | cut -c1-12)" + CONTENT="$(docker image inspect -f '{{ index .Config.Labels "spear.content" }}' "$IMAGE")" + [ -n "$CONTENT" ] || CONTENT="$(docker image inspect -f '{{.Id}}' "$IMAGE")" + VOLUME="spear-index-$(printf '%s' "$CONTENT" | cut -d: -f2 | cut -c1-12)" for old in $(docker volume ls -q --filter name=spear-index-); do [ "$old" = "$VOLUME" ] || docker volume rm "$old" >/dev/null 2>&1 || true diff --git a/scripts/spear-image b/scripts/spear-image index 791ba85..dd70a01 100755 --- a/scripts/spear-image +++ b/scripts/spear-image @@ -98,7 +98,7 @@ case "$action" in build) profile="$1" case "$profile" in - harness|base|project) + harness|code|base|project) shift exec "$DOCKER_SCRIPTS/build-tiered.sh" "$profile" "$@" ;; public|reds|private) shift ;;