feat(manifest): trusted agent forge identity and guidance
Implements PRD prd-new-trusted-agent-forge-identity. Moves author identity and named forge configurations onto the trusted, host-only agent definition, and lets a bottle repository optionally associate a git-gate repo with one of the agent's forge aliases. - Agent-owned identity: new `author` (name/email) and `forge-accounts` (alias -> canonical Gitea /api/v1 origin + host `token_secret` ref) on the agent manifest. `author` populates the bottle's git user.name/user.email. - Remove `git-gate.user` from both agents and bottles; fail with a migration pointer to `author`. `git-gate` is no longer accepted on an agent. - Bottle git-gate repos gain optional `forge: <alias>`, resolved against the selected agent's forge-accounts at composition (fail-closed on unknown). - Fail-closed Gitea API URL validation (https, no userinfo/query/fragment, /api/v1 base, host lowercased, trailing slash normalized, host dedup). - Proxy-held credential: synthesize one inspected, token-authenticated egress route per referenced forge alias, scoped to the origin + API prefix. The token is resolved from the host env at launch into the egress proxy only — never the bottle env, prompt, gitconfig, or workspace. - Generated, non-secret forge workflow guidance appended to the agent prompt for associated repos (API base, branch-backed PR flow, AGit-ref prohibition, mutation verification); omitted when no repo declares a forge. - Agents become home-only: cwd `.bot-bottle/agents` no longer contributes, overrides, or is selectable; warned-and-ignored like cwd bottles. - Docs: README examples, PRD 0011 supersession note, manifest schema docstring. - Tests: new test_forge_identity suite; legacy git-gate.user/cwd tests updated to the agent-owned identity model. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -118,7 +118,7 @@ class BottlePreparationPlanner:
|
||||
slug=slug,
|
||||
resolved_env=resolved_env,
|
||||
agent_provision_plan=provision,
|
||||
egress_plan=prepare_egress(bottle, slug, provision),
|
||||
egress_plan=prepare_egress(manifest, slug, provision),
|
||||
git_gate_plan=prepare_git_gate(bottle, slug),
|
||||
supervise_plan=prepare_supervise(bottle, slug),
|
||||
)
|
||||
|
||||
@@ -24,10 +24,11 @@ from ..bottle_state import (
|
||||
supervise_state_dir,
|
||||
write_metadata,
|
||||
)
|
||||
from ..egress import Egress, EgressPlan
|
||||
from ..egress import Egress, EgressPlan, egress_forge_routes
|
||||
from ..git_gate import GitGate, GitGatePlan
|
||||
from ..log import die
|
||||
from ..manifest import Manifest, ManifestBottle
|
||||
from ..manifest.forge import render_forge_guidance
|
||||
from ..supervisor.plan import SupervisePlan
|
||||
from ..orchestrator.supervisor import Supervisor
|
||||
from ..util import slugify
|
||||
@@ -71,12 +72,21 @@ def write_launch_metadata(
|
||||
|
||||
def prepare_agent_state_dir(slug: str, manifest: Manifest) -> tuple[Path, Path]:
|
||||
"""Create the agent state subdir, write the prompt file.
|
||||
Returns (agent_dir, prompt_file)."""
|
||||
Returns (agent_dir, prompt_file).
|
||||
|
||||
For repositories associated with a forge, appends generated, non-secret
|
||||
provider-specific workflow guidance to the prompt (PRD
|
||||
prd-new-trusted-agent-forge-identity). The guidance carries neither the
|
||||
token value nor its `token_secret` name."""
|
||||
agent = manifest.agent
|
||||
agent_dir = agent_state_dir(slug)
|
||||
agent_dir.mkdir(parents=True, exist_ok=True)
|
||||
prompt_file = agent_dir / "prompt.txt"
|
||||
prompt_file.write_text(agent.prompt or "")
|
||||
prompt = agent.prompt or ""
|
||||
guidance = render_forge_guidance(manifest.forge_associations)
|
||||
if guidance:
|
||||
prompt = f"{prompt.rstrip()}\n\n{guidance}" if prompt.strip() else guidance
|
||||
prompt_file.write_text(prompt)
|
||||
prompt_file.chmod(0o600)
|
||||
return agent_dir, prompt_file
|
||||
|
||||
@@ -88,11 +98,18 @@ def prepare_git_gate(bottle: ManifestBottle, slug: str) -> GitGatePlan:
|
||||
|
||||
|
||||
def prepare_egress(
|
||||
bottle: ManifestBottle, slug: str, provision: AgentProvisionPlan,
|
||||
manifest: Manifest, slug: str, provision: AgentProvisionPlan,
|
||||
) -> EgressPlan:
|
||||
"""Build the egress plan, adding a scoped, proxy-held Gitea API route for
|
||||
each forge alias referenced by a selected git-gate repo (PRD
|
||||
prd-new-trusted-agent-forge-identity). The token is resolved from the host
|
||||
env at launch and never enters the bottle."""
|
||||
egress_dir = egress_state_dir(slug)
|
||||
egress_dir.mkdir(parents=True, exist_ok=True)
|
||||
return Egress().prepare(bottle, slug, egress_dir, provision.egress_routes)
|
||||
forge_routes = egress_forge_routes(manifest.forge_associations)
|
||||
return Egress().prepare(
|
||||
manifest.bottle, slug, egress_dir, provision.egress_routes, forge_routes,
|
||||
)
|
||||
|
||||
|
||||
def prepare_supervise(bottle: ManifestBottle, slug: str) -> SupervisePlan | None:
|
||||
|
||||
@@ -128,7 +128,7 @@ def cmd_start(argv: list[str]) -> int:
|
||||
if not manifest.all_agent_names:
|
||||
print(
|
||||
"bot-bottle: no agents defined. "
|
||||
"Add an agent to ~/.bot-bottle/agents/ or ./bot-bottle/agents/ to get started.",
|
||||
"Add an agent to ~/.bot-bottle/agents/ to get started.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
@@ -383,12 +383,9 @@ def _peek_agent_bottle(manifest: ManifestIndex, agent_name: str) -> str:
|
||||
from ...manifest.loader import scan_agent_names
|
||||
from ...yaml_subset import YamlSubsetError, parse_frontmatter
|
||||
|
||||
# Agents are home-only (PRD prd-new-trusted-agent-forge-identity).
|
||||
home_agents = scan_agent_names(manifest.home_md / "agents")
|
||||
cwd_agents: dict[str, Path] = {}
|
||||
if manifest.cwd_md is not None:
|
||||
cwd_agents = scan_agent_names(manifest.cwd_md / "agents")
|
||||
merged = {**home_agents, **cwd_agents}
|
||||
path = merged.get(agent_name)
|
||||
path = home_agents.get(agent_name)
|
||||
if path is None:
|
||||
return ""
|
||||
try:
|
||||
@@ -488,13 +485,19 @@ def _manifest_to_yaml(manifest: Manifest) -> str:
|
||||
lines.append(" skills:")
|
||||
for s in agent.skills:
|
||||
lines.append(f" - {s}")
|
||||
if not agent.git_user.is_empty():
|
||||
lines.append(" git-gate:")
|
||||
lines.append(" user:")
|
||||
if agent.git_user.name:
|
||||
lines.append(f" name: {agent.git_user.name}")
|
||||
if agent.git_user.email:
|
||||
lines.append(f" email: {agent.git_user.email}")
|
||||
if agent.author is not None:
|
||||
lines.append(" author:")
|
||||
lines.append(f" name: {agent.author.name}")
|
||||
lines.append(f" email: {agent.author.email}")
|
||||
if agent.forge_accounts:
|
||||
lines.append(" forge-accounts:")
|
||||
for alias, acct in sorted(agent.forge_accounts.items()):
|
||||
lines.append(f" {alias}:")
|
||||
lines.append(f" url: {acct.url}")
|
||||
lines.append(" auth:")
|
||||
lines.append(f" type: {acct.auth_type}")
|
||||
# token_secret name is host config; show the name, never a value.
|
||||
lines.append(f" token_secret: {acct.token_secret}")
|
||||
|
||||
bottle = manifest.bottle
|
||||
lines.append("bottle:")
|
||||
@@ -510,20 +513,14 @@ def _manifest_to_yaml(manifest: Manifest) -> str:
|
||||
for k, v in sorted(bottle.env.items()):
|
||||
lines.append(f" {k}: {v}")
|
||||
|
||||
has_git_gate = not bottle.git_user.is_empty() or bottle.git
|
||||
if has_git_gate:
|
||||
if bottle.git:
|
||||
lines.append(" git-gate:")
|
||||
if not bottle.git_user.is_empty():
|
||||
lines.append(" user:")
|
||||
if bottle.git_user.name:
|
||||
lines.append(f" name: {bottle.git_user.name}")
|
||||
if bottle.git_user.email:
|
||||
lines.append(f" email: {bottle.git_user.email}")
|
||||
if bottle.git:
|
||||
lines.append(" repos:")
|
||||
for entry in bottle.git:
|
||||
lines.append(f" {entry.Name}:")
|
||||
lines.append(f" url: {entry.Upstream}")
|
||||
lines.append(" repos:")
|
||||
for entry in bottle.git:
|
||||
lines.append(f" {entry.Name}:")
|
||||
lines.append(f" url: {entry.Upstream}")
|
||||
if entry.Forge:
|
||||
lines.append(f" forge: {entry.Forge}")
|
||||
|
||||
if bottle.egress.routes:
|
||||
lines.append(" egress:")
|
||||
|
||||
@@ -32,6 +32,7 @@ if TYPE_CHECKING:
|
||||
EGRESS_ROUTES_IN_CONTAINER,
|
||||
Egress,
|
||||
egress_agent_env_entries,
|
||||
egress_forge_routes,
|
||||
egress_gateway_env_entries,
|
||||
egress_manifest_routes,
|
||||
egress_render_routes,
|
||||
@@ -51,6 +52,7 @@ _LAZY: dict[str, str] = {
|
||||
"EGRESS_ROUTES_FILENAME": ".service",
|
||||
"EGRESS_ROUTES_IN_CONTAINER": ".service",
|
||||
"egress_agent_env_entries": ".service",
|
||||
"egress_forge_routes": ".service",
|
||||
"egress_gateway_env_entries": ".service",
|
||||
"egress_manifest_routes": ".service",
|
||||
"egress_render_routes": ".service",
|
||||
@@ -80,6 +82,7 @@ __all__ = [
|
||||
"Egress",
|
||||
"EgressPlan",
|
||||
"EgressRoute",
|
||||
"egress_forge_routes",
|
||||
"egress_manifest_routes",
|
||||
"egress_render_routes",
|
||||
"egress_resolve_token_values",
|
||||
|
||||
@@ -26,7 +26,7 @@ from ..log import die
|
||||
from .plan import EgressPlan, EgressRoute
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..manifest import ManifestBottle
|
||||
from ..manifest import ManifestBottle, ResolvedForgeAssociation
|
||||
|
||||
|
||||
CODEX_HOST_CREDENTIAL_TOKEN_REF = "BOT_BOTTLE_CODEX_HOST_ACCESS_TOKEN"
|
||||
@@ -119,15 +119,56 @@ def egress_manifest_routes(
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def egress_forge_routes(
|
||||
associations: "tuple[ResolvedForgeAssociation, ...]",
|
||||
) -> tuple[EgressRoute, ...]:
|
||||
"""Synthesize one inspected, token-authenticated egress route per distinct
|
||||
forge alias referenced by a selected git-gate repo (PRD
|
||||
prd-new-trusted-agent-forge-identity).
|
||||
|
||||
The route is scoped to the canonical forge origin (host) and API prefix
|
||||
(`/api/v1`): the proxy injects the Gitea `token` scheme using the value of
|
||||
the host env var named by the account's `token_secret`, resolved at launch
|
||||
from the host environment — the token never enters the bottle. Aliases that
|
||||
canonicalize to the same host share a single route (deduplicated)."""
|
||||
out: list[EgressRoute] = []
|
||||
seen_hosts: set[str] = set()
|
||||
for assoc in associations:
|
||||
acct = assoc.account
|
||||
host_key = acct.host.lower()
|
||||
if host_key in seen_hosts:
|
||||
continue
|
||||
seen_hosts.add(host_key)
|
||||
out.append(EgressRoute(
|
||||
host=acct.host,
|
||||
matches=(CoreMatchEntry(
|
||||
paths=(CorePathMatch(type="prefix", value=acct.api_prefix),),
|
||||
),),
|
||||
auth_scheme=acct.auth_type,
|
||||
token_ref=acct.token_secret,
|
||||
inspect=True,
|
||||
))
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def egress_routes_for_bottle(
|
||||
bottle: ManifestBottle,
|
||||
provider_routes: tuple[EgressRoute, ...] = (),
|
||||
forge_routes: tuple[EgressRoute, ...] = (),
|
||||
) -> tuple[EgressRoute, ...]:
|
||||
manifest = egress_manifest_routes(bottle)
|
||||
provisioned_hosts = {pr.host.lower() for pr in provider_routes}
|
||||
merged = list(_default_provider_on_match(provider_routes)) + [
|
||||
r for r in manifest if r.host.lower() not in provisioned_hosts
|
||||
]
|
||||
# Provider routes (LLM API) default to redact-on-match; forge routes are
|
||||
# host-injected but keep the default DLP policy. Both take precedence over
|
||||
# a manifest route to the same host.
|
||||
reserved_hosts = (
|
||||
{pr.host.lower() for pr in provider_routes}
|
||||
| {fr.host.lower() for fr in forge_routes}
|
||||
)
|
||||
merged = (
|
||||
list(_default_provider_on_match(provider_routes))
|
||||
+ list(forge_routes)
|
||||
+ [r for r in manifest if r.host.lower() not in reserved_hosts]
|
||||
)
|
||||
return _assign_token_slots(merged)
|
||||
|
||||
|
||||
@@ -367,8 +408,9 @@ class Egress:
|
||||
slug: str,
|
||||
stage_dir: Path,
|
||||
provider_routes: tuple[EgressRoute, ...] = (),
|
||||
forge_routes: tuple[EgressRoute, ...] = (),
|
||||
) -> EgressPlan:
|
||||
routes = egress_routes_for_bottle(bottle, provider_routes)
|
||||
routes = egress_routes_for_bottle(bottle, provider_routes, forge_routes)
|
||||
log = bottle.egress.Log
|
||||
routes_path = stage_dir / EGRESS_ROUTES_FILENAME
|
||||
routes_path.write_text(egress_render_routes(routes, log=log))
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""Manifest dataclasses (PRD 0011 layout).
|
||||
|
||||
Reads the per-file manifest tree:
|
||||
Reads the per-file manifest tree (home-only —
|
||||
PRD prd-new-trusted-agent-forge-identity):
|
||||
|
||||
$HOME/.bot-bottle/bottles/<name>.md — one bottle per file
|
||||
$HOME/.bot-bottle/agents/<name>.md — home-resident agents
|
||||
$CWD/.bot-bottle/agents/<name>.md — cwd-supplied agents
|
||||
$HOME/.bot-bottle/agents/<name>.md — agents
|
||||
|
||||
Each file is Markdown with YAML frontmatter. The frontmatter holds
|
||||
the structured config (see schema below); for agents the body is
|
||||
@@ -15,27 +15,38 @@ Bottle schema (frontmatter):
|
||||
extends: <bottle-name> # optional (PRD 0025)
|
||||
env: { <NAME>: <env-entry>, ... }
|
||||
git-gate: # optional (PRD 0047)
|
||||
user: { name: <str>, email: <str> } # optional
|
||||
repos: { <name>: <git-gate-entry>, ... } # optional
|
||||
# git-gate-entry keys: url, key, host_key, forge
|
||||
# `forge`: optional alias into the selected agent's forge-accounts
|
||||
egress: { routes: [ <egress-route>, ... ] }
|
||||
# route keys: host, matches, auth, role, dlp
|
||||
supervise: <bool> # optional (default true)
|
||||
nested_containers: <bool> # optional (default false)
|
||||
|
||||
Agent schema (frontmatter):
|
||||
bottle: <bottle-name> # required
|
||||
bottle: <bottle-name> # optional
|
||||
skills: [ <skill-name>, ... ] # optional
|
||||
git-gate:
|
||||
user: { name: <str>, email: <str> } # optional; overlays bottle
|
||||
author: # optional; agent git identity
|
||||
name: <str> # required when author is present
|
||||
email: <str> # required when author is present
|
||||
forge-accounts: # optional; alias -> forge account
|
||||
<alias>:
|
||||
url: <https Gitea /api/v1 base>
|
||||
auth: { type: token, token_secret: <host env var name> }
|
||||
# Claude Code subagent passthrough fields — accepted, ignored:
|
||||
name, description, model, color, memory
|
||||
|
||||
`author` populates the bottle's git user.name/user.email; `forge-accounts`
|
||||
maps a forge alias to a Gitea API origin plus a host token reference. Identity
|
||||
is agent-owned — `git-gate` is no longer accepted on an agent (git-gate.user
|
||||
moved to `author`; git-gate.repos is bottle-only).
|
||||
|
||||
The agent file's Markdown body is the system prompt (stripped).
|
||||
Unknown top-level frontmatter keys raise ManifestError with a hint.
|
||||
|
||||
Bottles can ONLY live under $HOME. A bottles/ dir under $CWD is a
|
||||
warn at load time and contributes nothing. The trust boundary is
|
||||
expressed as filesystem layout rather than resolver logic.
|
||||
Both bottles and agents can ONLY live under $HOME. An agents/ or bottles/
|
||||
dir under $CWD is a warn at load time and contributes nothing. The trust
|
||||
boundary is expressed as filesystem layout rather than resolver logic.
|
||||
|
||||
Two types are exported:
|
||||
|
||||
@@ -66,6 +77,11 @@ if TYPE_CHECKING:
|
||||
from .agent import ManifestAgent, ManifestAgentProvider
|
||||
from .bottle import ManifestBottle
|
||||
from .egress import EGRESS_AUTH_SCHEMES, ManifestEgressConfig, ManifestEgressRoute
|
||||
from .forge import (
|
||||
ManifestAuthor,
|
||||
ManifestForgeAccount,
|
||||
ResolvedForgeAssociation,
|
||||
)
|
||||
from .git import ManifestGitEntry, ManifestGitUser, ManifestKeyConfig
|
||||
|
||||
|
||||
@@ -81,6 +97,9 @@ _LAZY_MODULES: dict[str, str] = {
|
||||
"EGRESS_AUTH_SCHEMES": "egress",
|
||||
"ManifestEgressRoute": "egress",
|
||||
"ManifestEgressConfig": "egress",
|
||||
"ManifestAuthor": "forge",
|
||||
"ManifestForgeAccount": "forge",
|
||||
"ResolvedForgeAssociation": "forge",
|
||||
"ManifestGitEntry": "git",
|
||||
"ManifestGitUser": "git",
|
||||
"ManifestKeyConfig": "git",
|
||||
@@ -115,4 +134,7 @@ __all__ = [
|
||||
"EGRESS_AUTH_SCHEMES",
|
||||
"ManifestEgressRoute",
|
||||
"ManifestEgressConfig",
|
||||
"ManifestAuthor",
|
||||
"ManifestForgeAccount",
|
||||
"ResolvedForgeAssociation",
|
||||
]
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import cast
|
||||
from typing import Mapping, cast
|
||||
|
||||
from ..agent_provider import PROVIDER_TEMPLATES
|
||||
from .util import ManifestError, as_json_object
|
||||
from .git import ManifestGitUser
|
||||
from .forge import ManifestAuthor, ManifestForgeAccount
|
||||
from .schema import AGENT_MODEL_KEYS, is_valid_entity_name
|
||||
|
||||
|
||||
@@ -119,15 +119,29 @@ class ManifestAgent:
|
||||
bottle: str = ""
|
||||
skills: tuple[str, ...] = ()
|
||||
prompt: str = ""
|
||||
# Per-agent git identity (issue #94). Overlays the referenced
|
||||
# bottle's git-gate.user per-field at `Manifest.bottle_for`. Only
|
||||
# `user` is allowed at the agent level; `repos` stays bottle-only
|
||||
# because it carries credentials and host trust.
|
||||
git_user: ManifestGitUser = ManifestGitUser()
|
||||
# Agent-owned identity (PRD prd-new-trusted-agent-forge-identity).
|
||||
# `author` populates the bottle's git user.name/user.email;
|
||||
# `forge_accounts` maps a forge alias to a canonical Gitea API origin and
|
||||
# a host token reference. Both live only on the agent — never under
|
||||
# `git-gate`, which is bottle-only transport policy.
|
||||
author: ManifestAuthor | None = None
|
||||
forge_accounts: Mapping[str, ManifestForgeAccount] = field(
|
||||
default_factory=dict
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, name: str, raw: object, bottle_names: set[str]) -> "ManifestAgent":
|
||||
d = as_json_object(raw, f"agent '{name}'")
|
||||
# git-gate is no longer accepted on an agent (checked before the
|
||||
# generic unknown-key error so the migration pointer is surfaced):
|
||||
# identity moved to `author`, and git-gate.repos is bottle-only.
|
||||
if "git-gate" in d:
|
||||
raise ManifestError(
|
||||
f"agent '{name}' has a 'git-gate' block, which is no longer "
|
||||
f"accepted on an agent (PRD prd-new-trusted-agent-forge-identity). "
|
||||
f"Move git-gate.user name/email into the 'author' block; "
|
||||
f"git-gate.repos stays on the bottle."
|
||||
)
|
||||
unknown = set(d.keys()) - AGENT_MODEL_KEYS
|
||||
if unknown:
|
||||
allowed = ", ".join(sorted(AGENT_MODEL_KEYS))
|
||||
@@ -191,24 +205,30 @@ class ManifestAgent:
|
||||
f"(was {type(prompt_raw).__name__})"
|
||||
)
|
||||
|
||||
# git-gate: agents may declare only `git-gate.user` (name/email).
|
||||
# `git-gate.repos` is bottle-only — it carries credentials and host trust.
|
||||
git_user = ManifestGitUser()
|
||||
git_raw = d.get("git-gate")
|
||||
if git_raw is not None:
|
||||
gd = as_json_object(git_raw, f"agent '{name}' git-gate")
|
||||
for k in gd:
|
||||
if k != "user":
|
||||
raise ManifestError(
|
||||
f"agent '{name}' git-gate.{k} is not allowed at the "
|
||||
f"agent level; only git-gate.user (name/email) may be "
|
||||
f"set on an agent. git-gate.repos is bottle-only "
|
||||
f"(it carries credentials and host trust)."
|
||||
)
|
||||
if "user" in gd:
|
||||
git_user = ManifestGitUser.from_dict(name, gd["user"])
|
||||
# author: agent-owned git identity (optional; both fields required
|
||||
# when present). Populates the bottle's user.name/user.email.
|
||||
author = (
|
||||
ManifestAuthor.from_dict(name, d["author"])
|
||||
if "author" in d else None
|
||||
)
|
||||
|
||||
return cls(bottle=bottle, skills=skills, prompt=prompt, git_user=git_user)
|
||||
# forge-accounts: alias -> Gitea API origin + host token reference.
|
||||
forge_accounts: dict[str, ManifestForgeAccount] = {}
|
||||
forge_raw = d.get("forge-accounts")
|
||||
if forge_raw is not None:
|
||||
forge_d = as_json_object(forge_raw, f"agent '{name}' forge-accounts")
|
||||
for alias, entry in forge_d.items():
|
||||
forge_accounts[alias] = ManifestForgeAccount.from_dict(
|
||||
name, alias, entry,
|
||||
)
|
||||
|
||||
return cls(
|
||||
bottle=bottle,
|
||||
skills=skills,
|
||||
prompt=prompt,
|
||||
author=author,
|
||||
forge_accounts=forge_accounts,
|
||||
)
|
||||
|
||||
|
||||
def _parse_provider_settings(
|
||||
|
||||
@@ -107,11 +107,14 @@ class ManifestBottle:
|
||||
)
|
||||
env[var] = value
|
||||
|
||||
# `git_user` is now an internal resolved carrier populated from the
|
||||
# selected agent's `author` at composition time — it is never parsed
|
||||
# from the bottle manifest (PRD prd-new-trusted-agent-forge-identity).
|
||||
git: tuple[ManifestGitEntry, ...] = ()
|
||||
git_user = ManifestGitUser()
|
||||
git_raw = d.get("git-gate")
|
||||
if git_raw is not None:
|
||||
git, git_user = parse_git_gate_config(name, git_raw)
|
||||
git = parse_git_gate_config(name, git_raw)
|
||||
|
||||
agent_provider = (
|
||||
ManifestAgentProvider.from_dict(name, d["agent_provider"])
|
||||
|
||||
@@ -210,7 +210,7 @@ def _fold_two_bottles(
|
||||
for n in names
|
||||
}
|
||||
if merged_repos_raw:
|
||||
merged_git, _ = parse_git_gate_config("_fold", {"repos": merged_repos_raw})
|
||||
merged_git = parse_git_gate_config("_fold", {"repos": merged_repos_raw})
|
||||
else:
|
||||
merged_git = ()
|
||||
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
"""Agent-owned author identity and forge accounts (PRD prd-new-trusted-agent-forge-identity).
|
||||
|
||||
`ManifestAuthor` is the agent's git author identity (name/email) — it moved off
|
||||
`git-gate.user` (PRD 0027 / ADR 0002) and onto the trusted agent definition.
|
||||
|
||||
`ManifestForgeAccount` maps a **forge alias** to a canonical HTTPS Gitea API
|
||||
origin plus the *name* of a host env var holding the operator-provided API
|
||||
token. The token value never lives on the manifest; the host resolves it only
|
||||
when a selected bottle repository references the alias, and hands it to the
|
||||
egress proxy — never to the bottle.
|
||||
|
||||
`ResolvedForgeAssociation` is the composed view: one distinct forge alias that
|
||||
at least one selected git-gate repository points at, with the repository names
|
||||
that reference it. The proxy-provisioning and prompt-guidance steps consume it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import urllib.parse
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .schema import is_valid_entity_name
|
||||
from .util import ManifestError, as_json_object
|
||||
|
||||
# Only the Gitea `/api/v1` base is supported today. A future provider adds a
|
||||
# validator + auth scheme + guidance renderer in code rather than accepting a
|
||||
# repository-supplied prompt or path (PRD non-goal: provider-generic prompts).
|
||||
GITEA_API_PREFIX = "/api/v1"
|
||||
|
||||
# Auth schemes an agent forge account may declare. Gitea uses `token`.
|
||||
FORGE_AUTH_TYPES = ("token",)
|
||||
|
||||
|
||||
def canonicalize_forge_url(
|
||||
agent_name: str, alias: str, url: object,
|
||||
) -> tuple[str, str, str, str]:
|
||||
"""Validate and canonicalize a forge account's API base URL.
|
||||
|
||||
Returns `(canonical, origin, host, api_prefix)` where `origin` is
|
||||
`https://host[:port]` and `canonical` is `origin + api_prefix`.
|
||||
|
||||
Fails closed on: non-string, non-`https`, embedded userinfo, query, or
|
||||
fragment, a missing host, or any path other than the supported Gitea API
|
||||
base (`/api/v1`, trailing slash tolerated)."""
|
||||
label = f"agent '{agent_name}' forge-accounts.{alias}.url"
|
||||
if not isinstance(url, str) or not url:
|
||||
raise ManifestError(f"{label} is required (non-empty string)")
|
||||
try:
|
||||
parts = urllib.parse.urlsplit(url)
|
||||
except ValueError as e:
|
||||
raise ManifestError(f"{label} is not a valid URL ({e}): {url!r}") from e
|
||||
|
||||
if parts.scheme != "https":
|
||||
raise ManifestError(
|
||||
f"{label} must use https (got scheme {parts.scheme!r} in {url!r})"
|
||||
)
|
||||
if parts.username or parts.password:
|
||||
raise ManifestError(
|
||||
f"{label} must not embed userinfo (user:pass@); the token is held "
|
||||
f"host-side via auth.token_secret. Got {url!r}"
|
||||
)
|
||||
if parts.query:
|
||||
raise ManifestError(f"{label} must not contain a query string: {url!r}")
|
||||
if parts.fragment:
|
||||
raise ManifestError(f"{label} must not contain a fragment: {url!r}")
|
||||
|
||||
host = parts.hostname
|
||||
if not host:
|
||||
raise ManifestError(f"{label} must include a hostname: {url!r}")
|
||||
|
||||
path = parts.path.rstrip("/")
|
||||
if path != GITEA_API_PREFIX:
|
||||
raise ManifestError(
|
||||
f"{label} path must be the Gitea API base '{GITEA_API_PREFIX}' "
|
||||
f"(got {parts.path!r} in {url!r}); other providers and API paths "
|
||||
f"are not yet supported."
|
||||
)
|
||||
|
||||
host = host.lower()
|
||||
netloc = host if parts.port is None else f"{host}:{parts.port}"
|
||||
origin = f"https://{netloc}"
|
||||
return f"{origin}{path}", origin, host, path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ManifestAuthor:
|
||||
"""The agent's git author identity. Both fields are required and
|
||||
non-empty — an author that is declared must fully identify the agent.
|
||||
Populates `user.name` / `user.email` inside the bottle."""
|
||||
|
||||
name: str
|
||||
email: str
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, agent_name: str, raw: object) -> "ManifestAuthor":
|
||||
d = as_json_object(raw, f"agent '{agent_name}' author")
|
||||
for k in d:
|
||||
if k not in {"name", "email"}:
|
||||
raise ManifestError(
|
||||
f"agent '{agent_name}' author has unknown key {k!r}; "
|
||||
f"allowed: name, email"
|
||||
)
|
||||
name = d.get("name")
|
||||
if not isinstance(name, str) or not name:
|
||||
raise ManifestError(
|
||||
f"agent '{agent_name}' author.name must be a non-empty string"
|
||||
)
|
||||
email = d.get("email")
|
||||
if not isinstance(email, str) or not email:
|
||||
raise ManifestError(
|
||||
f"agent '{agent_name}' author.email must be a non-empty string"
|
||||
)
|
||||
# Git identity validation: reject values that would break the
|
||||
# `git config user.email` line or smuggle a second config directive.
|
||||
if any(c in email for c in ("\n", "\r", " ", "\t")):
|
||||
raise ManifestError(
|
||||
f"agent '{agent_name}' author.email must not contain whitespace "
|
||||
f"or newlines (got {email!r})"
|
||||
)
|
||||
if any(c in name for c in ("\n", "\r")):
|
||||
raise ManifestError(
|
||||
f"agent '{agent_name}' author.name must not contain newlines "
|
||||
f"(got {name!r})"
|
||||
)
|
||||
return cls(name=name, email=email)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ManifestForgeAccount:
|
||||
"""One forge alias on an agent: a canonical Gitea API origin plus the
|
||||
host env var name that holds the agent-specific API token. The
|
||||
authenticated account is whoever owns that token — there is no separate
|
||||
account-name field."""
|
||||
|
||||
alias: str
|
||||
url: str # canonical https base incl. /api/v1, no trailing slash
|
||||
origin: str # https://host[:port]
|
||||
host: str # lowercased hostname
|
||||
api_prefix: str # /api/v1
|
||||
auth_type: str # "token"
|
||||
token_secret: str # host env var name holding the API token
|
||||
|
||||
@classmethod
|
||||
def from_dict(
|
||||
cls, agent_name: str, alias: str, raw: object,
|
||||
) -> "ManifestForgeAccount":
|
||||
if not is_valid_entity_name(alias):
|
||||
raise ManifestError(
|
||||
f"agent '{agent_name}' forge-accounts key {alias!r} is not a "
|
||||
f"valid alias; must match [a-z][a-z0-9-]*"
|
||||
)
|
||||
label = f"agent '{agent_name}' forge-accounts.{alias}"
|
||||
d = as_json_object(raw, label)
|
||||
for k in d:
|
||||
if k not in {"url", "auth"}:
|
||||
raise ManifestError(
|
||||
f"{label} has unknown key {k!r}; allowed: url, auth"
|
||||
)
|
||||
|
||||
canonical, origin, host, api_prefix = canonicalize_forge_url(
|
||||
agent_name, alias, d.get("url"),
|
||||
)
|
||||
|
||||
if "auth" not in d:
|
||||
raise ManifestError(f"{label} missing required 'auth' block")
|
||||
auth = as_json_object(d.get("auth"), f"{label}.auth")
|
||||
for k in auth:
|
||||
if k not in {"type", "token_secret"}:
|
||||
raise ManifestError(
|
||||
f"{label}.auth has unknown key {k!r}; allowed: type, "
|
||||
f"token_secret"
|
||||
)
|
||||
auth_type = auth.get("type")
|
||||
if auth_type not in FORGE_AUTH_TYPES:
|
||||
raise ManifestError(
|
||||
f"{label}.auth.type must be one of "
|
||||
f"{', '.join(FORGE_AUTH_TYPES)} (got {auth_type!r})"
|
||||
)
|
||||
token_secret = auth.get("token_secret")
|
||||
if not isinstance(token_secret, str) or not token_secret:
|
||||
raise ManifestError(
|
||||
f"{label}.auth.token_secret must be a non-empty string (the "
|
||||
f"name of a host env var holding the API token)"
|
||||
)
|
||||
return cls(
|
||||
alias=alias,
|
||||
url=canonical,
|
||||
origin=origin,
|
||||
host=host,
|
||||
api_prefix=api_prefix,
|
||||
auth_type=str(auth_type),
|
||||
token_secret=token_secret,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedForgeAssociation:
|
||||
"""A distinct forge alias referenced by one or more selected git-gate
|
||||
repositories. `repo_names` lists the git-gate repo names pointing at
|
||||
`account.alias` (sorted, deduplicated)."""
|
||||
|
||||
account: ManifestForgeAccount
|
||||
repo_names: tuple[str, ...]
|
||||
|
||||
@property
|
||||
def alias(self) -> str:
|
||||
return self.account.alias
|
||||
|
||||
|
||||
def resolve_forge_associations(
|
||||
agent_name: str,
|
||||
forge_accounts: "dict[str, ManifestForgeAccount]",
|
||||
git_entries: "tuple[object, ...]",
|
||||
) -> tuple[ResolvedForgeAssociation, ...]:
|
||||
"""Compose the agent's forge accounts with the effective bottle's
|
||||
git-gate repos. Each git entry that declares a `forge` alias must match a
|
||||
forge account on the selected agent — otherwise fail closed before launch.
|
||||
|
||||
Returns one association per distinct referenced alias, carrying the repo
|
||||
names that reference it. Unreferenced accounts produce nothing (no token
|
||||
is resolved and no route is created for them)."""
|
||||
by_alias: dict[str, list[str]] = {}
|
||||
for entry in git_entries:
|
||||
alias = getattr(entry, "Forge", "")
|
||||
if not alias:
|
||||
continue
|
||||
if alias not in forge_accounts:
|
||||
available = ", ".join(sorted(forge_accounts)) or "(none)"
|
||||
raise ManifestError(
|
||||
f"git-gate.repos['{getattr(entry, 'Name', '?')}'].forge "
|
||||
f"references forge alias {alias!r}, which is not defined on "
|
||||
f"agent '{agent_name}'. Available forge-accounts: {available}"
|
||||
)
|
||||
by_alias.setdefault(alias, []).append(getattr(entry, "Name", ""))
|
||||
|
||||
return tuple(
|
||||
ResolvedForgeAssociation(
|
||||
account=forge_accounts[alias],
|
||||
repo_names=tuple(sorted(set(names))),
|
||||
)
|
||||
for alias, names in sorted(by_alias.items())
|
||||
)
|
||||
|
||||
|
||||
def render_forge_guidance(
|
||||
associations: tuple[ResolvedForgeAssociation, ...],
|
||||
) -> str:
|
||||
"""Render the non-secret, provider-specific forge workflow guidance
|
||||
appended to the agent's system prompt for associated repositories only.
|
||||
|
||||
Derived entirely from validated typed fields — never repository-supplied
|
||||
Markdown. Contains neither the token value nor its `token_secret` name.
|
||||
Returns "" when there are no associations (no section is generated)."""
|
||||
if not associations:
|
||||
return ""
|
||||
lines: list[str] = [
|
||||
"## Forge access (managed by bot-bottle)",
|
||||
"",
|
||||
"bot-bottle authenticates the forge API requests below for you "
|
||||
"through the egress proxy. Do not read, print, or manually attach "
|
||||
"an authorization token — the proxy injects it. Never place a token "
|
||||
"in a request.",
|
||||
]
|
||||
for assoc in associations:
|
||||
acct = assoc.account
|
||||
for repo in assoc.repo_names:
|
||||
lines.extend([
|
||||
"",
|
||||
f"### Repository `{repo}` (forge alias `{acct.alias}`)",
|
||||
f"- Forge API base URL: `{acct.url}`.",
|
||||
f"- This git-gate repository (`{repo}`) is tied to forge "
|
||||
f"`{acct.alias}`; use its API for forge actions on this repo.",
|
||||
f"- Call the API at `{acct.url}` over HTTPS through the proxy. "
|
||||
"The proxy adds authentication; you never supply a token "
|
||||
"yourself.",
|
||||
"- Git pushes still use the git-gate remote, not the API.",
|
||||
"- To propose changes: push a normal branch "
|
||||
"(`refs/heads/<branch>`) through the git-gate remote, then open "
|
||||
"a branch-backed pull request through the API.",
|
||||
"- Do NOT push AGit review refs (`refs/for/*`, `refs/draft/*`, "
|
||||
"`refs/for-review/*`); they are prohibited here.",
|
||||
"- Use the API for reviews and comments, and verify the "
|
||||
"returned object state before claiming the task is complete.",
|
||||
])
|
||||
return "\n".join(lines) + "\n"
|
||||
+38
-12
@@ -117,6 +117,11 @@ class ManifestGitEntry:
|
||||
UpstreamHost: str = ""
|
||||
UpstreamPort: str = ""
|
||||
UpstreamPath: str = ""
|
||||
# Optional forge alias (PRD prd-new-trusted-agent-forge-identity). When
|
||||
# set, it must match a `forge-accounts` alias on the selected agent; the
|
||||
# composition enables a scoped proxy-held API credential and forge
|
||||
# workflow guidance for this repo. Empty = no forge association.
|
||||
Forge: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_repos_entry(
|
||||
@@ -139,10 +144,10 @@ class ManifestGitEntry:
|
||||
label = f"git-gate.repos[{repo_name!r}]"
|
||||
d = as_json_object(raw, f"bottle '{bottle_name}' {label}")
|
||||
for k in d:
|
||||
if k not in {"url", "key", "host_key"}:
|
||||
if k not in {"url", "key", "host_key", "forge"}:
|
||||
raise ManifestError(
|
||||
f"bottle '{bottle_name}' {label} has unknown key {k!r}; "
|
||||
f"allowed: url, key, host_key"
|
||||
f"allowed: url, key, host_key, forge"
|
||||
)
|
||||
upstream = d.get("url")
|
||||
if not isinstance(upstream, str) or not upstream:
|
||||
@@ -150,6 +155,21 @@ class ManifestGitEntry:
|
||||
f"bottle '{bottle_name}' {label} missing required string field 'url'"
|
||||
)
|
||||
|
||||
forge = d.get("forge", "")
|
||||
if not isinstance(forge, str):
|
||||
raise ManifestError(
|
||||
f"bottle '{bottle_name}' {label} forge must be a string "
|
||||
f"(was {type(forge).__name__})"
|
||||
)
|
||||
if forge and not _GIT_NAME_RE.match(forge):
|
||||
# forge aliases follow the kebab-case identifier grammar; the
|
||||
# cross-check against the agent's forge-accounts happens at
|
||||
# composition time (it needs the resolved agent).
|
||||
raise ManifestError(
|
||||
f"bottle '{bottle_name}' {label} forge {forge!r} is not a "
|
||||
f"valid forge alias; allowed characters: A-Z a-z 0-9 . _ -"
|
||||
)
|
||||
|
||||
if "key" not in d:
|
||||
raise ManifestError(
|
||||
f"bottle '{bottle_name}' {label} missing required 'key' block"
|
||||
@@ -176,6 +196,7 @@ class ManifestGitEntry:
|
||||
UpstreamHost=host,
|
||||
UpstreamPort=port,
|
||||
UpstreamPath=path,
|
||||
Forge=forge,
|
||||
)
|
||||
|
||||
|
||||
@@ -286,21 +307,26 @@ class ManifestGitUser:
|
||||
def parse_git_gate_config(
|
||||
bottle_name: str,
|
||||
raw: object,
|
||||
) -> tuple[tuple[ManifestGitEntry, ...], ManifestGitUser]:
|
||||
) -> tuple[ManifestGitEntry, ...]:
|
||||
"""Parse `git-gate` on a bottle. Only `repos` is accepted; `git-gate.user`
|
||||
moved to the agent's `author` block (PRD prd-new-trusted-agent-forge-identity)."""
|
||||
d = as_json_object(raw, f"bottle '{bottle_name}' git-gate")
|
||||
if "user" in d:
|
||||
raise ManifestError(
|
||||
f"bottle '{bottle_name}' git-gate.user is no longer supported "
|
||||
f"(PRD prd-new-trusted-agent-forge-identity). Move name/email into "
|
||||
f"the selected home agent's 'author' block:\n"
|
||||
f" author:\n name: <name>\n email: <email>\n"
|
||||
f"Identity is agent-owned; git-gate now carries only transport "
|
||||
f"policy (repos)."
|
||||
)
|
||||
for k in d:
|
||||
if k not in {"user", "repos"}:
|
||||
if k != "repos":
|
||||
raise ManifestError(
|
||||
f"bottle '{bottle_name}' git-gate has unknown key {k!r}; "
|
||||
f"allowed: user, repos"
|
||||
f"allowed: repos"
|
||||
)
|
||||
|
||||
git_user = (
|
||||
ManifestGitUser.from_dict(bottle_name, d["user"])
|
||||
if "user" in d
|
||||
else ManifestGitUser()
|
||||
)
|
||||
|
||||
git: tuple[ManifestGitEntry, ...] = ()
|
||||
repos_raw = d.get("repos")
|
||||
if repos_raw is not None:
|
||||
@@ -311,4 +337,4 @@ def parse_git_gate_config(
|
||||
)
|
||||
validate_unique_git_names(bottle_name, git)
|
||||
|
||||
return git, git_user
|
||||
return git
|
||||
|
||||
@@ -19,6 +19,7 @@ from .util import ManifestError, as_json_object
|
||||
from .agent import ManifestAgent
|
||||
from .bottle import ManifestBottle
|
||||
from .extends import merge_bottles_runtime, resolve_bottles
|
||||
from .forge import ResolvedForgeAssociation, resolve_forge_associations
|
||||
from .git import ManifestGitUser
|
||||
from .loader import (
|
||||
check_stale_json,
|
||||
@@ -37,30 +38,50 @@ def _section_dict(value: object, label: str) -> dict[str, object]:
|
||||
return as_json_object(value, label)
|
||||
|
||||
|
||||
def _merge_git_user(
|
||||
agent_user: ManifestGitUser, base_user: ManifestGitUser
|
||||
) -> ManifestGitUser:
|
||||
"""Merge the agent's git.user over the bottle's, agent-wins-on-non-empty."""
|
||||
if agent_user.is_empty():
|
||||
return base_user
|
||||
return ManifestGitUser(
|
||||
name=agent_user.name or base_user.name,
|
||||
email=agent_user.email or base_user.email,
|
||||
def _warn_ignored_cwd_dir(cwd_dir: Path, kind: str, home_path: str) -> None:
|
||||
"""Warn (once) that manifest files of `kind` under `$CWD/.bot-bottle/`
|
||||
are ignored — the filesystem layout IS the trust boundary. `kind` is the
|
||||
subdir name (`bottles`/`agents`); `home_path` is where they belong."""
|
||||
stale = cwd_dir / kind
|
||||
if not stale.is_dir():
|
||||
return
|
||||
files = sorted(stale.glob("*.md"))
|
||||
if not files:
|
||||
return
|
||||
names = ", ".join(p.name for p in files)
|
||||
warn(
|
||||
f"ignoring {kind[:-1]} file(s) under {stale}: {names}. "
|
||||
f"{kind.capitalize()} can only live under {home_path} "
|
||||
f"(PRD prd-new-trusted-agent-forge-identity). Move them or delete."
|
||||
)
|
||||
|
||||
|
||||
def _manifest_with_merged_git_user(
|
||||
agent: "ManifestAgent", raw_bottle: "ManifestBottle"
|
||||
def _compose_manifest(
|
||||
agent_name: str,
|
||||
agent: "ManifestAgent",
|
||||
raw_bottle: "ManifestBottle",
|
||||
) -> "Manifest":
|
||||
"""Build the single-value Manifest, overlaying the agent's git-gate.user
|
||||
onto the bottle (agent wins on non-empty, per-field). Shared by the eager
|
||||
and lazy load_for_agent paths."""
|
||||
merged = _merge_git_user(agent.git_user, raw_bottle.git_user)
|
||||
bottle = (
|
||||
raw_bottle if merged == raw_bottle.git_user
|
||||
else replace(raw_bottle, git_user=merged)
|
||||
"""Build the single-value Manifest from the selected agent and its
|
||||
effective bottle (PRD prd-new-trusted-agent-forge-identity):
|
||||
|
||||
- the agent's `author` populates the bottle's git user.name/user.email;
|
||||
- each git-gate repo's `forge` alias is resolved against the agent's
|
||||
`forge-accounts` (failing closed on an unknown alias) into the
|
||||
Manifest's forge associations.
|
||||
|
||||
Shared by the eager (from_json_obj) and lazy (from_md_dirs) paths."""
|
||||
identity = (
|
||||
ManifestGitUser(name=agent.author.name, email=agent.author.email)
|
||||
if agent.author is not None else ManifestGitUser()
|
||||
)
|
||||
return Manifest(agent=agent, bottle=bottle)
|
||||
bottle = (
|
||||
raw_bottle if identity == raw_bottle.git_user
|
||||
else replace(raw_bottle, git_user=identity)
|
||||
)
|
||||
associations = resolve_forge_associations(
|
||||
agent_name, dict(agent.forge_accounts), bottle.git,
|
||||
)
|
||||
return Manifest(agent=agent, bottle=bottle, forge_associations=associations)
|
||||
|
||||
|
||||
def _resolve_effective_bottle_eager(
|
||||
@@ -121,26 +142,28 @@ def _resolve_effective_bottle_lazy(
|
||||
class Manifest:
|
||||
"""Single-agent/bottle value type. Returned by ManifestIndex.load_for_agent().
|
||||
|
||||
`bottle` is the effective bottle with the agent's git-gate.user already
|
||||
overlaid per-field (agent wins on non-empty). Backends and provisioners
|
||||
use this directly — no agent_name lookup needed."""
|
||||
`bottle` is the effective bottle with the agent's `author` already
|
||||
populated into its git identity. `forge_associations` holds the distinct
|
||||
forge aliases referenced by the effective bottle's git-gate repos, resolved
|
||||
against the agent's `forge-accounts`. Backends and provisioners use this
|
||||
directly — no agent_name lookup needed."""
|
||||
|
||||
agent: ManifestAgent
|
||||
bottle: ManifestBottle
|
||||
forge_associations: tuple[ResolvedForgeAssociation, ...] = ()
|
||||
|
||||
def git_identity_summary(self) -> str | None:
|
||||
"""One-line effective git identity with per-field provenance, e.g.
|
||||
`name=claude (agent), email=eric@dideric.is (bottle)`.
|
||||
Returns None when neither agent nor bottle sets an identity."""
|
||||
over = self.agent.git_user # agent's declared git_user (pre-merge)
|
||||
merged = self.bottle.git_user # effective git_user (post-merge)
|
||||
if merged.is_empty():
|
||||
"""One-line effective git identity, e.g.
|
||||
`name=claude, email=eric@dideric.is`. Sourced from the agent's
|
||||
`author` block. Returns None when the agent declares no author."""
|
||||
gu = self.bottle.git_user
|
||||
if gu.is_empty():
|
||||
return None
|
||||
parts: list[str] = []
|
||||
if merged.name:
|
||||
parts.append(f"name={merged.name} ({'agent' if over.name else 'bottle'})")
|
||||
if merged.email:
|
||||
parts.append(f"email={merged.email} ({'agent' if over.email else 'bottle'})")
|
||||
if gu.name:
|
||||
parts.append(f"name={gu.name}")
|
||||
if gu.email:
|
||||
parts.append(f"email={gu.email}")
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
@@ -164,15 +187,15 @@ class ManifestIndex:
|
||||
def resolve(cls, cwd: str, *, missing_ok: bool = False) -> "ManifestIndex":
|
||||
"""Walk the per-file manifest tree and build a ManifestIndex.
|
||||
|
||||
Layout (PRD 0011):
|
||||
Layout:
|
||||
$HOME/.bot-bottle/bottles/<name>.md — bottles (home-only)
|
||||
$HOME/.bot-bottle/agents/<name>.md — home agents
|
||||
$CWD/.bot-bottle/agents/<name>.md — cwd agents
|
||||
$HOME/.bot-bottle/agents/<name>.md — agents (home-only)
|
||||
|
||||
Cwd agents merge into the home agents on the same name
|
||||
(cwd wins). A bottles/ subdir under $CWD is logged as a
|
||||
warning and ignored — the filesystem layout IS the trust
|
||||
boundary.
|
||||
Both agents and bottles are home-only
|
||||
(PRD prd-new-trusted-agent-forge-identity): a `bottles/` or `agents/`
|
||||
subdir under $CWD is logged as a warning and ignored — the filesystem
|
||||
layout IS the trust boundary, since an agent may now select a host
|
||||
identity and forge secret.
|
||||
|
||||
If `missing_ok` is true, a missing `$HOME/.bot-bottle/`
|
||||
returns an empty index instead of dying. This is for
|
||||
@@ -223,17 +246,12 @@ class ManifestIndex:
|
||||
Used by tests to build a ManifestIndex from fixture directories
|
||||
without touching `os.environ`."""
|
||||
if cwd_dir is not None:
|
||||
stale_bottles = cwd_dir / "bottles"
|
||||
if stale_bottles.is_dir():
|
||||
files = sorted(stale_bottles.glob("*.md"))
|
||||
if files:
|
||||
names = ", ".join(p.name for p in files)
|
||||
warn(
|
||||
f"ignoring bottle file(s) under "
|
||||
f"{stale_bottles}: {names}. Bottles can only "
|
||||
f"live under $HOME/.bot-bottle/bottles/ "
|
||||
f"(PRD 0011). Move them or delete."
|
||||
)
|
||||
_warn_ignored_cwd_dir(cwd_dir, "bottles", "$HOME/.bot-bottle/bottles/")
|
||||
# Agents became home-only in
|
||||
# PRD prd-new-trusted-agent-forge-identity: a cwd agent file that
|
||||
# once shadowed a home agent could select a host identity/secret,
|
||||
# so it is now ignored with a migration pointer.
|
||||
_warn_ignored_cwd_dir(cwd_dir, "agents", "$HOME/.bot-bottle/agents/")
|
||||
return cls(bottles={}, agents={}, home_md=home_dir, cwd_md=cwd_dir)
|
||||
|
||||
@classmethod
|
||||
@@ -275,13 +293,12 @@ class ManifestIndex:
|
||||
|
||||
In names-only mode (from resolve/from_md_dirs) this scans agent
|
||||
filenames without reading their content. In eager mode (from
|
||||
from_json_obj) it returns the pre-parsed agents' names."""
|
||||
from_json_obj) it returns the pre-parsed agents' names.
|
||||
|
||||
Agents are home-only (PRD prd-new-trusted-agent-forge-identity): cwd
|
||||
agent files never contribute names."""
|
||||
if self.home_md is not None:
|
||||
home_names = set(scan_agent_names(self.home_md / "agents").keys())
|
||||
cwd_names: set[str] = set()
|
||||
if self.cwd_md is not None:
|
||||
cwd_names = set(scan_agent_names(self.cwd_md / "agents").keys())
|
||||
return sorted(home_names | cwd_names)
|
||||
return sorted(scan_agent_names(self.home_md / "agents").keys())
|
||||
return sorted(self.agents.keys())
|
||||
|
||||
def load_for_agent(
|
||||
@@ -326,7 +343,7 @@ class ManifestIndex:
|
||||
raw_bottle = _resolve_effective_bottle_eager(
|
||||
agent_name, agent, bottle_names, self.bottles
|
||||
)
|
||||
return _manifest_with_merged_git_user(agent, raw_bottle)
|
||||
return _compose_manifest(agent_name, agent, raw_bottle)
|
||||
|
||||
def _load_for_agent_lazy(
|
||||
self, agent_name: str, bottle_names: tuple[str, ...]
|
||||
@@ -334,20 +351,17 @@ class ManifestIndex:
|
||||
"""Lazy path (resolve/from_md_dirs): read and parse the agent file and
|
||||
its bottle chain from disk for the first time here."""
|
||||
assert self.home_md is not None # guaranteed by load_for_agent dispatch
|
||||
# Locate the agent file; cwd wins over home on name collision.
|
||||
# Agents are home-only (PRD prd-new-trusted-agent-forge-identity):
|
||||
# a cwd agent file must not select a host identity or forge secret.
|
||||
home_agents = scan_agent_names(self.home_md / "agents")
|
||||
cwd_agents: dict[str, Path] = {}
|
||||
if self.cwd_md is not None:
|
||||
cwd_agents = scan_agent_names(self.cwd_md / "agents")
|
||||
merged_agents = {**home_agents, **cwd_agents}
|
||||
|
||||
if agent_name not in merged_agents:
|
||||
available = ", ".join(sorted(merged_agents.keys())) or "(none)"
|
||||
if agent_name not in home_agents:
|
||||
available = ", ".join(sorted(home_agents.keys())) or "(none)"
|
||||
raise ManifestError(
|
||||
f"agent '{agent_name}' not defined. Available: {available}"
|
||||
)
|
||||
|
||||
agent_path = merged_agents[agent_name]
|
||||
agent_path = home_agents[agent_name]
|
||||
try:
|
||||
fm, body = parse_frontmatter(agent_path.read_text())
|
||||
except OSError as e:
|
||||
@@ -374,15 +388,18 @@ class ManifestIndex:
|
||||
}
|
||||
if agent_bottle:
|
||||
agent_dict["bottle"] = agent_bottle
|
||||
if "git-gate" in fm:
|
||||
agent_dict["git-gate"] = fm["git-gate"]
|
||||
# Surface agent-owned identity keys (and any stale git-gate, so
|
||||
# ManifestAgent.from_dict raises the migration error).
|
||||
for key in ("author", "forge-accounts", "git-gate"):
|
||||
if key in fm:
|
||||
agent_dict[key] = fm[key]
|
||||
# Pass the effective bottle name as the known-bottles set so agents
|
||||
# that have bottle: set are validated; agents without bottle: pass {}
|
||||
# since bottle_names were already resolved above.
|
||||
known = {effective_bottle_name} if effective_bottle_name else set()
|
||||
agent = ManifestAgent.from_dict(agent_name, agent_dict, known)
|
||||
|
||||
return _manifest_with_merged_git_user(agent, raw_bottle)
|
||||
return _compose_manifest(agent_name, agent, raw_bottle)
|
||||
|
||||
def has_agent(self, name: str) -> bool:
|
||||
return name in self.agents
|
||||
@@ -394,13 +411,9 @@ class ManifestIndex:
|
||||
if self.has_agent(name):
|
||||
return
|
||||
if self.home_md is not None:
|
||||
# Names-only mode: check file existence without parsing.
|
||||
home_path = self.home_md / "agents" / f"{name}.md"
|
||||
cwd_path = (
|
||||
self.cwd_md / "agents" / f"{name}.md"
|
||||
if self.cwd_md else None
|
||||
)
|
||||
if home_path.is_file() or (cwd_path and cwd_path.is_file()):
|
||||
# Names-only mode: check home file existence without parsing.
|
||||
# Agents are home-only; a cwd agent file is never selectable.
|
||||
if (self.home_md / "agents" / f"{name}.md").is_file():
|
||||
return
|
||||
available = ", ".join(self.all_agent_names) or "(none)"
|
||||
raise ManifestError(
|
||||
|
||||
@@ -22,7 +22,10 @@ BOTTLE_KEYS = frozenset(
|
||||
}
|
||||
)
|
||||
AGENT_KEYS_REQUIRED: frozenset[str] = frozenset()
|
||||
AGENT_KEYS_OPTIONAL = frozenset({"bottle", "skills", "git-gate"})
|
||||
# `author` / `forge-accounts` are agent-owned identity (PRD
|
||||
# prd-new-trusted-agent-forge-identity). `git-gate` is no longer accepted on an
|
||||
# agent: `git-gate.user` moved to `author`, and `git-gate.repos` is bottle-only.
|
||||
AGENT_KEYS_OPTIONAL = frozenset({"bottle", "skills", "author", "forge-accounts"})
|
||||
|
||||
# Claude Code subagent fields bot-bottle ignores at launch but does
|
||||
# not reject. This lets the same file double as
|
||||
|
||||
Reference in New Issue
Block a user