Buckets:

download
raw
28.2 kB
"""Manifest generation, checksums, constants, and version utilities.
The leaf primitives ``MANIFEST_FILENAME`` and ``sha256_file`` live in the
build-time kernel (:mod:`osprey.build.manifest`) so lower layers can consume
them without importing ``cli``; they are re-imported here for the
catalog-aware generation/validation logic that stays in this module.
"""
import json
import logging
import tempfile
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from osprey.build.manifest import MANIFEST_FILENAME, sha256_file
from osprey.errors import BuildProfileError
from osprey.services.build_artifacts.catalog import BuildArtifactCatalog
logger = logging.getLogger("osprey.cli.templates")
# Manifest schema version for future compatibility.
#
# 1.3.0 — ``creation.template`` is the preset the profile records (``None`` for
# a hand-written profile) instead of a preset-or-bundle best effort, and
# ``creation.data_bundle`` / ``build_args.data_bundle`` are gone: the app bundle
# is a fact about the preset, so a reader that wants it asks the preset.
MANIFEST_SCHEMA_VERSION = "1.3.0"
#: Keys once written under ``creation`` that no longer exist. A manifest an
#: older build wrote still carries them, and every reader of build provenance is
#: advisory: it says what it found and moves on rather than failing the
#: operation it is annotating. Debug, not warning — nothing is wrong with such a
#: project, and the next build restamps it.
_RETIRED_CREATION_KEYS = ("data_bundle",)
# Maps manifest YAML category keys to BuildArtifactCatalog canonical-name prefixes.
# Needed because YAML convention uses underscores while registry uses hyphens.
_MANIFEST_CATEGORY_PREFIX = {
"hooks": "hooks/",
"rules": "rules/",
"skills": "skills/",
"agents": "agents/",
"output_styles": "output-styles/",
}
#: Framework-managed output paths tracked for checksum collection during regen,
#: for the case where neither a project manifest nor a preset names a
#: selection.
#:
#: DERIVED from the artifact catalog, never hand-listed: a literal list falls
#: silently behind the catalog it mirrors, and an artifact missing here is an
#: artifact whose drift is never detected. `resolve_manifest_outputs` above
#: reads the same `output_path` from the same catalog, so the fallback and the
#: selected path cannot disagree about what an artifact is called.
REGEN_TRACKED_FILES = sorted(
{"CLAUDE.md", ".mcp.json", ".claude/settings.json", ".claude/statusline.py"}
| {artifact.output_path for artifact in BuildArtifactCatalog.default().all_artifacts()}
)
def framework_template_hash(
claude_code_dir: Path,
template_path: str,
jinja_env: Any,
context: dict[str, Any],
) -> str | None:
"""``sha256:`` digest of the framework's own version of one artifact.
Recorded when an artifact is claimed and recomputed on every regen, so the
two must be computed identically or every regen would report drift that is
not there. That is the whole reason this lives in one function: the two
callers are in different modules and would otherwise be free to differ on
the render context, the encoding, or the ``sha256:`` prefix.
A ``.j2`` template is rendered first — the digest is of what the framework
would *write*, not of the template that writes it, so a context change is
drift and a comment change in the template is not.
Args:
claude_code_dir: The ``claude_code`` template directory.
template_path: The artifact's template path below it.
jinja_env: Jinja environment the render goes through.
context: Template context for the render.
Returns:
``sha256:<hex>``, or ``None`` when the template is missing or will not
render. Callers treat ``None`` as "no comparison possible" rather than
as drift: a template that cannot render is a framework problem, and
reporting it as the operator's artifact having drifted would misdirect.
"""
template_file = claude_code_dir / template_path
if not template_file.exists():
return None
try:
if template_file.suffix != ".j2":
return f"sha256:{sha256_file(template_file)}"
with tempfile.NamedTemporaryFile(
mode="w", suffix=template_file.stem, delete=False, encoding="utf-8"
) as tmp:
template = jinja_env.get_template(f"claude_code/{template_path}")
tmp.write(template.render(**context))
tmp_path = Path(tmp.name)
digest = f"sha256:{sha256_file(tmp_path)}"
tmp_path.unlink(missing_ok=True)
return digest
except Exception:
return None
def _stored_artifacts(project_dir: Path | None) -> dict | None:
"""The artifact selections a built project recorded, or ``None``.
Read from the project's own ``.osprey-manifest.json`` — what the build that
made this project actually selected, and therefore the most specific answer
available. ``None`` covers every way there is no answer: no project to ask,
no manifest, a manifest too damaged to parse, or one recording no
selections. A damaged manifest is not an error here: the callers all have a
further fallback, and refusing to regenerate a project because its manifest
got truncated would be worse than regenerating from the template's list.
"""
if project_dir is None:
return None
manifest_path = project_dir / MANIFEST_FILENAME
if not manifest_path.exists():
return None
try:
data = json.loads(manifest_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return None
return data.get("artifacts") or None
def load_template_manifest(
template_name: str | None,
project_dir: Path | None = None,
) -> dict | None:
"""The artifact selection that applies to a render, or ``None``.
Two sources, in that order: the project's own ``.osprey-manifest.json``,
which records what the build that made the project actually selected, and
failing that the bundled preset ``template_name`` names. Bundled templates
carry no artifact declaration of their own.
Args:
template_name: The app bundle directory ("control_assistant"), or the
preset a built project's manifest records ("control-assistant").
Both spellings resolve, because the bundled-preset fallback below
normalizes whichever it is given onto the hyphenated preset file.
``None`` when the caller has no name to offer — a project built
from a profile that records no preset — and then only the
project-local source applies.
project_dir: Optional project directory. When given, artifacts are read
from its ``.osprey-manifest.json`` in preference to the preset.
Returns:
``{"artifacts": {...}}``, or None if no source is available.
"""
stored_artifacts = _stored_artifacts(project_dir)
if stored_artifacts:
return {"artifacts": stored_artifacts}
if template_name is None:
return None
# The bundled preset profile is the canonical source of artifact declarations.
#
# Resolved through the profile resolver, not read as raw YAML: a preset
# that says `extends: control-assistant` declares only its DELTA, so
# reading its file alone answers with a fraction of what it selects —
# the persona presets would report no skills, or web_panels with no
# agents. Resolving is also what applies `exclude:`, so a persona that
# subtracts an artifact is reported without it.
artifact_keys = ("hooks", "rules", "skills", "agents", "output_styles", "web_panels")
try:
from osprey.cli.build_profile_merge import resolve_profile_document
from osprey.cli.build_profile_presets import _load_preset_raw, _preset_exists
if _preset_exists(template_name) is None:
return None
raw, preset_path = _load_preset_raw(template_name)
resolved = resolve_profile_document(raw, preset_path, warn=False).raw
artifacts = {k: resolved[k] for k in artifact_keys if k in resolved}
if artifacts:
return {"artifacts": artifacts}
except (BuildProfileError, OSError):
pass
return None
def resolve_manifest_outputs(manifest: dict) -> set[str]:
"""Resolve a template manifest to the set of output paths that should be generated.
Config artifacts (CLAUDE.md, .mcp.json, .claude/settings.json, .claude/statusline.py) are always included.
For each manifest entry, prefix-matching is used against the prompt registry to
handle multi-file artifacts (e.g. session-report -> SKILL.md + reference.md).
Args:
manifest: Parsed manifest dict (from load_template_manifest)
Returns:
Set of output paths (relative to project root) that the manifest allows.
"""
result = {"CLAUDE.md", ".mcp.json", ".claude/settings.json", ".claude/statusline.py"}
registry = BuildArtifactCatalog.default()
all_artifacts = registry.all_artifacts()
for category, entries in manifest.get("artifacts", {}).items():
prefix = _MANIFEST_CATEGORY_PREFIX.get(category)
if prefix is None:
continue
for entry_name in entries:
canonical_prefix = prefix + entry_name
# Prefix-match: include artifacts whose canonical name matches exactly
# OR starts with prefix + "/". This handles multi-file artifacts like
# session-report (skills/session-report + skills/session-report/reference).
for artifact in all_artifacts:
if (
artifact.canonical_name == canonical_prefix
or artifact.canonical_name.startswith(canonical_prefix + "/")
):
result.add(artifact.output_path)
return result
def get_tracked_files(
template_name: str | None,
project_dir: Path | None = None,
) -> list[str]:
"""Get the list of tracked files for regen, based on manifest if available.
Resolution order:
1. If ``project_dir`` is given and its ``.osprey-manifest.json`` contains
an ``"artifacts"`` key, use those artifact selections.
2. Otherwise fall back to the bundled preset ``template_name`` names.
3. If neither answers, return the static ``REGEN_TRACKED_FILES`` list.
Args:
template_name: Bundle or preset name, as :func:`load_template_manifest`
takes it; ``None`` when the caller has neither.
project_dir: Optional project directory; when provided, the project-local
``.osprey-manifest.json`` is checked for stored artifact selections.
Returns:
Sorted list of output paths that should be tracked during regen.
"""
# 1. Try project-local manifest first
stored_artifacts = _stored_artifacts(project_dir)
if stored_artifacts:
return sorted(resolve_manifest_outputs({"artifacts": stored_artifacts}))
# 2. Fall back to the bundled preset's declaration
tmpl_manifest = load_template_manifest(template_name)
if tmpl_manifest is not None:
return sorted(resolve_manifest_outputs(tmpl_manifest))
return list(REGEN_TRACKED_FILES)
def get_framework_version() -> str:
"""Get the running osprey version, for display in generated projects.
This is the version a human reads — it carries distance past the last release
(``2026.6.2.post783+g83fda5e60``) so a project rendered from a development
checkout says so. Anything comparing versions wants
:func:`osprey.version.get_release_version` instead; see
:func:`get_framework_release_version`.
Returns:
Version string, or ``"unknown"`` if the version module cannot be imported
(broken environment / partial install). Manifest readers branch on the
sentinel.
"""
try:
from osprey.version import get_running_version
return get_running_version()
except (ImportError, AttributeError):
return "unknown"
def get_framework_release_version() -> str:
"""Get the release this osprey descends from, for version *comparisons*.
Stamped into the manifest's ``creation.osprey_version`` and read back by
:mod:`osprey.deployment.staleness`, which compares it by string equality. Using
the running version on either side would make every commit in a development
checkout register as drift — inverting the advisory's rule that "can't compare"
must never read as drift into "always reads as drift".
Returns:
Release version string (e.g. ``"2026.6.2"``), or ``"unknown"`` if the
version module cannot be imported.
"""
try:
from osprey.version import get_release_version
return get_release_version()
except (ImportError, AttributeError):
return "unknown"
def extract_build_args(
project_name: str,
preset_name: str | None,
profile_path: str | None,
context: dict[str, Any],
) -> dict[str, Any]:
"""Extract build invocation arguments for manifest storage.
Captures both the user-facing options (provider/model/etc.) and the
invocation source (preset vs. positional profile path), as a record of what
this build resolved. Nothing renders a command line from it — the
manifest's ``reproducible_command`` is the constant
:data:`REPO_REPRODUCIBLE_COMMAND`, because the repo is the invocation.
Exactly one of ``preset_name`` and ``profile_path`` must be set.
``profile_path`` stays the string the user typed. ``profile_path_abs`` is
recorded separately, from ``context``, and on *every* build: it names the
profile the project was actually built from, which is what every later
reader follows. A relative CLI string re-resolves against whatever directory
the reader runs from, so it is the absolute form they follow.
Args:
project_name: Name of the project.
preset_name: Hyphenated preset name (e.g. "hello-world") if the build
was invoked via ``--preset``; otherwise ``None``.
profile_path: Path string to the positional profile YAML if the build
was invoked positionally; otherwise ``None``.
context: Full template context.
Returns:
Dictionary of build arguments suitable for round-trip reproduction.
"""
build_args: dict[str, Any] = {
"project_name": project_name,
"source": "preset" if preset_name else "profile",
}
if preset_name:
build_args["preset"] = preset_name
if profile_path:
build_args["profile_path"] = profile_path
profile_path_abs = context.get("profile_path_abs")
if profile_path_abs:
build_args["profile_path_abs"] = str(profile_path_abs)
optional_keys = [
("default_provider", "provider"),
("default_model", "model"),
("channel_finder_mode", "channel_finder_mode"),
]
for context_key, arg_key in optional_keys:
if context_key in context and context[context_key] is not None:
value = context[context_key]
if isinstance(value, bool) or value:
build_args[arg_key] = value
return build_args
#: What a manifest's ``reproducible_command`` says. A constant, because the
#: command is one: the repo is the invocation, so there is no project name to
#: pass, no profile path to name and no output directory to choose.
#:
#: Written directly rather than assembled by a generator: a generator's output
#: would have to be overwritten by this constant afterwards, and a manifest
#: written by any path that skipped the overwrite would carry the wrong string.
REPO_REPRODUCIBLE_COMMAND = "osprey build"
def calculate_file_checksums(project_dir: Path) -> dict[str, str]:
"""Calculate SHA256 checksums for trackable project files.
Trackable files are those the build renders into the project — everything
a rebuild reproduces, so a checksum mismatch means the file drifted from
its source. ``data/`` is included: it is build-owned (machine models,
channel databases, benchmark query sets all come from the profile or the
preset), so a runtime writer landing there would show up here as
unexplained drift. Runtime state belongs in the repo's ``var/`` zone, which
is a SIBLING of the rendered project rather than a directory inside it — so
the four-zone layout keeps runtime writers out of this walk by construction
and needs no exclusion of its own.
Excluded:
- ``.env`` (secrets, never rendered deterministically)
- ``_agent_data/`` — a runtime-state directory inside the project. Nothing
creates it, so on a current deployment the entry never matches; it is
kept because the cost of an exclusion that never matches is nothing,
while dropping it would silently start checksumming a directory left
behind by an older release and report the result as project drift.
- ``__pycache__/`` and ``.pyc`` files
- ``.git/``
- the manifest itself
Args:
project_dir: Root directory of the project
Returns:
Dictionary mapping relative file paths to their SHA256 checksums
"""
checksums = {}
# Patterns to exclude
exclude_patterns = {
".env",
".git",
"__pycache__",
".pyc",
"_agent_data",
".osprey-manifest.json", # Don't checksum ourselves
}
# Walk the project directory
for file_path in project_dir.rglob("*"):
if not file_path.is_file():
continue
# Get relative path
rel_path = file_path.relative_to(project_dir)
rel_path_str = str(rel_path)
# Skip excluded patterns
skip = False
for pattern in exclude_patterns:
if pattern in rel_path.parts or rel_path_str.startswith(pattern):
skip = True
break
if skip:
continue
# Skip binary and large files
# .duckdb: a derived binary artifact that carries its own content digest in
# its meta table, so checksumming it would turn every `osprey knowledge
# build-index` into apparent render drift.
if file_path.suffix in [".pyc", ".pyo", ".so", ".dll", ".dylib", ".duckdb"]:
continue
# Calculate checksum
try:
checksum = sha256_file(file_path)
checksums[rel_path_str] = f"sha256:{checksum}"
except OSError:
# Skip files that can't be read
continue
return checksums
def build_user_owned_manifest(
template_root: Path,
jinja_env,
project_dir: Path,
context: dict[str, Any],
) -> dict[str, Any]:
"""Build user_owned section for the manifest.
For each user-owned artifact, records the SHA-256 of the framework
template as rendered at claim time. During regen, if the framework
hash changes, a drift warning is shown.
Args:
template_root: Path to osprey's bundled templates directory
jinja_env: Jinja2 environment for template rendering
project_dir: Root directory of the project
context: Template context with ``user_owned`` key
Returns:
Dict mapping canonical names to user_owned metadata, or empty dict.
"""
user_owned = context.get("user_owned", [])
if not user_owned:
return {}
registry = BuildArtifactCatalog.default()
result: dict[str, Any] = {}
claude_code_dir = template_root / "claude_code"
for canonical_name in user_owned:
artifact = registry.get(canonical_name)
if artifact is None:
continue
framework_hash = framework_template_hash(
claude_code_dir, artifact.template_path, jinja_env, context
)
entry: dict[str, Any] = {
"claimed_at": datetime.now(UTC).isoformat(),
}
if framework_hash:
entry["framework_hash"] = framework_hash
result[canonical_name] = entry
return result
def generate_manifest(
template_root: Path,
jinja_env,
project_dir: Path,
project_name: str,
recorded_preset: str | None,
context: dict[str, Any],
*,
artifacts: dict[str, list[str]] | None = None,
preset_name: str | None = None,
profile_path: str | None = None,
) -> dict[str, Any]:
"""Generate ``.osprey-manifest.json`` for a freshly built project.
Args:
template_root: Root of the bundled templates package.
jinja_env: The Jinja2 environment used during rendering.
project_dir: Project root directory (where the manifest is written).
project_name: Name of the project.
recorded_preset: The preset the built profile records — ``None`` for a
hand-written profile that records none. Stamped as
``creation.template``; see the note there.
context: Full template-render context.
artifacts: Profile-driven artifact selection.
preset_name: Hyphenated preset name if invoked via ``--preset``.
profile_path: Path string to the positional profile, if any.
Returns:
The manifest dict written to disk.
"""
build_args = extract_build_args(
project_name=project_name,
preset_name=preset_name,
profile_path=profile_path,
context=context,
)
file_checksums = calculate_file_checksums(project_dir)
# The release lineage, not the running version — staleness compares this field
# by string equality, so a development build must not read as drift.
framework_version = get_framework_release_version()
user_owned_manifest = build_user_owned_manifest(template_root, jinja_env, project_dir, context)
creation_block: dict[str, Any] = {
"osprey_version": framework_version,
"timestamp": datetime.now(UTC).isoformat(),
# One meaning, always: the preset this project's profile records. Not a
# preset-or-bundle best effort — a field that names two different kinds
# of thing depending on how the build was invoked cannot be read without
# knowing the invocation, which is precisely what a later reader does
# not have. `None` is the honest answer for a hand-written profile that
# records no preset, and readers treat it as "no preset to name" rather
# than substituting a default.
"template": recorded_preset,
"claude_code_only": True,
}
# Stamp a content hash of what this project was rendered from, so `osprey up`
# can detect a project whose render predates its source — the
# osprey_version alone can't, since a --dev checkout keeps one version
# string across commits.
#
# That source is the PROFILE, on every build. A `--preset` build renders
# from the profile it materialized, not from the bundled preset, so hashing
# the preset here would leave a hand edit to that profile invisible to the
# staleness advisory — the one edit the advisory most needs to see, since
# editing the profile is how a facility is meant to change its project. The
# preset a profile came from stays recorded in the profile's own
# `provenance:` block, which the build compares separately for its
# materialization-time drift advisory. The preset hash remains the fallback
# for a build that somehow resolved no profile path.
#
# Best-effort: an unhashable source omits the key (staleness checks then
# skip the content comparison) rather than failing the build.
try:
from osprey.cli import build_profile as _build_profile
# The path the build resolved, never the string the user typed: the two
# only agree while the process stays in the invocation directory, and a
# profile's data/overlay trees are anchored on it.
hashed_profile = build_args.get("profile_path_abs") or profile_path
if hashed_profile:
preset_hash = _build_profile.compute_profile_hash(Path(hashed_profile))
elif preset_name:
preset_hash = _build_profile.compute_preset_hash(preset_name)
else:
preset_hash = None
except Exception:
preset_hash = None
if preset_hash:
creation_block["preset_hash"] = preset_hash
# Preserve the CLAUDE.md template choice so a later `osprey build` can
# re-render against the same persona (e.g. CLAUDE.ariel.md.j2 for the
# ARIEL standalone preset). Default is the control-system persona.
claude_md_template = context.get("claude_md_template")
if claude_md_template and claude_md_template != "CLAUDE.md.j2":
creation_block["claude_md_template"] = claude_md_template
manifest_data: dict[str, Any] = {
"schema_version": MANIFEST_SCHEMA_VERSION,
"creation": creation_block,
"build_args": build_args,
"reproducible_command": REPO_REPRODUCIBLE_COMMAND,
"file_checksums": file_checksums,
}
if artifacts:
manifest_data["artifacts"] = artifacts
if user_owned_manifest:
manifest_data["user_owned"] = user_owned_manifest
manifest_path = project_dir / MANIFEST_FILENAME
with open(manifest_path, "w", encoding="utf-8") as f:
json.dump(manifest_data, f, indent=2, sort_keys=False)
return manifest_data
def note_retired_creation_keys(creation: Any) -> None:
"""Debug-log any :data:`_RETIRED_CREATION_KEYS` a manifest still carries.
A manifest older than this schema version is still a perfectly good
manifest: the keys it holds that the current build no longer writes are
ignored, never refused. This is the one place that says so out loud, so the
fact is greppable when someone wonders why a field they remember has no
effect.
:param creation: A manifest's ``creation`` block, whatever it turned out to
be — a non-mapping is simply nothing to report.
"""
if not isinstance(creation, dict):
return
for key in _RETIRED_CREATION_KEYS:
if key in creation:
logger.debug(
"Project manifest carries retired creation key %r (schema %s no longer "
"writes it); ignoring it. The next build restamps the manifest.",
key,
MANIFEST_SCHEMA_VERSION,
)
def load_project_manifest(project_dir: Path) -> dict[str, Any] | None:
"""Read a built project's ``.osprey-manifest.json``.
Returns ``None`` when the file is missing, unparseable, or not an object —
every reader of build provenance is advisory and must fail open rather than
break the operation it is annotating.
:param project_dir: Project root (the directory holding the manifest).
"""
try:
raw = (Path(project_dir) / MANIFEST_FILENAME).read_text(encoding="utf-8")
except OSError:
return None
try:
data = json.loads(raw)
except ValueError:
return None
if not isinstance(data, dict):
return None
note_retired_creation_keys(data.get("creation"))
return data
def manifest_profile_path(project_dir: Path) -> Path | None:
"""The absolute profile file a project was built from, per its manifest.
Reads ``build_args.profile_path_abs`` — the path ``osprey build`` actually
resolved. The ``profile_path`` spelling beside it is the string the user
typed and is deliberately *not* used as a fallback here: a relative one
re-resolves against whatever directory the deploy runs from, so following it
would write a facility's secrets into an arbitrary directory that happens to
match. ``None`` for a legacy manifest or no manifest at all; every build
records it, a ``--preset`` build naming the profile it materialized.
:param project_dir: Project root (the directory holding the manifest).
"""
manifest = load_project_manifest(project_dir)
build_args = (manifest or {}).get("build_args")
if not isinstance(build_args, dict):
return None
profile_path = build_args.get("profile_path_abs")
if not isinstance(profile_path, str) or not profile_path:
return None
return Path(profile_path)

Xet Storage Details

Size:
28.2 kB
·
Xet hash:
8ce273df01a157dcd5ebe63149998029baad252d5fcb75d1d1a565057c293f9a

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.