Compare commits
22
Commits
@@ -9,8 +9,6 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
import base64
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
@@ -60,82 +58,6 @@ class AuthorityGitExecutor:
|
||||
value = self._git(["rev-parse", "--verify", ref], check=False)
|
||||
return value if value and OID_RE.fullmatch(value) else None
|
||||
|
||||
@staticmethod
|
||||
def _read_path(path: str) -> str:
|
||||
if not isinstance(path, str) or not path or len(path) > 512:
|
||||
raise AuthorityGitError("SOURCE_PATH_INVALID")
|
||||
if "\\" in path or "\x00" in path:
|
||||
raise AuthorityGitError("SOURCE_PATH_INVALID")
|
||||
parts = Path(path).parts
|
||||
if not parts or path.startswith("/") or ".." in parts or ".git" in parts:
|
||||
raise AuthorityGitError("SOURCE_PATH_INVALID")
|
||||
return "/".join(parts)
|
||||
|
||||
def _read_revision(self, ref: str) -> str:
|
||||
if not isinstance(ref, str) or not ref or len(ref) > 256 or "\x00" in ref:
|
||||
raise AuthorityGitError("SOURCE_REF_INVALID")
|
||||
if OID_RE.fullmatch(ref):
|
||||
if not self.commit_exists(ref):
|
||||
raise AuthorityGitError("SOURCE_REF_NOT_FOUND")
|
||||
return ref
|
||||
if ref == "main":
|
||||
ref = "refs/heads/main"
|
||||
elif ref.startswith("agent/"):
|
||||
ref = "refs/heads/" + ref
|
||||
elif ref.startswith("refs/heads/agent/"):
|
||||
pass
|
||||
elif ref == "V2R2C1":
|
||||
ref = "refs/tags/V2R2C1"
|
||||
elif ref.startswith("refs/tags/V"):
|
||||
pass
|
||||
else:
|
||||
raise AuthorityGitError("SOURCE_REF_SCOPE_DENIED")
|
||||
if ".." in ref or not re.fullmatch(r"refs/(heads/(?:agent/[A-Za-z0-9._/-]+|main)|tags/V[0-9]+R[0-9]+C[0-9]+)", ref):
|
||||
raise AuthorityGitError("SOURCE_REF_SCOPE_DENIED")
|
||||
value = self._git(["rev-parse", "--verify", ref + "^{commit}"], check=False)
|
||||
if not OID_RE.fullmatch(value):
|
||||
raise AuthorityGitError("SOURCE_REF_NOT_FOUND")
|
||||
return value
|
||||
|
||||
def read_file(self, ref: str, path: str, max_bytes: int) -> dict[str, object]:
|
||||
if not isinstance(max_bytes, int) or isinstance(max_bytes, bool) or not 1 <= max_bytes <= 262_144:
|
||||
raise AuthorityGitError("SOURCE_MAX_BYTES_INVALID")
|
||||
revision = self._read_revision(ref)
|
||||
relative = self._read_path(path)
|
||||
spec = f"{revision}:{relative}"
|
||||
size_result = subprocess.run(
|
||||
["git", f"--git-dir={self.git_dir}", "cat-file", "-s", spec],
|
||||
text=True, capture_output=True, check=False,
|
||||
)
|
||||
if size_result.returncode != 0:
|
||||
raise AuthorityGitError("SOURCE_FILE_NOT_FOUND")
|
||||
try:
|
||||
size = int(size_result.stdout.strip())
|
||||
except ValueError as exc:
|
||||
raise AuthorityGitError("SOURCE_FILE_READ_FAILED") from exc
|
||||
if size > max_bytes:
|
||||
raise AuthorityGitError("SOURCE_FILE_TOO_LARGE")
|
||||
result = subprocess.run(
|
||||
["git", f"--git-dir={self.git_dir}", "show", spec],
|
||||
capture_output=True, check=False,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AuthorityGitError("SOURCE_FILE_NOT_FOUND")
|
||||
content = result.stdout
|
||||
if len(content) != size:
|
||||
raise AuthorityGitError("SOURCE_FILE_READ_FAILED")
|
||||
return {
|
||||
"repository": "aios/aios",
|
||||
"ref": ref,
|
||||
"resolved_commit_oid": revision,
|
||||
"path": relative,
|
||||
"size_bytes": size,
|
||||
"sha256": hashlib.sha256(content).hexdigest(),
|
||||
"content_base64": base64.b64encode(content).decode("ascii"),
|
||||
"truncated": False,
|
||||
"read_only": True,
|
||||
}
|
||||
|
||||
def commit_exists(self, oid: str) -> bool:
|
||||
_oid(oid, "commit_oid")
|
||||
result = subprocess.run(["git", f"--git-dir={self.git_dir}", "cat-file", "-e", oid + "^{commit}"], capture_output=True, check=False)
|
||||
@@ -172,25 +94,6 @@ class AuthorityGitExecutor:
|
||||
self._git(["worktree", "add", "--detach", str(path), base_oid])
|
||||
return path
|
||||
|
||||
def create_task_branch(self, branch: str, base_oid: str) -> str:
|
||||
"""Create an isolated agent branch once, using an empty-ref CAS."""
|
||||
ref = branch if branch.startswith("refs/heads/") else "refs/heads/" + branch
|
||||
if not TASK_BRANCH_RE.fullmatch(ref):
|
||||
raise AuthorityGitError("TASK_BRANCH_SCOPE_DENIED")
|
||||
_oid(base_oid, "base_oid")
|
||||
if not self.commit_exists(base_oid):
|
||||
raise AuthorityGitError("BASE_COMMIT_NOT_FOUND")
|
||||
current = self.read_ref(ref)
|
||||
if current is not None:
|
||||
if current == base_oid:
|
||||
return current
|
||||
raise AuthorityGitError("AUTHORITY_BRANCH_EXPECTATION_MISMATCH")
|
||||
self._git(["update-ref", ref, base_oid, "0" * 40])
|
||||
readback = self.read_ref(ref)
|
||||
if readback != base_oid:
|
||||
raise AuthorityGitError("AUTHORITY_CAS_READBACK_MISMATCH")
|
||||
return readback
|
||||
|
||||
def advance_task_branch_CAS(self, branch: str, expected_oid: str, new_oid: str) -> str:
|
||||
if not TASK_BRANCH_RE.fullmatch(branch):
|
||||
raise AuthorityGitError("TASK_BRANCH_SCOPE_DENIED")
|
||||
|
||||
Regular → Executable
+7
-70
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
import hashlib, hmac, json, os, re, subprocess, sys, time, urllib.parse, urllib.request, uuid
|
||||
import hashlib, hmac, json, os, re, subprocess, sys, time, urllib.parse, uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -22,7 +22,6 @@ from gitea_tag_publication import (
|
||||
TagPublisher,
|
||||
redact,
|
||||
validate_version,
|
||||
validate_gitea_api_url,
|
||||
)
|
||||
from orchestrator.action_monitor import ActionMonitor
|
||||
from silent_release_hardening import (
|
||||
@@ -309,7 +308,8 @@ def resolve_commit_oid(value: str | None, field: str = 'target_oid') -> str:
|
||||
raise ValueError(f'{field} does not resolve to the exact approved commit') from exc
|
||||
|
||||
def existing_tag_target(tag: str) -> str | None:
|
||||
validate_version(tag)
|
||||
if not re.fullmatch(r'V\d+R\d+C\d+(?:-[A-Za-z0-9_.-]+)?$', str(tag or '')):
|
||||
raise ValueError('invalid release version')
|
||||
try:
|
||||
result = run_authoritative_git(
|
||||
['rev-parse', '--verify', f'refs/tags/{tag}^{{commit}}'],
|
||||
@@ -344,7 +344,7 @@ def required_authoritative_git_dir() -> Path:
|
||||
|
||||
def publication_publisher() -> TagPublisher:
|
||||
authoritative_repo = required_authoritative_git_dir()
|
||||
publisher = TagPublisher(
|
||||
return TagPublisher(
|
||||
WS,
|
||||
GitTagBackend(WS, authoritative_repo=authoritative_repo),
|
||||
GiteaTagClient(
|
||||
@@ -355,10 +355,6 @@ def publication_publisher() -> TagPublisher:
|
||||
),
|
||||
os.getenv('AIOS_GITOPS_GITEA_REMOTE','gitea'),
|
||||
)
|
||||
publisher.baseline_path = Path(os.getenv(
|
||||
'AIOS_GITOPS_BASELINE_AUTHORITY', str(WS / 'baseline' / 'current.json')
|
||||
))
|
||||
return publisher
|
||||
|
||||
def commit(paths, msg):
|
||||
ensure_git(); paths = [relpath(p) for p in paths] if paths else ['.']; sh(['add'] + paths, True)
|
||||
@@ -408,51 +404,6 @@ class H(BaseHTTPRequestHandler):
|
||||
if not a['ok']: self.sendj({'error':'unauthorized','hint':'Bearer token required'},401); return None
|
||||
if '*' not in a['scopes'] and scope not in a['scopes']: self.sendj({'error':'forbidden','required_scope':scope,'account':a['account']},403); return None
|
||||
return a
|
||||
def bridge_release(self, path, data):
|
||||
route = {
|
||||
'/createTagApprovalRequest': '/v2/tag/approval-request',
|
||||
'/requestOrCreateTag': '/v2/tag/publish',
|
||||
'/getTagPublicationStatus': '/v2/tag/status',
|
||||
'/buildProductionArtifact': '/v2/release/artifact',
|
||||
'/executeApprovedProductionRelease': '/v2/release/execute',
|
||||
'/getReleaseConsistency': '/v2/release/consistency',
|
||||
'/runReleaseAcceptance': '/v2/release/acceptance',
|
||||
}.get(path)
|
||||
if route is None:
|
||||
raise ValueError('governed_release_route_invalid')
|
||||
base = os.getenv('AIOS_BRIDGE_V2_URL', 'http://127.0.0.1:18892').rstrip('/')
|
||||
request = urllib.request.Request(
|
||||
base + route,
|
||||
data=json.dumps(data, sort_keys=True, separators=(',', ':')).encode('utf-8'),
|
||||
headers={'Content-Type': 'application/json'},
|
||||
method='POST',
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
result = json.loads(response.read().decode('utf-8'))
|
||||
return self.sendj(result, response.status)
|
||||
except urllib.error.HTTPError as exc:
|
||||
try:
|
||||
body = json.loads(exc.read().decode('utf-8'))
|
||||
except Exception:
|
||||
body = {'error': 'bridge_http_error'}
|
||||
return self.sendj(body, exc.code)
|
||||
except (urllib.error.URLError, TimeoutError) as exc:
|
||||
return self.sendj({'error': 'GOVERNED_BRIDGE_UNAVAILABLE', 'detail': type(exc).__name__}, 503)
|
||||
def do_POST(self):
|
||||
path = urllib.parse.urlparse(self.path).path
|
||||
if path in {
|
||||
'/createTagApprovalRequest', '/requestOrCreateTag', '/getTagPublicationStatus',
|
||||
'/buildProductionArtifact', '/executeApprovedProductionRelease',
|
||||
'/getReleaseConsistency', '/runReleaseAcceptance',
|
||||
}:
|
||||
actor = self.need('tag:create')
|
||||
if not actor:
|
||||
return
|
||||
return self.bridge_release(path, self.body())
|
||||
if reject_non_read_http(self, 'POST', path):
|
||||
return
|
||||
return self.sendj({'error': 'not_found', 'path': path}, 404)
|
||||
def do_GET(self):
|
||||
u=urllib.parse.urlparse(self.path); path=u.path.rstrip('/') if u.path != '/' else u.path
|
||||
if path not in READ_ONLY_GET_PATHS: return self.sendj({'error':'not_found','path':path},404)
|
||||
@@ -514,15 +465,7 @@ class H(BaseHTTPRequestHandler):
|
||||
return self.sendj({'error':redact(exc)},413)
|
||||
except (AuthoritativeGitError, RuntimeError) as exc:
|
||||
return self.sendj({'error':redact(exc)},503)
|
||||
payload = {'from': frm, 'to': to, 'diff': diff}
|
||||
payload.update({
|
||||
key: diff[key]
|
||||
for key in (
|
||||
'from_oid', 'to_oid', 'changed_paths', 'stats',
|
||||
'total_size_bytes', 'truncated', 'patch_limit_bytes',
|
||||
)
|
||||
})
|
||||
return self.sendj(payload)
|
||||
return self.sendj({'from':frm,'to':to,'diff':diff})
|
||||
if path in ('/api/patch','/api/patches','/api/branches','/patch'):
|
||||
snapshot = repository_snapshot(
|
||||
git_dir=AUTHORITATIVE_GIT_DIR,
|
||||
@@ -634,8 +577,7 @@ class H(BaseHTTPRequestHandler):
|
||||
return self.sendj(
|
||||
service.get_capability_status(candidate_id)
|
||||
)
|
||||
result = service.get_release_saga(candidate_id)
|
||||
return self.sendj(result, 404 if result.get('status') == 'NOT_FOUND' else 200)
|
||||
return self.sendj(service.get_release_saga(candidate_id))
|
||||
if path == '/getRecoveryStatus':
|
||||
return self.sendj(
|
||||
silent_release_service().get_recovery_status()
|
||||
@@ -786,10 +728,7 @@ class H(BaseHTTPRequestHandler):
|
||||
a=self.need('tag:create');
|
||||
if not a: return
|
||||
ver=data.get('version') or data.get('tag')
|
||||
try:
|
||||
validate_version(ver)
|
||||
except ValueError:
|
||||
return self.sendj({'error':'version must match VxRxCx'},400)
|
||||
if not re.match(r'^V\d+R\d+C\d+(-[A-Za-z0-9_.-]+)?$', ver or ''): return self.sendj({'error':'version must match VxRxCx'},400)
|
||||
if not data.get('target_oid') or not data.get('evidence_closure_oid') or not data.get('approval_plan_id'):
|
||||
return self.sendj({
|
||||
'error':'production_tag_evidence_required',
|
||||
@@ -963,8 +902,6 @@ def api_spec():
|
||||
return {'version':'V1R1C0-chatgpt-actions','openapi':'/api/openapi.yaml','read':['GET /api/base','GET /api/ver','GET /api/diff','GET /api/patch','GET /api/model','GET /api/run','GET /getReleaseCandidate','GET /getApprovalEnvelope','GET /getReleaseSaga','GET /admin/ai-evolution'],'write':['POST /api/branch','POST /api/file','POST /api/commit','POST /api/patch','POST /api/tag','POST /api/rollback','POST /api/model','PUT /api/model-priority','POST /api/nl','POST /createReleaseCandidate','POST /submitOwnerApproval','POST /startDeployment'],'policy':{'bearer_required_for_write':True,'direct_main_push':False,'delete_tag':False,'owner_approval_required_for_v_level':True,'api_keys_in_git':False,'git_secret_field':'secret_ref','online_git_sync':True,'silent_release_execution_enabled':SILENT_RELEASE_EXECUTION_ENABLED,'silent_release_shadow_default':True}}
|
||||
|
||||
def main():
|
||||
validate_gitea_api_url(os.getenv('AIOS_GITOPS_GITEA_API_URL', ''))
|
||||
print(f'AIOS ChatGPT GitOps adapter listening on {HOST}:{PORT}')
|
||||
ThreadingHTTPServer((HOST,PORT), H).serve_forever()
|
||||
if __name__ == '__main__': main()
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""ChatGPT GitOps Bridge v2 contract and governed release operations."""
|
||||
"""ChatGPT GitOps Bridge v2 contract and immutable runtime identity."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
@@ -6,29 +6,8 @@ import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Mapping
|
||||
|
||||
|
||||
BRIDGE_SCHEMA_VERSION = "aios.chatgpt-gitops-bridge.v2"
|
||||
BRIDGE_OPERATIONS = (
|
||||
"getRuntimeStatus",
|
||||
"getGovernedWriteCapabilities",
|
||||
"readRepositoryFile",
|
||||
"createGovernedTask",
|
||||
"acquireWriterLease",
|
||||
"commitFileGoverned",
|
||||
"commitFilesGoverned",
|
||||
"getGitOpsJob",
|
||||
"resumeGitOpsJob",
|
||||
"reconcileGitOpsJob",
|
||||
"createTagApprovalRequest",
|
||||
"requestOrCreateTag",
|
||||
"getTagPublicationStatus",
|
||||
"buildProductionArtifact",
|
||||
"executeApprovedProductionRelease",
|
||||
"getReleaseConsistency",
|
||||
"runReleaseAcceptance",
|
||||
"getControlPlaneSnapshot",
|
||||
)
|
||||
|
||||
BRIDGE_OPERATIONS = ("getRuntimeStatus", "getGovernedWriteCapabilities", "createGovernedTask", "acquireWriterLease", "commitFileGoverned", "commitFilesGoverned", "getGitOpsJob", "resumeGitOpsJob", "reconcileGitOpsJob", "getControlPlaneSnapshot")
|
||||
OPERATION_REQUIRED_FIELDS = {
|
||||
"createGovernedTask": ("task_id", "repository", "base_oid", "target_branch", "risk", "description", "idempotency_key"),
|
||||
"acquireWriterLease": ("schema", "task_id", "repository", "branch_mode", "base_oid", "expected_branch_oid", "target_branch", "generation", "lease_seconds"),
|
||||
@@ -37,90 +16,9 @@ OPERATION_REQUIRED_FIELDS = {
|
||||
"getGitOpsJob": ("job_id",),
|
||||
"resumeGitOpsJob": ("job_id", "expected_revision"),
|
||||
"reconcileGitOpsJob": ("job_id", "expected_revision"),
|
||||
"createTagApprovalRequest": ("version", "target_oid", "evidence_closure_oid", "approval_plan_id", "owner_approval", "execute"),
|
||||
"requestOrCreateTag": ("version", "target_oid", "evidence_closure_oid", "approval_plan_id", "execute"),
|
||||
"getTagPublicationStatus": ("version",),
|
||||
"buildProductionArtifact": ("version", "target_oid", "evidence_closure_oid", "approval_plan_id"),
|
||||
"executeApprovedProductionRelease": ("version", "target_oid", "evidence_closure_oid", "approval_plan_id", "execute"),
|
||||
"getReleaseConsistency": ("version", "target_oid", "evidence_closure_oid", "approval_plan_id"),
|
||||
"runReleaseAcceptance": ("version", "target_oid", "evidence_closure_oid", "approval_plan_id"),
|
||||
"getControlPlaneSnapshot": (),
|
||||
"readRepositoryFile": ("repository", "ref", "path", "max_bytes"),
|
||||
}
|
||||
|
||||
_OPERATION_PATHS = {
|
||||
"createGovernedTask": "/v2/governed-task",
|
||||
"acquireWriterLease": "/v2/writer-lease",
|
||||
"commitFileGoverned": "/v2/commit-file",
|
||||
"commitFilesGoverned": "/v2/commit-files",
|
||||
"getGitOpsJob": "/v2/job",
|
||||
"resumeGitOpsJob": "/v2/job/resume",
|
||||
"reconcileGitOpsJob": "/v2/job/reconcile",
|
||||
"getTagPublicationStatus": "/v2/tag/status",
|
||||
"getReleaseConsistency": "/v2/release/consistency",
|
||||
"runReleaseAcceptance": "/v2/release/acceptance",
|
||||
"readRepositoryFile": "/v2/source/file",
|
||||
}
|
||||
|
||||
|
||||
def operation_contracts() -> dict[str, dict[str, object]]:
|
||||
"""Return the runtime contract consumed by adapters and schema tooling."""
|
||||
return {
|
||||
operation: {
|
||||
"method": "POST",
|
||||
"path": _OPERATION_PATHS.get(operation),
|
||||
"required_fields": list(fields),
|
||||
}
|
||||
for operation, fields in OPERATION_REQUIRED_FIELDS.items()
|
||||
}
|
||||
|
||||
|
||||
def render_openapi_contract_fragment() -> str:
|
||||
required = "\n".join(
|
||||
f" - {field}"
|
||||
for field in OPERATION_REQUIRED_FIELDS["commitFilesGoverned"]
|
||||
)
|
||||
return (
|
||||
" /v2/commit-files:\n"
|
||||
" post:\n"
|
||||
" operationId: commitFilesGoverned\n"
|
||||
" summary: Submit one atomic governed commit containing multiple files\n"
|
||||
" security: [{bearerAuth: []}]\n"
|
||||
" requestBody:\n"
|
||||
" required: true\n"
|
||||
" content:\n"
|
||||
" application/json:\n"
|
||||
" schema:\n"
|
||||
" type: object\n"
|
||||
" additionalProperties: false\n"
|
||||
" required:\n"
|
||||
f"{required}\n"
|
||||
" properties:\n"
|
||||
" task_id: {type: string}\n"
|
||||
" repository: {type: string, example: aios/aios}\n"
|
||||
" expected_branch_oid: {type: string, pattern: '^[0-9a-f]{40}$'}\n"
|
||||
" target_branch: {type: string, pattern: '^agent/[A-Za-z0-9._/-]+$'}\n"
|
||||
" generation: {type: integer, minimum: 1}\n"
|
||||
" idempotency_key: {type: string, minLength: 8, maxLength: 128, pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$'}\n"
|
||||
" files:\n"
|
||||
" type: array\n"
|
||||
" minItems: 1\n"
|
||||
" maxItems: 50\n"
|
||||
" items:\n"
|
||||
" type: object\n"
|
||||
" additionalProperties: false\n"
|
||||
" required: [path, content_base64]\n"
|
||||
" properties:\n"
|
||||
" path: {type: string, minLength: 1, maxLength: 512}\n"
|
||||
" content_base64: {type: string}\n"
|
||||
" message: {type: string, minLength: 1, maxLength: 200}\n"
|
||||
" responses:\n"
|
||||
" '200': {description: Governed commit job and verified branch result}\n"
|
||||
" '400': {description: Contract or policy rejection}\n"
|
||||
" '409': {description: Branch CAS or idempotency conflict}\n"
|
||||
" x-openai-isConsequential: true\n"
|
||||
)
|
||||
|
||||
|
||||
class RuntimeDriftError(RuntimeError):
|
||||
pass
|
||||
@@ -142,83 +40,37 @@ class ControlPlaneReleaseManifest:
|
||||
deployment_state: str
|
||||
|
||||
def as_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"control_plane_release_version": self.control_plane_release_version,
|
||||
"control_plane_target_oid": self.control_plane_target_oid,
|
||||
"artifact_sha256": self.artifact_sha256,
|
||||
"runtime_path": str(self.runtime_path),
|
||||
"bridge_schema_version": self.bridge_schema_version,
|
||||
"repository_identity": self.repository_identity,
|
||||
"authoritative_git_dir": str(self.authoritative_git_dir),
|
||||
"deployment_state": self.deployment_state,
|
||||
}
|
||||
return {"control_plane_release_version": self.control_plane_release_version, "control_plane_target_oid": self.control_plane_target_oid, "artifact_sha256": self.artifact_sha256, "runtime_path": str(self.runtime_path), "bridge_schema_version": self.bridge_schema_version, "repository_identity": self.repository_identity, "authoritative_git_dir": str(self.authoritative_git_dir), "deployment_state": self.deployment_state}
|
||||
|
||||
def validate(self, artifact: Path, *, observed_oid: str, approved_root: Path = Path("/opt/aios/gitops-control-plane")) -> dict[str, object]:
|
||||
try:
|
||||
runtime = self.runtime_path.resolve(strict=True)
|
||||
root = approved_root.resolve(strict=True)
|
||||
artifact_path = artifact.resolve(strict=True)
|
||||
runtime.relative_to(root)
|
||||
artifact_path.relative_to(runtime)
|
||||
runtime = self.runtime_path.resolve(strict=True); root = approved_root.resolve(strict=True); artifact_path = artifact.resolve(strict=True); runtime.relative_to(root); artifact_path.relative_to(runtime)
|
||||
except (OSError, ValueError):
|
||||
raise RuntimeDriftError("CONTROL_PLANE_RUNTIME_DRIFT") from None
|
||||
mutable_markers = {"workspace", "workspaces", "worktree", "worktrees"}
|
||||
if mutable_markers.intersection(part.lower() for part in runtime.parts):
|
||||
if any(marker in {"workspace", "workspaces", "worktree", "worktrees"} for marker in (part.lower() for part in runtime.parts)):
|
||||
raise RuntimeDriftError("CONTROL_PLANE_RUNTIME_DRIFT")
|
||||
valid = (
|
||||
len(self.control_plane_target_oid) == 40
|
||||
and observed_oid == self.control_plane_target_oid
|
||||
and len(self.artifact_sha256) == 64
|
||||
and hashlib.sha256(artifact_path.read_bytes()).hexdigest() == self.artifact_sha256
|
||||
and self.bridge_schema_version == BRIDGE_SCHEMA_VERSION
|
||||
and self.repository_identity == "aios/aios"
|
||||
and self.authoritative_git_dir == Path("/data/aios-gitops/repo.git")
|
||||
and self.authoritative_git_dir.is_absolute()
|
||||
and self.deployment_state == "STAGING"
|
||||
)
|
||||
valid = len(self.control_plane_target_oid) == 40 and observed_oid == self.control_plane_target_oid and len(self.artifact_sha256) == 64 and hashlib.sha256(artifact_path.read_bytes()).hexdigest() == self.artifact_sha256 and self.bridge_schema_version == BRIDGE_SCHEMA_VERSION and self.repository_identity == "aios/aios" and self.authoritative_git_dir == Path("/data/aios-gitops/repo.git") and self.deployment_state == "STAGING"
|
||||
if not valid:
|
||||
raise RuntimeDriftError("CONTROL_PLANE_RUNTIME_DRIFT")
|
||||
return {**self.as_dict(), "drift_status": "PASS"}
|
||||
|
||||
|
||||
class BridgeV2Adapter:
|
||||
"""Thin operation adapter; all mutating handlers are injected seams."""
|
||||
|
||||
def __init__(self, *, runtime_status: Mapping[str, Any], handlers: Mapping[str, Callable[[Mapping[str, Any]], Any]] | None = None) -> None:
|
||||
self.runtime_status = dict(runtime_status)
|
||||
self.handlers = dict(handlers or {})
|
||||
self.runtime_status = dict(runtime_status); self.handlers = dict(handlers or {})
|
||||
|
||||
def getRuntimeStatus(self) -> dict[str, Any]:
|
||||
return {"bridge_schema_version": BRIDGE_SCHEMA_VERSION, **self.runtime_status}
|
||||
|
||||
def getGovernedWriteCapabilities(self) -> dict[str, Any]:
|
||||
return {
|
||||
"bridge_schema_version": BRIDGE_SCHEMA_VERSION,
|
||||
"legacy_writes_enabled": False,
|
||||
"governed_writes_enabled": True,
|
||||
"operations": list(BRIDGE_OPERATIONS),
|
||||
"operation_contracts": operation_contracts(),
|
||||
"force_push": False,
|
||||
"main_write": False,
|
||||
"tag_write": False,
|
||||
"baseline_write": False,
|
||||
"production_write": False,
|
||||
"approved_release_operations": True,
|
||||
"approved_release_scope": {
|
||||
"version": "V2R2C1",
|
||||
"target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"evidence_closure_oid": "a8b906d1bc24088c19647e98de6a679268f6d0a2",
|
||||
"approval_plan_id": "sha256:c0df52008ae7f64cec5ee2d28947aa7b892066c670ab8295e4549140b1a7500e",
|
||||
},
|
||||
}
|
||||
return {"bridge_schema_version": BRIDGE_SCHEMA_VERSION, "legacy_writes_enabled": False, "governed_writes_enabled": True, "operations": list(BRIDGE_OPERATIONS), "force_push": False, "main_write": False, "tag_write": False, "baseline_write": False, "production_write": False}
|
||||
|
||||
@staticmethod
|
||||
def legacy_write_disabled() -> dict[str, object]:
|
||||
return {"error": "LEGACY_WRITE_DISABLED", "replacement": "createGovernedTask", "governed_writes_available": True}
|
||||
|
||||
def _call(self, operation: str, request: Mapping[str, Any]) -> Any:
|
||||
required = OPERATION_REQUIRED_FIELDS[operation]
|
||||
if any(key not in request for key in required):
|
||||
if tuple(key for key in OPERATION_REQUIRED_FIELDS[operation] if key not in request):
|
||||
raise BridgeV2Error("BRIDGE_REQUEST_FIELDS_MISSING")
|
||||
handler = self.handlers.get(operation)
|
||||
if handler is None:
|
||||
@@ -229,16 +81,7 @@ class BridgeV2Adapter:
|
||||
def acquireWriterLease(self, request: Mapping[str, Any]) -> Any: return self._call("acquireWriterLease", request)
|
||||
def commitFileGoverned(self, request: Mapping[str, Any]) -> Any: return self._call("commitFileGoverned", request)
|
||||
def commitFilesGoverned(self, request: Mapping[str, Any]) -> Any: return self._call("commitFilesGoverned", request)
|
||||
def readRepositoryFile(self, request: Mapping[str, Any]) -> Any: return self._call("readRepositoryFile", request)
|
||||
def getGitOpsJob(self, request: Mapping[str, Any]) -> Any: return self._call("getGitOpsJob", request)
|
||||
def resumeGitOpsJob(self, request: Mapping[str, Any]) -> Any: return self._call("resumeGitOpsJob", request)
|
||||
def reconcileGitOpsJob(self, request: Mapping[str, Any]) -> Any: return self._call("reconcileGitOpsJob", request)
|
||||
def createTagApprovalRequest(self, request: Mapping[str, Any]) -> Any: return self._call("createTagApprovalRequest", request)
|
||||
def requestOrCreateTag(self, request: Mapping[str, Any]) -> Any: return self._call("requestOrCreateTag", request)
|
||||
def getTagPublicationStatus(self, request: Mapping[str, Any]) -> Any: return self._call("getTagPublicationStatus", request)
|
||||
def buildProductionArtifact(self, request: Mapping[str, Any]) -> Any: return self._call("buildProductionArtifact", request)
|
||||
def executeApprovedProductionRelease(self, request: Mapping[str, Any]) -> Any: return self._call("executeApprovedProductionRelease", request)
|
||||
def getReleaseConsistency(self, request: Mapping[str, Any]) -> Any: return self._call("getReleaseConsistency", request)
|
||||
def runReleaseAcceptance(self, request: Mapping[str, Any]) -> Any: return self._call("runReleaseAcceptance", request)
|
||||
|
||||
def getControlPlaneSnapshot(self, request: Mapping[str, Any] | None = None) -> Any: return self._call("getControlPlaneSnapshot", request or {})
|
||||
|
||||
@@ -4,8 +4,6 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
@@ -16,36 +14,14 @@ from typing import Any, Mapping
|
||||
|
||||
from aios_authority_git_executor import AuthorityGitExecutor
|
||||
from aios_chatgpt_bridge_v2 import BridgeV2Adapter, BridgeV2Error, OPERATION_REQUIRED_FIELDS
|
||||
from gitea_tag_publication import validate_gitea_api_url
|
||||
from aios_continuation_executor import AuthorityGitAdapter, ContinuationCommit, ContinuationExecutor, ContinuationPermissions, ContinuationRuntimeBinding, DetachedGitWorkspace, GiteaContinuationRemote, ServerSideCredentialProjection
|
||||
from aios_continuation_lease import WriterLeaseRequestV2
|
||||
from scoped_lease_store import ScopedLeaseError, ScopedLeaseStore
|
||||
from aios_control_plane_snapshot import build_control_plane_snapshot
|
||||
from aios_gitops_job_controller import GitOpsJobController, JobState, JobStore, _RECOVERABLE
|
||||
from aios_gitops_job_controller import GitOpsJobController, JobStore
|
||||
from aios_governed_task_bootstrap import BootstrapError, GovernedTaskBootstrap
|
||||
from governed_production_release import build_executor_config
|
||||
|
||||
MAX_BODY = 2 * 1024 * 1024
|
||||
MAX_SOURCE_BYTES = 262_144
|
||||
ROUTES = {
|
||||
"/v2/runtime": "getRuntimeStatus",
|
||||
"/v2/capabilities": "getGovernedWriteCapabilities",
|
||||
"/v2/governed-task": "createGovernedTask",
|
||||
"/v2/writer-lease": "acquireWriterLease",
|
||||
"/v2/commit-file": "commitFileGoverned",
|
||||
"/v2/commit-files": "commitFilesGoverned",
|
||||
"/v2/source/file": "readRepositoryFile",
|
||||
"/v2/job": "getGitOpsJob",
|
||||
"/v2/job/resume": "resumeGitOpsJob",
|
||||
"/v2/job/reconcile": "reconcileGitOpsJob",
|
||||
"/v2/tag/approval-request": "createTagApprovalRequest",
|
||||
"/v2/tag/publish": "requestOrCreateTag",
|
||||
"/v2/tag/status": "getTagPublicationStatus",
|
||||
"/v2/release/artifact": "buildProductionArtifact",
|
||||
"/v2/release/execute": "executeApprovedProductionRelease",
|
||||
"/v2/release/consistency": "getReleaseConsistency",
|
||||
"/v2/release/acceptance": "runReleaseAcceptance",
|
||||
}
|
||||
ROUTES = {"/v2/governed-task": "createGovernedTask", "/v2/writer-lease": "acquireWriterLease", "/v2/commit-file": "commitFileGoverned", "/v2/commit-files": "commitFilesGoverned", "/v2/job": "getGitOpsJob", "/v2/job/resume": "resumeGitOpsJob", "/v2/job/reconcile": "reconcileGitOpsJob"}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -58,13 +34,8 @@ class RuntimeConfig:
|
||||
ssh_key_path: Path
|
||||
remote_name: str = "gitea-http"
|
||||
repository: str = "aios/aios"
|
||||
api_base: str = ""
|
||||
v2_task_id: str = "TASK-P0-CHATGPT-BRIDGE-V2-CONTROL-PLANE-CONVERGENCE-20260809"
|
||||
v2_branch: str = "agent/p0-chatgpt-bridge-v2-control-plane-convergence-20260809"
|
||||
api_base: str = "https://g.cnnetmkt.top/git/api/v1"
|
||||
target_version: str = "V2R2C1"
|
||||
registry_root: Path = Path("/var/lib/aios-gitops/runtime/registry-projection")
|
||||
baseline_path: Path = Path("/var/lib/aios-gitops-runtime-anchor/baseline/current.json")
|
||||
health_url: str = "http://127.0.0.1:18927/health"
|
||||
|
||||
|
||||
def _safe(value: str) -> str:
|
||||
@@ -80,8 +51,6 @@ class GovernedRuntime:
|
||||
self.runtimes: dict[tuple[str, int], tuple[Any, GitOpsJobController, ContinuationExecutor]] = {}
|
||||
self.controllers: dict[str, GitOpsJobController] = {}
|
||||
self.bindings: dict[str, dict[str, Any]] = {}
|
||||
self.leases = ScopedLeaseStore(config.state_root / "scoped-leases.sqlite3")
|
||||
self.release = build_executor_config(config)
|
||||
metadata_root = config.state_root / "task-bindings"
|
||||
if metadata_root.is_dir():
|
||||
for metadata in metadata_root.glob("*.json"):
|
||||
@@ -98,22 +67,7 @@ class GovernedRuntime:
|
||||
os.environ.setdefault("GIT_ASKPASS", str(askpass)); os.environ.setdefault("GIT_ASKPASS_REQUIRE", "force"); os.environ.setdefault("GIT_TERMINAL_PROMPT", "0"); os.environ.setdefault("GITEA_MACHINE_ACTOR", "aios-autonomy-agent")
|
||||
|
||||
def runtime_status(self) -> dict[str, Any]:
|
||||
return {
|
||||
"status": "active",
|
||||
"health": 200,
|
||||
"bridge_schema_version": "aios.chatgpt-gitops-bridge.v2",
|
||||
"control_plane_release_version": self.config.target_version,
|
||||
"control_plane_target_oid": self.config.target_oid,
|
||||
"runtime_release_commit": self.config.target_oid,
|
||||
"runtime_path": str(self.config.state_root),
|
||||
"artifact_sha256": os.environ.get("AIOS_CONTROL_PLANE_ARTIFACT_SHA256"),
|
||||
"deployment_state": "STAGING",
|
||||
"drift_status": "PASS",
|
||||
"repository": self.config.repository,
|
||||
"repository_identity": self.config.repository,
|
||||
"authoritative_git_dir": str(self.config.authoritative_git_dir),
|
||||
"legacy_global_writes_enabled": False,
|
||||
}
|
||||
return {"bridge_schema_version": "aios.chatgpt-gitops-bridge.v2", "control_plane_release_version": self.config.target_version, "control_plane_target_oid": self.config.target_oid, "runtime_release_commit": self.config.target_oid, "runtime_path": str(self.config.state_root), "artifact_sha256": os.environ.get("AIOS_CONTROL_PLANE_ARTIFACT_SHA256"), "deployment_state": "STAGING", "drift_status": "PASS", "repository_identity": self.config.repository, "authoritative_git_dir": str(self.config.authoritative_git_dir)}
|
||||
|
||||
def _job_root(self, task_id: str) -> Path:
|
||||
return self.config.state_root / "jobs" / _safe(task_id)
|
||||
@@ -122,30 +76,6 @@ class GovernedRuntime:
|
||||
key = (str(request["task_id"]), int(request["generation"]))
|
||||
if key in self.runtimes: return self.runtimes[key]
|
||||
lease = WriterLeaseRequestV2(task_id=str(request["task_id"]), repository=str(request["repository"]), branch_mode=str(request.get("branch_mode", "CONTINUE_EXISTING")), base_oid=str(request["base_oid"]), expected_branch_oid=str(request["expected_branch_oid"]), target_branch=str(request["target_branch"]), generation=int(request["generation"]), lease_seconds=int(request.get("lease_seconds", 900)))
|
||||
original_branch_mode = lease.branch_mode
|
||||
if lease.branch_mode == "CREATE_NEW":
|
||||
try:
|
||||
lease.validate(AuthorityGitAdapter(self.authority))
|
||||
except Exception as exc:
|
||||
# A request replay after the authority CAS may observe the
|
||||
# already-created branch. Only the exact base identity is
|
||||
# idempotent; all other validation failures remain fail-closed.
|
||||
if str(exc) != "TARGET_BRANCH_ALREADY_EXISTS":
|
||||
raise
|
||||
# Bootstrap owns the durable binding; the runtime performs the one-time
|
||||
# branch materialization through the authority CAS before continuation
|
||||
# validation. No direct Git or legacy writer path is used.
|
||||
self.authority.create_task_branch(lease.target_branch, lease.base_oid)
|
||||
lease = WriterLeaseRequestV2(
|
||||
task_id=lease.task_id,
|
||||
repository=lease.repository,
|
||||
branch_mode="CONTINUE_EXISTING",
|
||||
base_oid=lease.base_oid,
|
||||
expected_branch_oid=lease.expected_branch_oid,
|
||||
target_branch=lease.target_branch,
|
||||
generation=lease.generation,
|
||||
lease_seconds=lease.lease_seconds,
|
||||
)
|
||||
lease.validate(AuthorityGitAdapter(self.authority))
|
||||
worktree_path = self.config.state_root / "worktrees" / _safe(lease.task_id)
|
||||
if worktree_path.exists():
|
||||
@@ -155,102 +85,16 @@ class GovernedRuntime:
|
||||
workspace = DetachedGitWorkspace(worktree_path)
|
||||
if workspace.head_oid() != lease.expected_branch_oid or not workspace.is_detached(): raise RuntimeError("WORKTREE_HEAD_MISMATCH")
|
||||
job_root = self._job_root(lease.task_id); controller = GitOpsJobController(JobStore(job_root, payload_root=job_root / "payloads")); credential = ServerSideCredentialProjection(self.config.ssh_key_path, self.config.token_path); remote = GiteaContinuationRemote(workspace=worktree_path, credential=credential, remote_name=self.config.remote_name, repository=lease.repository, api_base=self.config.api_base); executor = ContinuationExecutor(controller, AuthorityGitAdapter(self.authority), workspace, remote, credential)
|
||||
binding = ContinuationRuntimeBinding(request=lease, workspace_path=worktree_path, lease_not_before=datetime.now(timezone.utc) - timedelta(seconds=1), lease_expires_at=datetime.now(timezone.utc) + timedelta(seconds=lease.lease_seconds), original_receipt_valid=True, original_grant_consumed=True, permissions=ContinuationPermissions(), remote_branch_create_allowed=original_branch_mode == "CREATE_NEW")
|
||||
binding = ContinuationRuntimeBinding(request=lease, workspace_path=worktree_path, lease_not_before=datetime.now(timezone.utc) - timedelta(seconds=1), lease_expires_at=datetime.now(timezone.utc) + timedelta(seconds=lease.lease_seconds), original_receipt_valid=True, original_grant_consumed=True, permissions=ContinuationPermissions())
|
||||
result = (binding, controller, executor); self.runtimes[key] = result; self.controllers[lease.task_id] = controller; return result
|
||||
|
||||
def _validate_task_binding(self, request: Mapping[str, Any]) -> None:
|
||||
stored = self.bindings.get(str(request.get("task_id")))
|
||||
if not stored:
|
||||
raise RuntimeError("TASK_BINDING_NOT_FOUND")
|
||||
if (
|
||||
str(request.get("repository")) != str(stored.get("repository"))
|
||||
or str(request.get("target_branch")) != str(stored.get("target_branch"))
|
||||
or str(request.get("base_oid")) != str(stored.get("base_oid"))
|
||||
):
|
||||
raise RuntimeError("TASK_LEASE_BINDING_CONFLICT")
|
||||
if str(request.get("branch_mode")) != "CONTINUE_EXISTING":
|
||||
raise RuntimeError("TASK_BRANCH_MODE_INVALID")
|
||||
try:
|
||||
generation = int(request.get("generation"))
|
||||
stored_generation = int(stored.get("generation") or 1)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise RuntimeError("TASK_LEASE_BINDING_CONFLICT") from exc
|
||||
if generation < stored_generation:
|
||||
raise RuntimeError("TASK_GENERATION_STALE")
|
||||
current = self.authority.read_ref("refs/heads/" + str(request["target_branch"]))
|
||||
if current != str(request.get("expected_branch_oid")):
|
||||
raise RuntimeError("LEASE_EXPECTED_BRANCH_OID_STALE")
|
||||
if not self.authority.ancestry_check(str(stored.get("expected_branch_oid")), str(request["expected_branch_oid"])):
|
||||
raise RuntimeError("TASK_LEASE_LINEAGE_INVALID")
|
||||
|
||||
def create_task(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
result = self.bootstrap.create(request); self.bindings[result["task_id"]] = result; return result
|
||||
|
||||
def acquire_lease(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
if os.environ.get("AIOS_GITOPS_WRITES_ENABLED", "false").lower() not in {"1", "true", "yes", "on"}:
|
||||
raise RuntimeError("GITOPS_WRITES_DISABLED")
|
||||
self._validate_task_binding(request)
|
||||
try:
|
||||
record, created = self.leases.acquire(request)
|
||||
except ScopedLeaseError:
|
||||
raise
|
||||
if not created:
|
||||
if record["state"] == "EXPIRED":
|
||||
raise RuntimeError("LEASE_EXPIRED")
|
||||
record = {**record, "created": False}
|
||||
return self._lease_response(record["binding"], record)
|
||||
try:
|
||||
binding, _, _ = self._runtime(request)
|
||||
except Exception:
|
||||
# The lease cannot be usable if its detached runtime could not be
|
||||
# established. Leave no durable orphan behind.
|
||||
self.leases.delete(record["lease_key"])
|
||||
raise
|
||||
req = binding.request
|
||||
return self._lease_response(
|
||||
{
|
||||
"schema": WriterLeaseRequestV2.schema,
|
||||
"task_id": req.task_id,
|
||||
"repository": req.repository,
|
||||
"branch_mode": req.branch_mode,
|
||||
"base_oid": req.base_oid,
|
||||
"expected_branch_oid": req.expected_branch_oid,
|
||||
"target_branch": req.target_branch,
|
||||
"generation": req.generation,
|
||||
"lease_seconds": req.lease_seconds,
|
||||
},
|
||||
{**record, "created": True},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _lease_response(request: Mapping[str, Any], record: Mapping[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"schema": WriterLeaseRequestV2.schema,
|
||||
"task_id": request["task_id"],
|
||||
"repository": request["repository"],
|
||||
"branch_mode": request["branch_mode"],
|
||||
"base_oid": request["base_oid"],
|
||||
"expected_branch_oid": request["expected_branch_oid"],
|
||||
"target_branch": request["target_branch"],
|
||||
"generation": int(request["generation"]),
|
||||
"lease_seconds": int(request["lease_seconds"]),
|
||||
"lease_key": record["lease_key"],
|
||||
"lease_state": record["state"],
|
||||
"lease_expires_at": record["expires_at"],
|
||||
"idempotent": not bool(record.get("created", True)),
|
||||
"create_target_branch": request["branch_mode"] == "CREATE_NEW",
|
||||
"worktree_mode": "detached_at_base_oid" if request["branch_mode"] == "CREATE_NEW" else "detached_at_expected_head",
|
||||
"cas_ref_update_required": True,
|
||||
}
|
||||
|
||||
def read_source_file(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
repository = str(request.get("repository") or "")
|
||||
if repository != self.config.repository:
|
||||
raise RuntimeError("REPOSITORY_NOT_ALLOWED")
|
||||
max_bytes = request.get("max_bytes")
|
||||
if not isinstance(max_bytes, int) or isinstance(max_bytes, bool) or not 1 <= max_bytes <= MAX_SOURCE_BYTES:
|
||||
raise RuntimeError("SOURCE_MAX_BYTES_INVALID")
|
||||
return self.authority.read_file(str(request.get("ref") or ""), str(request.get("path") or ""), max_bytes)
|
||||
return {"schema": WriterLeaseRequestV2.schema, "task_id": req.task_id, "repository": req.repository, "branch_mode": req.branch_mode, "base_oid": req.base_oid, "expected_branch_oid": req.expected_branch_oid, "target_branch": req.target_branch, "generation": req.generation, "lease_seconds": req.lease_seconds, "create_target_branch": req.branch_mode == "CREATE_NEW", "worktree_mode": "detached_at_base_oid" if req.branch_mode == "CREATE_NEW" else "detached_at_expected_head", "cas_ref_update_required": True}
|
||||
|
||||
@staticmethod
|
||||
def _files(request: Mapping[str, Any]) -> dict[str, bytes]:
|
||||
@@ -259,29 +103,13 @@ class GovernedRuntime:
|
||||
return files
|
||||
|
||||
def commit_files(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
if os.environ.get("AIOS_GITOPS_WRITES_ENABLED", "false").lower() not in {"1", "true", "yes", "on"}:
|
||||
raise RuntimeError("GITOPS_WRITES_DISABLED")
|
||||
self._validate_task_binding(request)
|
||||
record = self.leases.for_commit(request)
|
||||
if record is None:
|
||||
raise RuntimeError("LEASE_NOT_FOUND")
|
||||
if record["state"] == "EXPIRED":
|
||||
raise RuntimeError("LEASE_EXPIRED")
|
||||
if record["state"] == "USED":
|
||||
if record.get("idempotency_key") == str(request["idempotency_key"]):
|
||||
return dict(record["result"])
|
||||
raise RuntimeError("LEASE_ALREADY_USED")
|
||||
runtime = self.runtimes.get((str(request["task_id"]), int(request["generation"])))
|
||||
if runtime is None:
|
||||
runtime = self._runtime(record["binding"])
|
||||
if runtime is None: raise RuntimeError("LEASE_NOT_FOUND")
|
||||
binding, _, executor = runtime
|
||||
if request["repository"] != binding.request.repository or request["target_branch"] != binding.request.target_branch or request["expected_branch_oid"] != binding.request.expected_branch_oid:
|
||||
raise RuntimeError("LEASE_BINDING_CONFLICT")
|
||||
if request["target_branch"] != binding.request.target_branch or request["expected_branch_oid"] != binding.request.expected_branch_oid: raise RuntimeError("LEASE_BINDING_CONFLICT")
|
||||
commit = ContinuationCommit(idempotency_key=str(request["idempotency_key"]), files=self._files(request), message=str(request["message"]))
|
||||
executor.workspace.materialize_files(commit.files)
|
||||
result = executor.execute(binding, commit)
|
||||
self.leases.mark_used(record["lease_key"], commit.idempotency_key, result)
|
||||
return result
|
||||
return executor.execute(binding, commit)
|
||||
|
||||
def _controller_for_job(self, job_id: str) -> GitOpsJobController:
|
||||
for controller in self.controllers.values():
|
||||
@@ -413,8 +241,6 @@ class GovernedRuntime:
|
||||
return controller.store._receipt(row, duplicate=True).as_dict()
|
||||
if action == "resume":
|
||||
return controller.resume(job_id).as_dict()
|
||||
if JobState(row["state"]) not in _RECOVERABLE:
|
||||
return controller.store._receipt(row, duplicate=True).as_dict()
|
||||
return self._executor_from_row(row, controller).reconcile(job_id)
|
||||
|
||||
def _snapshot_task(self) -> dict[str, Any]:
|
||||
@@ -475,24 +301,7 @@ class GovernedRuntime:
|
||||
return build_control_plane_snapshot(target_version=self.config.target_version, runtime=self.runtime_status(), repository={"identity": self.config.repository, "authority_git_dir": str(self.config.authoritative_git_dir), "authority_main_oid": self.authority.read_ref("refs/heads/main")}, production={"baseline_version": "V2R1C7", "target_oid": "c7adece1cc8beffe7c718d53c775898b45d6c7f8", "deployment_state": "ACTIVE"}, task=task, capabilities={"legacy_writes_enabled": False, "governed_writes_enabled": True, "force_push": False, "main_write": False, "tag_write": False, "baseline_write": False, "production_write": False}, credential_broker={"status": "SERVER_SIDE_ONLY", "provider": "FileCredentialProvider"})
|
||||
|
||||
def handlers(self) -> dict[str, Any]:
|
||||
return {
|
||||
"createGovernedTask": self.create_task,
|
||||
"acquireWriterLease": self.acquire_lease,
|
||||
"commitFileGoverned": lambda request: self.commit_files({**request, "files": {request["path"]: request["content_base64"]}}),
|
||||
"commitFilesGoverned": self.commit_files,
|
||||
"readRepositoryFile": self.read_source_file,
|
||||
"getGitOpsJob": lambda request: self.job(request, "get"),
|
||||
"resumeGitOpsJob": lambda request: self.job(request, "resume"),
|
||||
"reconcileGitOpsJob": lambda request: self.job(request, "reconcile"),
|
||||
"getControlPlaneSnapshot": lambda request: self.snapshot(),
|
||||
"createTagApprovalRequest": self.release.approval_request,
|
||||
"requestOrCreateTag": self.release.publish_tag,
|
||||
"getTagPublicationStatus": self.release.tag_status,
|
||||
"buildProductionArtifact": self.release.build_artifact,
|
||||
"executeApprovedProductionRelease": self.release.execute_request,
|
||||
"getReleaseConsistency": self.release.consistency,
|
||||
"runReleaseAcceptance": self.release.acceptance,
|
||||
}
|
||||
return {"createGovernedTask": self.create_task, "acquireWriterLease": self.acquire_lease, "commitFileGoverned": lambda request: self.commit_files({**request, "files": {request["path"]: request["content_base64"]}}), "commitFilesGoverned": self.commit_files, "getGitOpsJob": lambda request: self.job(request, "get"), "resumeGitOpsJob": lambda request: self.job(request, "resume"), "reconcileGitOpsJob": lambda request: self.job(request, "reconcile"), "getControlPlaneSnapshot": lambda request: self.snapshot()}
|
||||
|
||||
|
||||
def build_governed_handlers(runtime_config: RuntimeConfig | Mapping[str, Any]) -> Mapping[str, Any]:
|
||||
@@ -505,7 +314,6 @@ class _HTTPError(RuntimeError): pass
|
||||
|
||||
class BridgeHandler(BaseHTTPRequestHandler):
|
||||
adapter: BridgeV2Adapter | None = None
|
||||
action_token_path: Path | None = None
|
||||
def log_message(self, *_args: Any) -> None: return
|
||||
def _json(self, value: Any, status: int = 200) -> None:
|
||||
raw = json.dumps(value, sort_keys=True, separators=(",", ":")).encode(); self.send_response(status); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(raw))); self.end_headers(); self.wfile.write(raw)
|
||||
@@ -516,47 +324,9 @@ class BridgeHandler(BaseHTTPRequestHandler):
|
||||
value = json.loads(self.rfile.read(length).decode("utf-8"))
|
||||
if not isinstance(value, dict): raise _HTTPError("JSON_OBJECT_REQUIRED")
|
||||
return value
|
||||
def _authorized(self, operation: str) -> bool:
|
||||
if operation not in {"readRepositoryFile", "acquireWriterLease", "commitFilesGoverned", "commitFileGoverned"}:
|
||||
return True
|
||||
header = self.headers.get("Authorization", "")
|
||||
token = header[7:].strip() if header.startswith("Bearer ") else self.headers.get("X-AIOS-Token", "")
|
||||
if not token or self.action_token_path is None or not self.action_token_path.is_file():
|
||||
self._json({"error": "UNAUTHORIZED", "hint": "Bearer token required"}, 401)
|
||||
return False
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
try:
|
||||
records = self.action_token_path.read_text(encoding="utf-8").splitlines()
|
||||
except OSError:
|
||||
self._json({"error": "AUTHORITY_UNAVAILABLE"}, 503)
|
||||
return False
|
||||
for raw in records:
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
try:
|
||||
record = json.loads(line) if line.startswith("{") else {"token_plain": line, "scopes": ["*"]}
|
||||
except ValueError:
|
||||
continue
|
||||
if record.get("disabled"):
|
||||
continue
|
||||
valid = bool(record.get("token_sha256") and hmac.compare_digest(str(record["token_sha256"]), digest))
|
||||
valid = valid or bool(record.get("token_plain") and hmac.compare_digest(str(record["token_plain"]), token))
|
||||
scopes = set(record.get("scopes") or [])
|
||||
required = {
|
||||
"readRepositoryFile": {"repository:read", "file:write"},
|
||||
"acquireWriterLease": {"agent-task:control"},
|
||||
"commitFilesGoverned": {"file:write"},
|
||||
"commitFileGoverned": {"file:write"},
|
||||
}[operation]
|
||||
if valid and ("*" in scopes or required.intersection(scopes)):
|
||||
return True
|
||||
self._json({"error": "FORBIDDEN", "required_scope": sorted(required)}, 403)
|
||||
return False
|
||||
def _allowed(self, operation: str, body: Mapping[str, Any]) -> None:
|
||||
allowed = set(OPERATION_REQUIRED_FIELDS[operation]) | {"schema", "lease_seconds", "create_target_branch", "worktree_mode", "cas_ref_update_required", "expected_branch_oid", "generation", "branch_mode"}
|
||||
if operation == "commitFilesGoverned": allowed.add("files")
|
||||
allowed.update({"owner_approval", "execute"})
|
||||
if set(body) - allowed: raise _HTTPError("UNKNOWN_FIELDS")
|
||||
def do_GET(self) -> None:
|
||||
if self.adapter is None: self._json({"error": "RUNTIME_UNAVAILABLE"}, 503); return
|
||||
@@ -566,30 +336,16 @@ class BridgeHandler(BaseHTTPRequestHandler):
|
||||
self._json({"error": "NOT_FOUND"}, 404)
|
||||
def do_POST(self) -> None:
|
||||
operation = ROUTES.get(self.path)
|
||||
if operation is None or operation in ("getRuntimeStatus", "getGovernedWriteCapabilities") or self.adapter is None: self._json({"error": "NOT_FOUND"}, 404); return
|
||||
if operation is None or self.adapter is None: self._json({"error": "NOT_FOUND"}, 404); return
|
||||
try:
|
||||
if not self._authorized(operation):
|
||||
return
|
||||
body = self._body(); self._allowed(operation, body); self._json(getattr(self.adapter, operation)(body))
|
||||
except _HTTPError as exc: self._json({"error": str(exc)}, 413 if str(exc) == "REQUEST_TOO_LARGE" else 400)
|
||||
except (BootstrapError, ValueError, BridgeV2Error) as exc: self._json({"error": str(exc)}, 409 if "CONFLICT" in str(exc) else 400)
|
||||
except Exception as exc:
|
||||
code = str(exc) or type(exc).__name__
|
||||
if code.endswith("NOT_FOUND") or code in {"SOURCE_FILE_NOT_FOUND", "SOURCE_REF_NOT_FOUND", "LEASE_NOT_FOUND"}:
|
||||
status = 404
|
||||
elif code in {"SOURCE_FILE_TOO_LARGE", "SOURCE_MAX_BYTES_INVALID", "SOURCE_PATH_INVALID", "SOURCE_REF_INVALID", "SOURCE_REF_SCOPE_DENIED", "REPOSITORY_NOT_ALLOWED", "GITOPS_WRITES_DISABLED"}:
|
||||
status = 400 if code != "GITOPS_WRITES_DISABLED" else 423
|
||||
elif any(token in code for token in ("CONFLICT", "EXPECTATION", "MONOTONIC", "EXPIRED", "ALREADY_USED", "STALE", "BINDING")):
|
||||
status = 409
|
||||
else:
|
||||
status = 503
|
||||
self._json({"error": code, "retryable": status >= 500}, status)
|
||||
except Exception as exc: self._json({"error": str(exc) or type(exc).__name__}, 409 if any(token in str(exc) for token in ("CONFLICT", "EXPECTATION", "MONOTONIC")) else 503)
|
||||
|
||||
|
||||
def serve(adapter: BridgeV2Adapter, host: str = "127.0.0.1", port: int = 18892) -> None:
|
||||
BridgeHandler.adapter = adapter
|
||||
BridgeHandler.action_token_path = Path(os.environ.get("AIOS_GITOPS_TOKEN_FILE", "/var/lib/aios-gitops/runtime/secrets/gitops.tokens"))
|
||||
ThreadingHTTPServer((host, port), BridgeHandler).serve_forever()
|
||||
BridgeHandler.adapter = adapter; ThreadingHTTPServer((host, port), BridgeHandler).serve_forever()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -605,13 +361,7 @@ def main() -> None:
|
||||
state_root / "jobs",
|
||||
token_path,
|
||||
ssh_key_path,
|
||||
remote_name=os.environ.get("AIOS_GITEA_REMOTE", "gitea-http"),
|
||||
api_base=validate_gitea_api_url(os.environ.get("AIOS_GITEA_API_BASE", "")),
|
||||
target_version=os.environ.get("AIOS_CONTROL_PLANE_TARGET_VERSION", "V2R2C1"),
|
||||
baseline_path=Path(os.environ.get(
|
||||
"AIOS_GITOPS_BASELINE_AUTHORITY",
|
||||
"/var/lib/aios-gitops-runtime-anchor/baseline/current.json",
|
||||
)),
|
||||
)
|
||||
runtime = GovernedRuntime(config)
|
||||
serve(
|
||||
|
||||
@@ -56,7 +56,7 @@ class AuthorityPort(Protocol):
|
||||
|
||||
class RemotePort(Protocol):
|
||||
def repository_identity(self) -> str: ...
|
||||
def push_exact(self, branch: str, expected: str, new: str, *, allow_absent: bool = False) -> None: ...
|
||||
def push_exact(self, branch: str, expected: str, new: str) -> None: ...
|
||||
def read_git_ref(self, branch: str) -> str | None: ...
|
||||
def read_api_branch(self, branch: str) -> str | None: ...
|
||||
def commit_visible(self, oid: str) -> bool: ...
|
||||
@@ -258,11 +258,10 @@ class GiteaContinuationRemote:
|
||||
raise ContinuationExecutionError("GITEA_GIT_READBACK_INVALID")
|
||||
return oid
|
||||
|
||||
def push_exact(self, branch: str, expected: str, new: str, *, allow_absent: bool = False) -> None:
|
||||
def push_exact(self, branch: str, expected: str, new: str) -> None:
|
||||
self._require_projected()
|
||||
self.repository_identity()
|
||||
current = self.read_git_ref(branch)
|
||||
if current != expected and not (allow_absent and current is None):
|
||||
if self.read_git_ref(branch) != expected:
|
||||
raise ContinuationExecutionError("GITEA_BRANCH_EXPECTATION_MISMATCH")
|
||||
_run(["git", "push", self.remote_name, f"{new}:refs/heads/{branch}"], cwd=self.workspace)
|
||||
|
||||
@@ -285,24 +284,13 @@ class GiteaContinuationRemote:
|
||||
|
||||
def read_api_branch(self, branch: str) -> str | None:
|
||||
owner, name = self.repository.split("/", 1)
|
||||
page = 1
|
||||
while page <= 100:
|
||||
value = self._api(f"/repos/{quote(owner)}/{quote(name)}/branches?page={page}&limit=50")
|
||||
value = self._api(f"/repos/{quote(owner)}/{quote(name)}/branches/{quote(branch, safe='/')}")
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, list):
|
||||
raise ContinuationExecutionError("GITEA_API_BRANCH_COLLECTION_INVALID")
|
||||
for item in value:
|
||||
if not isinstance(item, dict) or item.get("name") != branch:
|
||||
continue
|
||||
oid = item.get("commit", {}).get("id")
|
||||
oid = value.get("commit", {}).get("id") if isinstance(value, dict) else None
|
||||
if not isinstance(oid, str) or not OID_RE.fullmatch(oid):
|
||||
raise ContinuationExecutionError("GITEA_API_BRANCH_INVALID")
|
||||
return oid
|
||||
if len(value) < 50:
|
||||
return None
|
||||
page += 1
|
||||
raise ContinuationExecutionError("GITEA_API_BRANCH_PAGINATION_LIMIT")
|
||||
|
||||
def commit_visible(self, oid: str) -> bool:
|
||||
owner, name = self.repository.split("/", 1)
|
||||
@@ -336,7 +324,6 @@ class ContinuationRuntimeBinding:
|
||||
original_receipt_valid: bool
|
||||
original_grant_consumed: bool
|
||||
permissions: ContinuationPermissions
|
||||
remote_branch_create_allowed: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -452,7 +439,6 @@ class ContinuationExecutor:
|
||||
"payload_digest": hashlib.sha256(payload).hexdigest(),
|
||||
"lineage_anchor_oid": request.base_oid,
|
||||
"generation": request.generation,
|
||||
"remote_branch_create_allowed": binding.remote_branch_create_allowed,
|
||||
}
|
||||
|
||||
def execute(self, binding: ContinuationRuntimeBinding, commit: ContinuationCommit) -> dict[str, object]:
|
||||
@@ -502,7 +488,7 @@ class ContinuationExecutor:
|
||||
)
|
||||
try:
|
||||
self.controller.advance(submitted.job_id, JobState.REMOTE_SYNCING, side_effect_state="IN_PROGRESS")
|
||||
self.remote.push_exact(request.target_branch, request.expected_branch_oid, new_oid, allow_absent=binding.remote_branch_create_allowed)
|
||||
self.remote.push_exact(request.target_branch, request.expected_branch_oid, new_oid)
|
||||
except Exception:
|
||||
return self._remote_pending(submitted.job_id, authority_oid, new_oid)
|
||||
return self._finish_remote_verification(submitted.job_id, authority_oid, new_oid)
|
||||
@@ -586,14 +572,11 @@ class ContinuationExecutor:
|
||||
and self.authority.is_ancestor(git_oid, new_oid)
|
||||
):
|
||||
self.controller.advance(job_id, JobState.RECONCILING, side_effect_state="OBSERVATION_FIRST_CHAIN")
|
||||
self.remote.push_exact(row["branch"], git_oid, new_oid, allow_absent=bool(request.get("remote_branch_create_allowed")) or request.get("branch_mode") == "CREATE_NEW")
|
||||
self.remote.push_exact(row["branch"], git_oid, new_oid)
|
||||
return self._finish_remote_verification(job_id, new_oid, new_oid)
|
||||
allow_remote_create = bool(request.get("remote_branch_create_allowed")) or request.get("branch_mode") == "CREATE_NEW" or (git_oid is None and api_oid is None)
|
||||
remote_matches_expected = git_oid == api_oid == expected_oid
|
||||
remote_absent_for_create = git_oid is None and api_oid is None
|
||||
if authority_oid == new_oid and (remote_matches_expected or remote_absent_for_create):
|
||||
if authority_oid == new_oid and git_oid == api_oid == expected_oid:
|
||||
self.controller.advance(job_id, JobState.RECONCILING, side_effect_state="OBSERVATION_FIRST_RETRY")
|
||||
self.remote.push_exact(row["branch"], expected_oid, new_oid, allow_absent=allow_remote_create)
|
||||
self.remote.push_exact(row["branch"], expected_oid, new_oid)
|
||||
return self._finish_remote_verification(job_id, new_oid, new_oid)
|
||||
return self.controller.store._receipt(row, duplicate=True).as_dict()
|
||||
finally:
|
||||
|
||||
@@ -74,12 +74,6 @@ class WriterLeaseRequestV2:
|
||||
raise ContinuationError("EXISTING_BRANCH_OID_CONFLICT")
|
||||
if not probe.is_ancestor(self.base_oid, actual):
|
||||
raise ContinuationError("BASE_NOT_ANCESTOR_OF_BRANCH")
|
||||
elif hasattr(probe, "commit_exists") and not probe.commit_exists(self.base_oid):
|
||||
raise ContinuationError("BASE_COMMIT_NOT_FOUND")
|
||||
elif self.branch_mode == "CREATE_NEW" and probe.branch_exists(self.target_branch):
|
||||
raise ContinuationError("TARGET_BRANCH_ALREADY_EXISTS")
|
||||
elif self.branch_mode == "CREATE_NEW" and self.base_oid != self.expected_branch_oid:
|
||||
raise ContinuationError("CREATE_NEW_BASE_EXPECTATION_MISMATCH")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
||||
@@ -41,8 +41,6 @@ class JobState(str, Enum):
|
||||
REMOTE_SYNCING = "REMOTE_SYNCING"
|
||||
REMOTE_VERIFIED = "REMOTE_VERIFIED"
|
||||
COMPLETED = "COMPLETED"
|
||||
FAILED = "FAILED"
|
||||
CANCELLED = "CANCELLED"
|
||||
RECOVERABLE_FAILURE = "RECOVERABLE_FAILURE"
|
||||
RECONCILING = "RECONCILING"
|
||||
RECONCILIATION_REQUIRED = "RECONCILIATION_REQUIRED"
|
||||
@@ -61,12 +59,7 @@ _ORDER = {
|
||||
JobState.COMPLETED: 8,
|
||||
}
|
||||
_RECOVERABLE = {JobState.RECOVERABLE_FAILURE, JobState.RECONCILIATION_REQUIRED}
|
||||
_TERMINAL = {
|
||||
JobState.COMPLETED,
|
||||
JobState.FAILED,
|
||||
JobState.CANCELLED,
|
||||
JobState.MANUAL_OWNER_REVIEW_REQUIRED,
|
||||
}
|
||||
_TERMINAL = {JobState.COMPLETED, JobState.MANUAL_OWNER_REVIEW_REQUIRED}
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
|
||||
@@ -5,8 +5,6 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from release_version import validate_release_version
|
||||
|
||||
ROOT = Path(os.getenv('AIOS_GITOPS_ROOT', '/data/aios-gitops'))
|
||||
WORKSPACE = Path(os.getenv('AIOS_GITOPS_WORKSPACE', str(ROOT / 'workspace')))
|
||||
DB_PATH = Path(os.getenv('AIOS_GITOPS_DB', str(ROOT / 'runtime' / 'gitops_model.sqlite3')))
|
||||
@@ -220,11 +218,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
a = self.require_write(['owner']);
|
||||
if not a: return
|
||||
ver=data.get('version') or data.get('tag')
|
||||
try:
|
||||
validate_release_version(ver)
|
||||
except ValueError:
|
||||
self.send_json({'error':'version must match VxRxCx'},400)
|
||||
return
|
||||
if not re.match(r'^V\d+R\d+C\d+(-[a-zA-Z0-9_.-]+)?$', ver or ''): self.send_json({'error':'version must match VxRxCx'},400); return
|
||||
msg=data.get('message') or f'release {ver}'; out=git_cmd(['tag','-a',ver,'-m',msg]);
|
||||
if data.get('push',False): git_cmd(['push','origin',ver])
|
||||
level='V' if re.match(r'^V[1-9]\d*R0C0', ver) else ('R' if re.match(r'^V\d+R[1-9]\d*C0', ver) else 'C'); exec_sql('INSERT OR REPLACE INTO gitops_versions(version,tag,level,summary,status,created_by,created_at) VALUES(?,?,?,?,?,?,?)',(ver,ver,level,msg,'ready',a['username'],now())); exec_sql('UPDATE gitops_baseline SET active_version=?,active_tag=?,updated_at=? WHERE id=?',(ver,ver,now(),'current')); audit(a['username'],'git_tag',ver,{'level':level}); self.send_json({'status':'tagged','version':ver,'git':out}); return
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,229 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Small staging-only response overlay for the legacy listPatches route.
|
||||
|
||||
The base staging module remains the source of truth for routing, auth, and
|
||||
governed write behavior. This entrypoint only replaces the handler's JSON
|
||||
serializer for the patch-read aliases, projecting the legacy payload into a
|
||||
bounded, cursor-pageable summary while leaving every other route untouched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import urllib.parse
|
||||
from typing import Any
|
||||
|
||||
import aios_model_api_staging as base
|
||||
|
||||
|
||||
PATCH_PATHS = frozenset({"/api/patch", "/api/patches", "/api/branches", "/patch"})
|
||||
PATCH_DEFAULT_LIMIT = 20
|
||||
PATCH_MAX_LIMIT = 100
|
||||
PATCH_RESPONSE_BUDGET = 128 * 1024
|
||||
PATCH_FIELD_MAX_CHARS = 256
|
||||
PATCH_SUMMARY_MAX_CHARS = 1024
|
||||
PATCH_COMPAT_LIST_LIMIT = 20
|
||||
_TOKEN_RE = re.compile(r"(?i)(?:sk-|ghp_|bearer\s+)[A-Za-z0-9._:/+=-]{12,}")
|
||||
|
||||
|
||||
def _text(value: Any, limit: int = PATCH_FIELD_MAX_CHARS) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, (dict, list)):
|
||||
value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
value = _TOKEN_RE.sub("[REDACTED]", str(value))
|
||||
return value if len(value) <= limit else value[: max(1, limit - 1)] + "…"
|
||||
|
||||
|
||||
def _record_id(record: dict[str, Any], index: int) -> str:
|
||||
return _text(
|
||||
record.get("patch_id")
|
||||
or record.get("id")
|
||||
or record.get("patch_name")
|
||||
or record.get("branch")
|
||||
or f"patch-{index}",
|
||||
)
|
||||
|
||||
|
||||
def _record_key(record: dict[str, Any], index: int) -> tuple[bool, str, str, int]:
|
||||
timestamp = _text(
|
||||
record.get("updated_at")
|
||||
or record.get("updatedAt")
|
||||
or record.get("created_at")
|
||||
or record.get("createdAt")
|
||||
)
|
||||
return bool(timestamp), timestamp, _record_id(record, index), index
|
||||
|
||||
|
||||
def _summary(record: dict[str, Any], index: int, summary_limit: int) -> dict[str, Any]:
|
||||
patch_id = _record_id(record, index)
|
||||
raw_summary = next(
|
||||
(
|
||||
record.get(key)
|
||||
for key in ("summary", "description", "text", "intent")
|
||||
if record.get(key) not in (None, "")
|
||||
),
|
||||
"",
|
||||
)
|
||||
summary = _text(raw_summary, summary_limit)
|
||||
item = {
|
||||
"patch_id": patch_id,
|
||||
"name": _text(record.get("name") or record.get("title") or record.get("patch_name") or patch_id),
|
||||
"branch": _text(record.get("branch")) or None,
|
||||
"ref": _text(record.get("ref") or record.get("branch")) or None,
|
||||
"status": _text(record.get("status") or record.get("state") or "recorded"),
|
||||
"risk": _text(record.get("risk")) or None,
|
||||
"created_at": _text(record.get("created_at") or record.get("createdAt")) or None,
|
||||
"updated_at": _text(record.get("updated_at") or record.get("updatedAt")) or None,
|
||||
"commit_oid": _text(record.get("commit_oid") or record.get("commit") or record.get("oid"), 128) or None,
|
||||
"summary": summary,
|
||||
}
|
||||
if len(_text(raw_summary, PATCH_SUMMARY_MAX_CHARS + 1)) > summary_limit:
|
||||
item["summary_truncated"] = True
|
||||
return item
|
||||
|
||||
|
||||
def _branch_summary(record: Any, index: int) -> Any:
|
||||
if not isinstance(record, dict):
|
||||
return _text(record)
|
||||
return {
|
||||
"name": _text(record.get("name") or record.get("branch") or f"branch-{index}"),
|
||||
"ref": _text(record.get("ref") or record.get("name") or record.get("branch")) or None,
|
||||
"oid": _text(record.get("oid") or record.get("commit_oid") or record.get("commit"), 128) or None,
|
||||
"updated_at": _text(record.get("updated_at") or record.get("updatedAt")) or None,
|
||||
}
|
||||
|
||||
|
||||
def _encode_cursor(key: tuple[bool, str, str, int]) -> str:
|
||||
raw = json.dumps(
|
||||
{"has_timestamp": key[0], "timestamp": key[1], "patch_id": key[2], "index": key[3]},
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(value: Any) -> tuple[bool, str, str, int]:
|
||||
if not isinstance(value, str) or not value or len(value) > 256 or re.fullmatch(r"[A-Za-z0-9_-]+", value) is None:
|
||||
raise ValueError("invalid_cursor")
|
||||
try:
|
||||
padded = value + "=" * (-len(value) % 4)
|
||||
decoded = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
|
||||
except Exception as exc:
|
||||
raise ValueError("invalid_cursor") from exc
|
||||
if (
|
||||
not isinstance(decoded, dict)
|
||||
or set(decoded) != {"has_timestamp", "timestamp", "patch_id", "index"}
|
||||
or not isinstance(decoded["has_timestamp"], bool)
|
||||
or not isinstance(decoded["timestamp"], str)
|
||||
or not isinstance(decoded["patch_id"], str)
|
||||
or not isinstance(decoded["index"], int)
|
||||
or decoded["index"] < 0
|
||||
):
|
||||
raise ValueError("invalid_cursor")
|
||||
return decoded["has_timestamp"], decoded["timestamp"], decoded["patch_id"], decoded["index"]
|
||||
|
||||
|
||||
def _limit(query: dict[str, list[str]]) -> int:
|
||||
raw = (query.get("limit") or [str(PATCH_DEFAULT_LIMIT)])[0]
|
||||
try:
|
||||
result = int(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError("invalid_limit") from exc
|
||||
if not 1 <= result <= PATCH_MAX_LIMIT:
|
||||
raise ValueError("invalid_limit")
|
||||
return result
|
||||
|
||||
|
||||
def _page(records: list[Any], query: dict[str, list[str]], summary_limit: int = PATCH_SUMMARY_MAX_CHARS) -> dict[str, Any]:
|
||||
limit = _limit(query)
|
||||
rows = [
|
||||
(record, index, _record_key(record, index))
|
||||
for index, record in enumerate(records)
|
||||
if isinstance(record, dict)
|
||||
]
|
||||
rows.sort(key=lambda row: row[2], reverse=True)
|
||||
cursor = (query.get("cursor") or [None])[0]
|
||||
if cursor:
|
||||
cursor_key = _decode_cursor(cursor)
|
||||
if cursor_key not in {row[2] for row in rows}:
|
||||
raise ValueError("invalid_cursor")
|
||||
rows = [row for row in rows if row[2] < cursor_key]
|
||||
selected = rows[:limit]
|
||||
return {
|
||||
"items": [_summary(record, index, summary_limit) for record, index, _ in selected],
|
||||
"next_cursor": _encode_cursor(selected[-1][2]) if len(rows) > len(selected) and selected else None,
|
||||
"has_more": len(rows) > len(selected),
|
||||
"count": len(selected),
|
||||
"_cursor_keys": [key for _, _, key in selected],
|
||||
}
|
||||
|
||||
|
||||
def _bounded_payload(data: dict[str, Any], query: dict[str, list[str]]) -> dict[str, Any]:
|
||||
records = data.get("metadata_patches")
|
||||
if not isinstance(records, list):
|
||||
records = data.get("patches") if isinstance(data.get("patches"), list) else []
|
||||
page = _page(records, query)
|
||||
cursor_keys = page.pop("_cursor_keys")
|
||||
payload = {
|
||||
key: data[key]
|
||||
for key in ("repository_available", "query_error")
|
||||
if key in data
|
||||
}
|
||||
payload["metadata_patches"] = page["items"]
|
||||
payload["patches"] = page["items"]
|
||||
for key in ("orphan_metadata", "branches_without_metadata"):
|
||||
values = data.get(key)
|
||||
payload[key] = [
|
||||
_summary(value, index, PATCH_SUMMARY_MAX_CHARS)
|
||||
if isinstance(value, dict)
|
||||
else _text(value)
|
||||
for index, value in enumerate(values[:PATCH_COMPAT_LIST_LIMIT])
|
||||
] if isinstance(values, list) else []
|
||||
branches = data.get("authoritative_branches")
|
||||
if isinstance(branches, list):
|
||||
payload["authoritative_branches"] = [
|
||||
_branch_summary(value, index) for index, value in enumerate(branches[:PATCH_COMPAT_LIST_LIMIT])
|
||||
]
|
||||
if isinstance(data.get("branches"), list):
|
||||
payload["branches"] = [_text(value) for value in data["branches"][:PATCH_COMPAT_LIST_LIMIT]]
|
||||
payload.update(page)
|
||||
payload["list_patches_overlay"] = "bounded-summary-v1"
|
||||
|
||||
while len(json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")) > PATCH_RESPONSE_BUDGET and payload["items"]:
|
||||
payload["items"] = payload["items"][:-1]
|
||||
cursor_keys = cursor_keys[:-1]
|
||||
payload["metadata_patches"] = payload["items"]
|
||||
payload["patches"] = payload["items"]
|
||||
payload["count"] = len(payload["items"])
|
||||
payload["has_more"] = True
|
||||
payload["next_cursor"] = (
|
||||
_encode_cursor(cursor_keys[-1])
|
||||
if cursor_keys
|
||||
else None
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
class ListPatchesOverlayHandler(base.H):
|
||||
"""Delegate all behavior except bounded serialization of patch reads."""
|
||||
|
||||
def sendj(self, data: Any, code: int = 200):
|
||||
path = urllib.parse.urlparse(self.path).path.rstrip("/")
|
||||
if path in PATCH_PATHS and code in (200, 503) and isinstance(data, dict):
|
||||
try:
|
||||
data = _bounded_payload(data, urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query))
|
||||
except ValueError as exc:
|
||||
return super().sendj(
|
||||
{"error": str(exc), "min_limit": 1, "max_limit": PATCH_MAX_LIMIT},
|
||||
400,
|
||||
)
|
||||
return super().sendj(data, code)
|
||||
|
||||
|
||||
base.H = ListPatchesOverlayHandler
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
base.main()
|
||||
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
@@ -307,76 +306,14 @@ def authoritative_diff(
|
||||
from_oid = validate_git_revision(from_revision, "from", git_dir=path)
|
||||
to_oid = validate_git_revision(to_revision, "to", git_dir=path)
|
||||
args = ["diff", "--no-ext-diff", "--no-textconv", from_oid, to_oid]
|
||||
patch_limit = max(1, min(_MAX_OUTPUT, 256 * 1024))
|
||||
process = subprocess.Popen(
|
||||
["git", "--git-dir", str(path), *args],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
env={**os.environ, "GIT_OPTIONAL_LOCKS": "0"},
|
||||
)
|
||||
chunks: list[bytes] = []
|
||||
stored_bytes = 0
|
||||
total_bytes = 0
|
||||
started = time.monotonic()
|
||||
try:
|
||||
while process.stdout is not None:
|
||||
chunk = process.stdout.read(64 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
total_bytes += len(chunk)
|
||||
if stored_bytes < patch_limit:
|
||||
remaining = patch_limit - stored_bytes
|
||||
selected = chunk[:remaining]
|
||||
chunks.append(selected)
|
||||
stored_bytes += len(selected)
|
||||
if time.monotonic() - started > _TIMEOUT:
|
||||
process.kill()
|
||||
raise AuthoritativeGitError("GIT_REF_QUERY_TIMEOUT")
|
||||
stderr = (
|
||||
process.stderr.read(8192).decode("utf-8", errors="replace")
|
||||
if process.stderr is not None
|
||||
else ""
|
||||
)
|
||||
returncode = process.wait(timeout=max(0.1, _TIMEOUT - (time.monotonic() - started)))
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
process.kill()
|
||||
process.wait()
|
||||
raise AuthoritativeGitError("GIT_REF_QUERY_FAILED") from exc
|
||||
if returncode != 0:
|
||||
raise AuthoritativeGitError(_redact(stderr.strip() or "GIT_REF_QUERY_FAILED")[:200])
|
||||
try:
|
||||
names_result = run_authoritative_git(
|
||||
["diff", "--no-ext-diff", "--no-textconv", "--name-status", from_oid, to_oid],
|
||||
git_dir=path,
|
||||
)
|
||||
changed_paths = [
|
||||
line.split("\t", 1)[-1]
|
||||
for line in names_result.stdout.splitlines()
|
||||
if line.strip()
|
||||
]
|
||||
except AuthoritativeGitOutputTooLarge:
|
||||
changed_paths = []
|
||||
try:
|
||||
stats_result = run_authoritative_git(
|
||||
["diff", "--no-ext-diff", "--no-textconv", "--stat", from_oid, to_oid],
|
||||
git_dir=path,
|
||||
)
|
||||
stats = stats_result.stdout.strip()
|
||||
except AuthoritativeGitOutputTooLarge:
|
||||
stats = "GIT_STAT_OUTPUT_TRUNCATED"
|
||||
patch = b"".join(chunks).decode("utf-8", errors="replace")
|
||||
result = run_authoritative_git(args, git_dir=path)
|
||||
return {
|
||||
"code": 0,
|
||||
"stdout": patch,
|
||||
"stdout": result.stdout,
|
||||
"stderr": "",
|
||||
"cmd": ["git", f"--git-dir={path}", *args],
|
||||
"from_oid": from_oid,
|
||||
"to_oid": to_oid,
|
||||
"changed_paths": changed_paths,
|
||||
"stats": stats,
|
||||
"total_size_bytes": total_bytes,
|
||||
"truncated": total_bytes > patch_limit,
|
||||
"patch_limit_bytes": patch_limit,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -995,7 +995,7 @@ def validate_writer_lease_request_v2(raw: Mapping[str, Any], probe: Any) -> dict
|
||||
"target_branch": request.target_branch,
|
||||
"generation": request.generation,
|
||||
"lease_seconds": request.lease_seconds,
|
||||
"create_target_branch": request.branch_mode == "CREATE_NEW",
|
||||
"worktree_mode": "detached_at_base_oid" if request.branch_mode == "CREATE_NEW" else "detached_at_expected_head",
|
||||
"create_target_branch": False,
|
||||
"worktree_mode": "detached_at_expected_head",
|
||||
"cas_ref_update_required": True,
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Single canonical Production Baseline authority for the GitOps reader.
|
||||
|
||||
The API and the one-shot writer import this module. Workspace and release
|
||||
copies are projections only; they are never selected as a fallback source.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
AUTHORITY_PATH = Path(os.getenv(
|
||||
"AIOS_GITOPS_BASELINE_AUTHORITY",
|
||||
"/var/lib/aios-gitops-runtime-anchor/baseline/current.json",
|
||||
))
|
||||
AUTHORITY_SHA_PATH = AUTHORITY_PATH.with_suffix(".sha256")
|
||||
|
||||
|
||||
class BaselineAuthorityError(RuntimeError):
|
||||
"""Fail-closed error raised for an unavailable or inconsistent authority."""
|
||||
|
||||
|
||||
class BaselineAuthority:
|
||||
def __init__(self, path: Path | str = AUTHORITY_PATH):
|
||||
self.path = Path(path)
|
||||
self.sha_path = self.path.with_suffix(".sha256")
|
||||
|
||||
def _raw(self) -> bytes:
|
||||
try:
|
||||
raw = self.path.read_bytes()
|
||||
except OSError as exc:
|
||||
raise BaselineAuthorityError(f"authority_unavailable:{exc}") from exc
|
||||
if not raw:
|
||||
raise BaselineAuthorityError("authority_empty")
|
||||
return raw
|
||||
|
||||
def read(self) -> dict[str, Any]:
|
||||
raw = self._raw()
|
||||
digest = hashlib.sha256(raw).hexdigest()
|
||||
try:
|
||||
value = json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise BaselineAuthorityError("authority_invalid_json") from exc
|
||||
if not isinstance(value, dict):
|
||||
raise BaselineAuthorityError("authority_not_object")
|
||||
expected = str(value.get("authority_sha256", ""))
|
||||
if expected and expected != digest:
|
||||
raise BaselineAuthorityError("authority_embedded_digest_mismatch")
|
||||
if self.sha_path.exists():
|
||||
sidecar = self.sha_path.read_text(encoding="utf-8").strip().split()[0]
|
||||
if sidecar != digest:
|
||||
raise BaselineAuthorityError("authority_sidecar_digest_mismatch")
|
||||
required = {
|
||||
"current_baseline", "previous_baseline", "target_oid", "tag_oid",
|
||||
"evidence_closure_oid", "approval_plan_id", "status", "generation",
|
||||
"source_identity",
|
||||
}
|
||||
missing = sorted(required.difference(value))
|
||||
if missing:
|
||||
raise BaselineAuthorityError("authority_missing:" + ",".join(missing))
|
||||
value = dict(value)
|
||||
value["authority_sha256"] = digest
|
||||
value["authority_path"] = str(self.path)
|
||||
return value
|
||||
|
||||
def read_consistent(self, policy: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
value = self.read()
|
||||
if policy:
|
||||
expected = policy.get("release_binding", policy)
|
||||
for key, field in (("version", "current_baseline"),
|
||||
("previous_version", "previous_baseline"),
|
||||
("target_oid", "target_oid"),
|
||||
("tag_oid", "tag_oid"),
|
||||
("evidence_closure_oid", "evidence_closure_oid"),
|
||||
("approval_plan_id", "approval_plan_id")):
|
||||
wanted = expected.get(key)
|
||||
if wanted is not None and value.get(field) != wanted:
|
||||
raise BaselineAuthorityError(f"authority_binding_mismatch:{field}")
|
||||
return value
|
||||
|
||||
@@ -8,7 +8,6 @@ import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
@@ -24,15 +23,10 @@ try:
|
||||
from authoritative_git import AuthoritativeGitError, run_authoritative_git
|
||||
except ModuleNotFoundError:
|
||||
from .authoritative_git import AuthoritativeGitError, run_authoritative_git
|
||||
try:
|
||||
from release_version import RELEASE_VERSION_RE, validate_release_version
|
||||
except ModuleNotFoundError:
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
from release_version import RELEASE_VERSION_RE, validate_release_version
|
||||
|
||||
|
||||
OID_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
VERSION_RE = RELEASE_VERSION_RE
|
||||
VERSION_RE = re.compile(r"^V\d+R\d+C\d+(?:-[A-Za-z0-9_.-]+)?$")
|
||||
DEPLOYMENT_EVIDENCE_RE = re.compile(r"^(?:sha256:[0-9a-f]{64}|git:[0-9a-f]{40})$")
|
||||
FINGERPRINT_FIELDS = (
|
||||
"version",
|
||||
@@ -89,14 +83,9 @@ class PublicationManualOwnerReviewRequired(
|
||||
|
||||
|
||||
def validate_version(version: str) -> str:
|
||||
return validate_release_version(version)
|
||||
|
||||
|
||||
def validate_gitea_api_url(api_url: str) -> str:
|
||||
value = str(api_url or "").strip().rstrip("/")
|
||||
parsed = urllib.parse.urlsplit(value)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise ValueError("Gitea API URL must be HTTP(S)")
|
||||
value = str(version or "")
|
||||
if not VERSION_RE.fullmatch(value):
|
||||
raise ValueError("invalid release version")
|
||||
return value
|
||||
|
||||
|
||||
@@ -422,11 +411,13 @@ class GiteaTagClient:
|
||||
timeout: float = 15,
|
||||
token_line: int = 1,
|
||||
):
|
||||
self.api_url = validate_gitea_api_url(api_url)
|
||||
self.api_url = api_url.rstrip("/")
|
||||
self.repository = repository.strip("/")
|
||||
self.token_file = token_file
|
||||
self.timeout = timeout
|
||||
self.token_line = token_line
|
||||
if not self.api_url.startswith(("https://", "http://")):
|
||||
raise ValueError("Gitea API URL must be HTTP(S)")
|
||||
if self.repository.count("/") != 1:
|
||||
raise ValueError("Gitea repository must be owner/name")
|
||||
|
||||
|
||||
@@ -1,588 +0,0 @@
|
||||
"""Governed V2R2C1 production release orchestration.
|
||||
|
||||
This module is deliberately scoped to the Owner-approved V2R2C1 binding. It
|
||||
uses the existing TagPublisher and metadata adapters; it does not introduce a
|
||||
second Git writer, a second durable job store, or an alternate baseline.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from gitea_tag_publication import (
|
||||
GiteaTagClient,
|
||||
GitTagBackend,
|
||||
PublicationManualOwnerReviewRequired,
|
||||
PublicationPending,
|
||||
PublicationReconciliationRequired,
|
||||
PublicationRequest,
|
||||
TagPublisher,
|
||||
)
|
||||
|
||||
|
||||
VERSION = "V2R2C1"
|
||||
TARGET_OID = "998d30304787e31e5ae607c0bd86b5edb2b0e5ad"
|
||||
EVIDENCE_CLOSURE_OID = "a8b906d1bc24088c19647e98de6a679268f6d0a2"
|
||||
APPROVAL_PLAN_ID = "sha256:c0df52008ae7f64cec5ee2d28947aa7b892066c670ab8295e4549140b1a7500e"
|
||||
REPOSITORY = "aios/aios"
|
||||
SERVICE = "aios-v2r1c7-production.service"
|
||||
PORT = 18927
|
||||
OID_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
SHA_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
|
||||
|
||||
class ReleaseBlocked(RuntimeError):
|
||||
"""A release gate failed and no unsafe recovery is permitted."""
|
||||
|
||||
|
||||
class ManualOwnerReviewRequired(ReleaseBlocked):
|
||||
pass
|
||||
|
||||
|
||||
class ReconciliationRequired(ReleaseBlocked):
|
||||
pass
|
||||
|
||||
|
||||
def canonical(value: object) -> bytes:
|
||||
return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode()
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise ReleaseBlocked("artifact must be a regular file")
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def atomic_json(path: Path, value: Mapping[str, Any], mode: int = 0o600) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(path.name + ".tmp")
|
||||
temporary.write_bytes(canonical(dict(value)))
|
||||
os.chmod(temporary, mode)
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReleaseBinding:
|
||||
version: str = VERSION
|
||||
target_oid: str = TARGET_OID
|
||||
evidence_closure_oid: str = EVIDENCE_CLOSURE_OID
|
||||
approval_plan_id: str = APPROVAL_PLAN_ID
|
||||
repository: str = REPOSITORY
|
||||
production_service: str = SERVICE
|
||||
production_port: int = PORT
|
||||
|
||||
def validate(self) -> None:
|
||||
if self.version != VERSION or self.repository != REPOSITORY:
|
||||
raise ManualOwnerReviewRequired("release binding is outside V2R2C1 scope")
|
||||
if not OID_RE.fullmatch(self.target_oid) or self.target_oid != TARGET_OID:
|
||||
raise ManualOwnerReviewRequired("V2R2C1 target_oid mismatch")
|
||||
if not OID_RE.fullmatch(self.evidence_closure_oid) or self.evidence_closure_oid != EVIDENCE_CLOSURE_OID:
|
||||
raise ManualOwnerReviewRequired("V2R2C1 evidence closure mismatch")
|
||||
if self.approval_plan_id != APPROVAL_PLAN_ID:
|
||||
raise ManualOwnerReviewRequired("V2R2C1 approval plan mismatch")
|
||||
if self.production_service != SERVICE or int(self.production_port) != PORT:
|
||||
raise ManualOwnerReviewRequired("production service binding mismatch")
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"version": self.version,
|
||||
"target_oid": self.target_oid,
|
||||
"evidence_closure_oid": self.evidence_closure_oid,
|
||||
"approval_plan_id": self.approval_plan_id,
|
||||
"repository": self.repository,
|
||||
"production_service": self.production_service,
|
||||
"production_port": self.production_port,
|
||||
}
|
||||
|
||||
|
||||
class StateLock:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
self.handle = None
|
||||
|
||||
def __enter__(self) -> "StateLock":
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.handle = self.path.open("a+", encoding="utf-8")
|
||||
fcntl.flock(self.handle.fileno(), fcntl.LOCK_EX)
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> None:
|
||||
if self.handle is not None:
|
||||
fcntl.flock(self.handle.fileno(), fcntl.LOCK_UN)
|
||||
self.handle.close()
|
||||
|
||||
|
||||
class ReleaseState:
|
||||
def __init__(self, root: Path, binding: ReleaseBinding):
|
||||
self.root = root
|
||||
self.path = root / "release-state.json"
|
||||
self.binding = binding
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
if self.path.exists():
|
||||
value = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
if value.get("binding") != binding.as_dict():
|
||||
raise ManualOwnerReviewRequired("persisted release binding conflict")
|
||||
self.value = value
|
||||
else:
|
||||
self.value = {
|
||||
"schema": "aios.v2r2c1.governed-production-release-state.v1",
|
||||
"binding": binding.as_dict(),
|
||||
"state": "INITIAL",
|
||||
"completed": {},
|
||||
"history": [],
|
||||
}
|
||||
self.save()
|
||||
|
||||
def save(self) -> None:
|
||||
atomic_json(self.path, self.value)
|
||||
|
||||
def record(self, state: str, step: str, result: Mapping[str, Any]) -> None:
|
||||
safe = json.loads(json.dumps(dict(result)))
|
||||
self.value["state"] = state
|
||||
self.value.setdefault("completed", {})[step] = safe
|
||||
self.value.setdefault("history", []).append(
|
||||
{"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "state": state, "step": step, "result": safe}
|
||||
)
|
||||
self.save()
|
||||
|
||||
def fail(self, state: str, reason: str) -> None:
|
||||
self.value["state"] = state
|
||||
self.value.setdefault("history", []).append(
|
||||
{"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "state": state, "reason": str(reason)[:500]}
|
||||
)
|
||||
self.save()
|
||||
|
||||
|
||||
def _git(git_dir: Path, *args: str, check: bool = True) -> str:
|
||||
completed = subprocess.run(
|
||||
["git", f"--git-dir={git_dir}", *args],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=45,
|
||||
env={"PATH": os.environ.get("PATH", "")},
|
||||
)
|
||||
if check and completed.returncode != 0:
|
||||
raise ReconciliationRequired(completed.stderr.strip() or "authoritative git query failed")
|
||||
return completed.stdout.strip()
|
||||
|
||||
|
||||
def _ancestor(git_dir: Path, ancestor: str, descendant: str) -> bool:
|
||||
return subprocess.run(
|
||||
["git", f"--git-dir={git_dir}", "merge-base", "--is-ancestor", ancestor, descendant],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
timeout=45,
|
||||
env={"PATH": os.environ.get("PATH", "")},
|
||||
).returncode == 0
|
||||
|
||||
|
||||
def verify_lineage(git_dir: Path, binding: ReleaseBinding) -> dict[str, Any]:
|
||||
binding.validate()
|
||||
if _git(git_dir, "cat-file", "-t", binding.target_oid) != "commit":
|
||||
raise ReleaseBlocked("approved target_oid is not a commit")
|
||||
if _git(git_dir, "cat-file", "-t", binding.evidence_closure_oid) != "commit":
|
||||
raise ReleaseBlocked("evidence closure is not a commit")
|
||||
if not _ancestor(git_dir, binding.target_oid, binding.evidence_closure_oid):
|
||||
raise ManualOwnerReviewRequired("approved target is not an ancestor of evidence closure")
|
||||
return {
|
||||
"target_oid": binding.target_oid,
|
||||
"evidence_closure_oid": binding.evidence_closure_oid,
|
||||
"target_is_ancestor_of_evidence": True,
|
||||
"main_oid": _git(git_dir, "rev-parse", "refs/heads/main"),
|
||||
}
|
||||
|
||||
|
||||
def verify_owner_approval(value: Mapping[str, Any], binding: ReleaseBinding) -> dict[str, Any]:
|
||||
approval = value.get("owner_approval")
|
||||
if not isinstance(approval, Mapping):
|
||||
raise ReleaseBlocked("OWNER_APPROVAL_RECEIPT_REQUIRED")
|
||||
if approval.get("approved") is not True or approval.get("status") != "APPROVED":
|
||||
raise ReleaseBlocked("OWNER_APPROVAL_NOT_ACCEPTED")
|
||||
if approval.get("approved_by") != "aiman":
|
||||
raise ManualOwnerReviewRequired("OWNER_APPROVAL_ACTOR_MISMATCH")
|
||||
if approval.get("approval_source") != "explicit_owner_approval_in_chat":
|
||||
raise ManualOwnerReviewRequired("OWNER_APPROVAL_SOURCE_MISMATCH")
|
||||
for key, expected in binding.as_dict().items():
|
||||
if key in {"repository", "production_service", "production_port"}:
|
||||
continue
|
||||
if approval.get(key) != expected:
|
||||
raise ManualOwnerReviewRequired("OWNER_APPROVAL_BINDING_MISMATCH:" + key)
|
||||
return dict(approval)
|
||||
|
||||
|
||||
def _payload_file(git_dir: Path, oid: str, path: str) -> bytes:
|
||||
completed = subprocess.run(
|
||||
["git", f"--git-dir={git_dir}", "show", f"{oid}:{path}"],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
timeout=45,
|
||||
env={"PATH": os.environ.get("PATH", "")},
|
||||
)
|
||||
if completed.returncode != 0:
|
||||
raise ReleaseBlocked("required release source missing:" + path)
|
||||
return completed.stdout
|
||||
|
||||
|
||||
def _commit_epoch(git_dir: Path, oid: str) -> int:
|
||||
return int(_git(git_dir, "show", "-s", "--format=%ct", oid))
|
||||
|
||||
|
||||
def build_production_artifact(
|
||||
git_dir: Path,
|
||||
binding: ReleaseBinding,
|
||||
output_root: Path,
|
||||
) -> dict[str, Any]:
|
||||
"""Build a deterministic executable V2R2C1 health artifact from target_oid."""
|
||||
binding.validate()
|
||||
verify_lineage(git_dir, binding)
|
||||
epoch = _commit_epoch(git_dir, binding.target_oid)
|
||||
output_root.mkdir(parents=True, exist_ok=True)
|
||||
stem = f"aios-{VERSION}-{binding.target_oid[:12]}"
|
||||
output = output_root / (stem + ".tar.zst")
|
||||
with tempfile.TemporaryDirectory(prefix="v2r2c1-artifact-") as temp:
|
||||
root = Path(temp) / "payload"
|
||||
root.mkdir(parents=True)
|
||||
source_paths = {
|
||||
"active-runtime/app/deployment_state.py": "active-runtime/app/deployment_state.py",
|
||||
"active-runtime/app/v2r1c6_privacy_tools.py": "active-runtime/app/v2r1c6_privacy_tools.py",
|
||||
}
|
||||
for destination, source in source_paths.items():
|
||||
target = root / destination
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(_payload_file(git_dir, binding.target_oid, source))
|
||||
generated: dict[str, str] = {
|
||||
"VERSION": VERSION + "\n",
|
||||
"active-runtime/app/v2r2c1_health_service.py": (
|
||||
"from v2r1c6_privacy_tools import main\n\n"
|
||||
"if __name__ == '__main__':\n raise SystemExit(main())\n"
|
||||
),
|
||||
"deploy/aios-v2/systemd/aios-v2r1c7-production.service": (
|
||||
"[Unit]\nDescription=AIOS V2R2C1 governed health contract service\n"
|
||||
"After=network.target\n\n[Service]\nType=simple\n"
|
||||
"User=aios-v2r1c7\nGroup=aios-v2r1c7\n"
|
||||
"WorkingDirectory=/opt/aios/v2r2c1\n"
|
||||
"EnvironmentFile=/etc/aios/aios-v2r2c1.env\n"
|
||||
"ExecStart=/usr/bin/python3 /opt/aios/v2r2c1/active-runtime/app/v2r2c1_health_service.py --serve --host 127.0.0.1 --port ${AIOS_V2R1C7_PORT}\n"
|
||||
"Restart=on-failure\nRestartSec=5\nNoNewPrivileges=true\nPrivateTmp=true\n"
|
||||
"ProtectHome=true\nProtectSystem=strict\nProtectKernelLogs=true\n"
|
||||
"ProtectKernelModules=true\nProtectKernelTunables=true\nProtectControlGroups=true\n"
|
||||
"RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nIPAddressDeny=any\n"
|
||||
"IPAddressAllow=localhost\nUMask=0077\n\n[Install]\nWantedBy=multi-user.target\n"
|
||||
),
|
||||
"deploy/aios-v2/v2r2c1-runtime-config.json": json.dumps({
|
||||
"schema": "aios.v2r2c1.production-runtime.v1",
|
||||
"version": VERSION,
|
||||
"target_oid": binding.target_oid,
|
||||
"service": SERVICE,
|
||||
"port": PORT,
|
||||
"health_path": "/health",
|
||||
"deployment_state_source": "environment_and_state_file",
|
||||
}, sort_keys=True, separators=(",", ":")) + "\n",
|
||||
"deploy/aios-v2/v2r2c1-rollback.json": json.dumps({
|
||||
"schema": "aios.v2r2c1.rollback-metadata.v1",
|
||||
"rollback_version": "V2R1C7",
|
||||
"rollback_service": SERVICE,
|
||||
"rollback_target_is_previous_production": True,
|
||||
"automatic_rollback": False,
|
||||
}, sort_keys=True, separators=(",", ":")) + "\n",
|
||||
"scripts/probe_v2r2c1_health.py": (
|
||||
"import json,sys,urllib.request\n"
|
||||
"url=sys.argv[1] if len(sys.argv)>1 else 'http://127.0.0.1:18927/health'\n"
|
||||
"with urllib.request.urlopen(url, timeout=5) as r: print(json.dumps(json.load(r), sort_keys=True))\n"
|
||||
),
|
||||
"scripts/rollback_v2r2c1_release.sh": "#!/bin/sh\nset -eu\nprintf '%s\\n' 'rollback requires governed owner-approved executor'\nexit 2\n",
|
||||
"release-manifests/V2R2C1.json": json.dumps({
|
||||
"schema": "aios.release-source.v2",
|
||||
"version": VERSION,
|
||||
"repository": REPOSITORY,
|
||||
"target_oid": binding.target_oid,
|
||||
"evidence_closure_oid": binding.evidence_closure_oid,
|
||||
"production_deployed": False,
|
||||
"deployment_state": "STAGING",
|
||||
"artifact_kind": "executable-production-health",
|
||||
}, sort_keys=True, separators=(",", ":")) + "\n",
|
||||
}
|
||||
for rel, text in generated.items():
|
||||
target = root / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(text, encoding="utf-8")
|
||||
if rel.startswith("scripts/"):
|
||||
target.chmod(0o755)
|
||||
metadata = {
|
||||
"schema": "aios.release-artifact-build.v3",
|
||||
"version": VERSION,
|
||||
"repository": REPOSITORY,
|
||||
"source_head_oid": binding.target_oid,
|
||||
"evidence_closure_oid": binding.evidence_closure_oid,
|
||||
"source_date_epoch": epoch,
|
||||
"clean_source": True,
|
||||
"executable_payload": True,
|
||||
"production_deployed": False,
|
||||
"tag_created": False,
|
||||
"baseline_changed": False,
|
||||
"secrets_included": False,
|
||||
}
|
||||
(root / "BUILD-METADATA.json").write_bytes(canonical(metadata))
|
||||
(root / "ROLLBACK-METADATA.json").write_bytes(canonical(json.loads((root / "deploy/aios-v2/v2r2c1-rollback.json").read_text(encoding="utf-8"))))
|
||||
names = sorted("payload/" + str(path.relative_to(root)).replace(os.sep, "/") for path in root.rglob("*") if path.is_file())
|
||||
(root / "ARTIFACT-MANIFEST.json").write_bytes(canonical({
|
||||
"schema": "aios.release-artifact-manifest.v3",
|
||||
"version": VERSION,
|
||||
"source_head_oid": binding.target_oid,
|
||||
"evidence_closure_oid": binding.evidence_closure_oid,
|
||||
"repository": REPOSITORY,
|
||||
"files": names + ["payload/ARTIFACT-MANIFEST.json"],
|
||||
"deployable": True,
|
||||
"executable_payload": True,
|
||||
"production_deployed": False,
|
||||
"tag_created": False,
|
||||
"baseline_changed": False,
|
||||
}))
|
||||
tar_path = Path(temp) / "release.tar"
|
||||
with tarfile.open(tar_path, "w") as archive:
|
||||
for path in sorted(root.rglob("*")):
|
||||
relative = str(path.relative_to(root)).replace(os.sep, "/")
|
||||
info = archive.gettarinfo(str(path), arcname="payload/" + relative)
|
||||
info.uid = info.gid = 0
|
||||
info.uname = "root"
|
||||
info.gname = "root"
|
||||
info.mtime = epoch
|
||||
info.mode = 0o755 if path.is_dir() or path.suffix == ".sh" else 0o644
|
||||
if path.is_file():
|
||||
with path.open("rb") as stream:
|
||||
archive.addfile(info, stream)
|
||||
else:
|
||||
archive.addfile(info)
|
||||
subprocess.run(["zstd", "-T1", "-19", "--no-progress", "-q", "-f", str(tar_path), "-o", str(output)], check=True, timeout=120)
|
||||
digest = sha256_file(output)
|
||||
receipt = {
|
||||
"schema": "aios.release-artifact-receipt.v3",
|
||||
"version": VERSION,
|
||||
"repository": REPOSITORY,
|
||||
"source_head_oid": binding.target_oid,
|
||||
"evidence_closure_oid": binding.evidence_closure_oid,
|
||||
"artifact": str(output),
|
||||
"artifact_sha256": digest,
|
||||
"artifact_size": output.stat().st_size,
|
||||
"deployable": True,
|
||||
"executable_payload": True,
|
||||
"production_deployed": False,
|
||||
"tag_created": False,
|
||||
"baseline_changed": False,
|
||||
}
|
||||
atomic_json(output.with_suffix(output.suffix + ".receipt.json"), receipt, mode=0o640)
|
||||
return receipt
|
||||
|
||||
|
||||
class GovernedProductionReleaseExecutor:
|
||||
def __init__(self, config: Any):
|
||||
self.config = config
|
||||
self.binding = ReleaseBinding()
|
||||
self.binding.validate()
|
||||
self.root = Path(config.state_root) / "v2r2c1-governed-production-release"
|
||||
self.state = ReleaseState(self.root, self.binding)
|
||||
workspace = self.root / "publication-workspace"
|
||||
workspace.mkdir(parents=True, exist_ok=True)
|
||||
self.publisher = TagPublisher(
|
||||
workspace,
|
||||
GitTagBackend(workspace, authoritative_repo=Path(config.authoritative_git_dir)),
|
||||
GiteaTagClient(config.api_base, REPOSITORY, Path(config.token_path)),
|
||||
config.remote_name,
|
||||
state_root=self.root / "tag-publication",
|
||||
)
|
||||
# Release checks must use the same explicitly configured staging baseline
|
||||
# as the Action/model runtime; do not fall back to the publication workspace.
|
||||
self.publisher.baseline_path = Path(
|
||||
os.environ.get("AIOS_GITOPS_BASELINE_AUTHORITY", str(config.baseline_path))
|
||||
)
|
||||
# The immutable runtime package is the source of the version projection;
|
||||
# the mutable state workspace only stores publication state.
|
||||
self.publisher.versions_root = Path(__file__).resolve().parents[1] / "versions"
|
||||
|
||||
def _request(self, request: Mapping[str, Any]) -> PublicationRequest:
|
||||
binding = self.binding
|
||||
for key, expected in binding.as_dict().items():
|
||||
if key in request and request[key] != expected:
|
||||
raise ManualOwnerReviewRequired("release request binding mismatch:" + key)
|
||||
return PublicationRequest(binding.version, binding.target_oid, binding.evidence_closure_oid, binding.approval_plan_id)
|
||||
|
||||
def approval_request(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
if request.get("execute") is not False:
|
||||
raise ReleaseBlocked("TAG_APPROVAL_REQUEST_MUST_BE_DRY_RUN")
|
||||
owner = verify_owner_approval(request, self.binding)
|
||||
with StateLock(self.root / "release.lock"):
|
||||
current = self.state.value.get("approval")
|
||||
approval_digest = hashlib.sha256(canonical(owner)).hexdigest()
|
||||
record = {
|
||||
"schema": "aios.v2r2c1.tag-approval-request.v1",
|
||||
"binding": self.binding.as_dict(),
|
||||
"owner_approval": owner,
|
||||
"owner_approval_digest_sha256": approval_digest,
|
||||
"execute": False,
|
||||
"recorded_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
}
|
||||
if current and current != record:
|
||||
raise ManualOwnerReviewRequired("persisted Owner approval differs")
|
||||
self.state.value["approval"] = record
|
||||
self.state.record("APPROVAL_REQUEST_RECORDED", "tag_approval_request", record)
|
||||
return {"status": "RECORDED", "execute": False, "binding": self.binding.as_dict(), "owner_approval_digest_sha256": approval_digest}
|
||||
|
||||
def _require_approval(self) -> None:
|
||||
approval = self.state.value.get("approval")
|
||||
if not isinstance(approval, Mapping) or approval.get("binding") != self.binding.as_dict():
|
||||
raise ReleaseBlocked("OWNER_APPROVAL_REQUEST_NOT_RECORDED")
|
||||
|
||||
def publish_tag(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
if request.get("execute") is not True:
|
||||
raise ReleaseBlocked("TAG_PUBLICATION_REQUIRES_EXECUTE_TRUE")
|
||||
self._require_approval()
|
||||
publication = self._request(request)
|
||||
with StateLock(self.root / "release.lock"):
|
||||
try:
|
||||
verified = self.publisher._verify_publication(publication, allow_push=True, previously_deployed=False)
|
||||
except PublicationManualOwnerReviewRequired as exc:
|
||||
self.state.fail("MANUAL_OWNER_REVIEW_REQUIRED", str(exc))
|
||||
raise ManualOwnerReviewRequired(str(exc)) from exc
|
||||
except PublicationPending as exc:
|
||||
self.state.fail("REMOTE_PUSH_PENDING", str(exc))
|
||||
raise ReconciliationRequired(str(exc)) from exc
|
||||
except PublicationReconciliationRequired as exc:
|
||||
self.state.fail("RECONCILIATION_REQUIRED", str(exc))
|
||||
raise ReconciliationRequired(str(exc)) from exc
|
||||
result = dict(verified)
|
||||
self.state.record("TAG_VERIFIED", "tag", result)
|
||||
return {"status": "REMOTE_VERIFIED", **result}
|
||||
|
||||
def tag_status(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
self._request(request)
|
||||
return self.publisher.get_tag_publication_status(VERSION)
|
||||
|
||||
def build_artifact(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
self._require_approval()
|
||||
self._request(request)
|
||||
receipt = build_production_artifact(Path(self.config.authoritative_git_dir), self.binding, self.root / "artifacts")
|
||||
self.state.record("ARTIFACT_VERIFIED", "production_artifact", receipt)
|
||||
return {"status": "VERIFIED", **receipt}
|
||||
|
||||
def execute_request(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
self._require_approval()
|
||||
publication = self._request(request)
|
||||
tag_state = self.state.value.get("completed", {}).get("tag")
|
||||
if not isinstance(tag_state, Mapping) or tag_state.get("state") not in {"GITEA_API_CONFIRMED", "REMOTE_VERIFIED"}:
|
||||
raise ReleaseBlocked("REMOTE_TAG_PROOF_REQUIRED")
|
||||
artifact = self.state.value.get("completed", {}).get("production_artifact")
|
||||
if not isinstance(artifact, Mapping):
|
||||
artifact = self.build_artifact(request)
|
||||
value = {
|
||||
**self.binding.as_dict(),
|
||||
"tag_oid": tag_state.get("tag_oid") or tag_state.get("gitea_tag_oid"),
|
||||
"artifact_path": artifact["artifact"],
|
||||
"artifact_size": int(artifact["artifact_size"]),
|
||||
"artifact_sha256": artifact["artifact_sha256"],
|
||||
}
|
||||
# The production adapter is privileged and is run through the root
|
||||
# approved-release service boundary by the caller. This handler is
|
||||
# still useful for a root-owned staging invocation and remains
|
||||
# fail-closed when the adapter is not available.
|
||||
import v2r2c1_production_adapter
|
||||
runtime = v2r2c1_production_adapter.execute_request({"schema": "aios.production-executor-request.v1", "operation": "apply", **value})
|
||||
if runtime.get("status") != "ACTIVE_VERIFIED":
|
||||
self.state.fail("RECONCILIATION_REQUIRED", "production health did not verify")
|
||||
raise ReconciliationRequired("production health did not verify")
|
||||
self.state.record("PRODUCTION_VERIFIED", "production", runtime)
|
||||
return {"status": "PRODUCTION_VERIFIED", "runtime": runtime, "artifact": artifact, "tag_oid": value["tag_oid"]}
|
||||
|
||||
def consistency(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
publication = self._request(request)
|
||||
result = self.publisher.get_release_consistency(publication)
|
||||
result["release_binding"] = self.binding.as_dict()
|
||||
result["production_health"] = _health(self.config.health_url, self.binding, self.state.value.get("completed", {}).get("production_artifact", {}))
|
||||
result["registry"] = _read_json(Path(self.config.registry_root) / f"{VERSION}.json")
|
||||
result["baseline"] = _read_json(Path(self.config.baseline_path))
|
||||
return result
|
||||
|
||||
def acceptance(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
||||
result = self.consistency(request)
|
||||
result["accepted"] = (
|
||||
result.get("status") == "PASS"
|
||||
and result.get("production_health", {}).get("verification_status")
|
||||
== "ACTIVE_VERIFIED"
|
||||
)
|
||||
self.state.record("ACCEPTED" if result["accepted"] else "RECONCILIATION_REQUIRED", "acceptance", result)
|
||||
return result
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {"status": "MISSING", "path": str(path)}
|
||||
if not isinstance(value, dict):
|
||||
return {"status": "INVALID", "path": str(path)}
|
||||
return {"status": "PRESENT", "path": str(path), **value}
|
||||
|
||||
|
||||
def _health(url: str, binding: ReleaseBinding, artifact: Mapping[str, Any]) -> dict[str, Any]:
|
||||
import urllib.request
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=5) as response:
|
||||
body = json.loads(response.read().decode("utf-8"))
|
||||
status = response.status
|
||||
except Exception as exc:
|
||||
return {
|
||||
"status": "UNAVAILABLE",
|
||||
"verification_status": "UNAVAILABLE",
|
||||
"error": type(exc).__name__,
|
||||
}
|
||||
expected_artifact = artifact.get("artifact_sha256")
|
||||
exact = (
|
||||
status == 200
|
||||
and body.get("version") == binding.version
|
||||
and body.get("commit_oid") == binding.target_oid
|
||||
and (not expected_artifact or body.get("artifact_sha256") == expected_artifact)
|
||||
and body.get("deployment_state") == "ACTIVE"
|
||||
and body.get("production_deployed") is True
|
||||
)
|
||||
return {
|
||||
**body,
|
||||
"http_status": status,
|
||||
"verification_status": "ACTIVE_VERIFIED" if exact else "CONFLICT",
|
||||
}
|
||||
|
||||
|
||||
def build_executor_config(config: Any) -> GovernedProductionReleaseExecutor:
|
||||
return GovernedProductionReleaseExecutor(config)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("operation", choices=("build-artifact", "status"))
|
||||
parser.add_argument("--git-dir", type=Path, default=Path("/data/aios-gitops/repo.git"))
|
||||
parser.add_argument("--output-root", type=Path, default=Path("/var/lib/aios-gitops/approved-artifacts/V2R2C1"))
|
||||
args = parser.parse_args()
|
||||
binding = ReleaseBinding()
|
||||
if args.operation == "build-artifact":
|
||||
print(json.dumps(build_production_artifact(args.git_dir, binding, args.output_root), sort_keys=True))
|
||||
else:
|
||||
print(json.dumps({"binding": binding.as_dict(), "status": "READY"}, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -34,8 +34,6 @@ from gitea_tag_publication import (
|
||||
TagPublisher,
|
||||
)
|
||||
|
||||
from release_version import validate_release_version
|
||||
|
||||
OID_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
PLAN_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
|
||||
|
||||
@@ -46,10 +44,8 @@ def load_request() -> dict[str, Any]:
|
||||
raise ValueError("request_object_required")
|
||||
if value.get("schema") != "aios.production-executor-request.v1":
|
||||
raise ValueError("request_schema_invalid")
|
||||
try:
|
||||
validate_release_version(value.get("version", ""))
|
||||
except ValueError as exc:
|
||||
raise ValueError("version_invalid") from exc
|
||||
if not re.fullmatch(r"V\d+R\d+C\d+(?:-[A-Za-z0-9_.-]+)?", str(value.get("version", ""))):
|
||||
raise ValueError("version_invalid")
|
||||
for name in ("target_oid", "evidence_closure_oid"):
|
||||
if not OID_RE.fullmatch(str(value.get(name, ""))):
|
||||
raise ValueError(f"{name}_invalid")
|
||||
|
||||
@@ -27,8 +27,6 @@ import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from release_version import validate_release_version
|
||||
|
||||
OID_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
SHA_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
PLAN_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
|
||||
@@ -88,10 +86,8 @@ def load_request() -> dict[str, Any]:
|
||||
raise ValueError("request_schema_invalid")
|
||||
if value.get("repository_identity") != "aios/aios":
|
||||
raise ValueError("repository_identity_invalid")
|
||||
try:
|
||||
validate_release_version(value.get("version", ""))
|
||||
except ValueError as exc:
|
||||
raise ValueError("version_invalid") from exc
|
||||
if not re.fullmatch(r"V\d+R\d+C\d+(?:-[A-Za-z0-9_.-]+)?", str(value.get("version", ""))):
|
||||
raise ValueError("version_invalid")
|
||||
for name in ("target_oid", "evidence_closure_oid"):
|
||||
if not OID_RE.fullmatch(str(value.get(name, ""))):
|
||||
raise ValueError(f"{name}_invalid")
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
"""Durable, generation-scoped leases for the staging governed writer."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
from typing import Any, Mapping
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _iso(value: datetime) -> str:
|
||||
return value.isoformat()
|
||||
|
||||
|
||||
def _expired(value: str) -> bool:
|
||||
return datetime.fromisoformat(value).astimezone(timezone.utc) <= _now()
|
||||
|
||||
|
||||
class ScopedLeaseError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class ScopedLeaseStore:
|
||||
"""A small SQLite CAS boundary; no repository or filesystem writes."""
|
||||
|
||||
def __init__(self, path: Path) -> None:
|
||||
if not path.is_absolute() or path.is_symlink():
|
||||
raise ScopedLeaseError("LEASE_STORE_INVALID")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.path = path
|
||||
with self._connect() as db:
|
||||
db.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS scoped_leases (
|
||||
lease_key TEXT PRIMARY KEY,
|
||||
task_id TEXT NOT NULL,
|
||||
repository TEXT NOT NULL,
|
||||
target_branch TEXT NOT NULL,
|
||||
expected_branch_oid TEXT NOT NULL,
|
||||
generation INTEGER NOT NULL,
|
||||
binding_json TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
idempotency_key TEXT,
|
||||
result_json TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS scoped_leases_binding
|
||||
ON scoped_leases(task_id, repository, target_branch, generation);
|
||||
"""
|
||||
)
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
db = sqlite3.connect(self.path, timeout=30.0)
|
||||
db.row_factory = sqlite3.Row
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
db.execute("PRAGMA synchronous=FULL")
|
||||
db.execute("PRAGMA busy_timeout=30000")
|
||||
return db
|
||||
|
||||
@staticmethod
|
||||
def key(request: Mapping[str, Any]) -> str:
|
||||
binding = {
|
||||
field: request[field]
|
||||
for field in (
|
||||
"task_id", "repository", "branch_mode", "base_oid",
|
||||
"expected_branch_oid", "target_branch", "generation",
|
||||
"lease_seconds",
|
||||
)
|
||||
}
|
||||
return hashlib.sha256(
|
||||
json.dumps(binding, sort_keys=True, separators=(",", ":")).encode()
|
||||
).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def _row(row: sqlite3.Row) -> dict[str, Any]:
|
||||
value = dict(row)
|
||||
value["binding"] = json.loads(value.pop("binding_json"))
|
||||
if value.get("result_json"):
|
||||
value["result"] = json.loads(value.pop("result_json"))
|
||||
else:
|
||||
value.pop("result_json", None)
|
||||
return value
|
||||
|
||||
def acquire(self, request: Mapping[str, Any]) -> tuple[dict[str, Any], bool]:
|
||||
key = self.key(request)
|
||||
now = _now()
|
||||
expires = now.timestamp() + int(request["lease_seconds"])
|
||||
expires_at = _iso(datetime.fromtimestamp(expires, timezone.utc))
|
||||
binding_json = json.dumps(dict(request), sort_keys=True, separators=(",", ":"))
|
||||
try:
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
exact = db.execute(
|
||||
"SELECT * FROM scoped_leases WHERE lease_key=?", (key,)
|
||||
).fetchone()
|
||||
if exact is not None:
|
||||
if exact["state"] == "ACTIVE" and _expired(exact["expires_at"]):
|
||||
db.execute(
|
||||
"UPDATE scoped_leases SET state='EXPIRED',updated_at=? WHERE lease_key=?",
|
||||
(_iso(now), key),
|
||||
)
|
||||
exact = db.execute(
|
||||
"SELECT * FROM scoped_leases WHERE lease_key=?", (key,)
|
||||
).fetchone()
|
||||
db.commit()
|
||||
return self._row(exact), False
|
||||
active = db.execute(
|
||||
"SELECT * FROM scoped_leases WHERE task_id=? AND repository=? AND target_branch=? AND state='ACTIVE'",
|
||||
(str(request["task_id"]), str(request["repository"]), str(request["target_branch"])),
|
||||
).fetchall()
|
||||
for row in active:
|
||||
if _expired(row["expires_at"]):
|
||||
db.execute(
|
||||
"UPDATE scoped_leases SET state='EXPIRED',updated_at=? WHERE lease_key=?",
|
||||
(_iso(now), row["lease_key"]),
|
||||
)
|
||||
else:
|
||||
raise ScopedLeaseError("LEASE_BINDING_CONFLICT")
|
||||
db.execute(
|
||||
"INSERT INTO scoped_leases(lease_key,task_id,repository,target_branch,expected_branch_oid,generation,binding_json,expires_at,state,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
key, request["task_id"], request["repository"],
|
||||
request["target_branch"], request["expected_branch_oid"],
|
||||
int(request["generation"]), binding_json, expires_at,
|
||||
"ACTIVE", _iso(now), _iso(now),
|
||||
),
|
||||
)
|
||||
row = db.execute(
|
||||
"SELECT * FROM scoped_leases WHERE lease_key=?", (key,)
|
||||
).fetchone()
|
||||
db.commit()
|
||||
return self._row(row), True
|
||||
except ScopedLeaseError:
|
||||
raise
|
||||
except sqlite3.Error as exc:
|
||||
raise ScopedLeaseError("LEASE_STORE_UNAVAILABLE") from exc
|
||||
|
||||
def for_commit(self, request: Mapping[str, Any]) -> dict[str, Any] | None:
|
||||
try:
|
||||
with self._connect() as db:
|
||||
row = db.execute(
|
||||
"SELECT * FROM scoped_leases WHERE task_id=? AND repository=? AND target_branch=? AND expected_branch_oid=? AND generation=? ORDER BY created_at DESC LIMIT 1",
|
||||
(
|
||||
request["task_id"], request["repository"],
|
||||
request["target_branch"], request["expected_branch_oid"],
|
||||
int(request["generation"]),
|
||||
),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if row["state"] == "ACTIVE" and _expired(row["expires_at"]):
|
||||
db.execute(
|
||||
"UPDATE scoped_leases SET state='EXPIRED',updated_at=? WHERE lease_key=?",
|
||||
(_iso(_now()), row["lease_key"]),
|
||||
)
|
||||
row = db.execute(
|
||||
"SELECT * FROM scoped_leases WHERE lease_key=?", (row["lease_key"],)
|
||||
).fetchone()
|
||||
return self._row(row)
|
||||
except sqlite3.Error as exc:
|
||||
raise ScopedLeaseError("LEASE_STORE_UNAVAILABLE") from exc
|
||||
|
||||
def mark_used(self, lease_key: str, idempotency_key: str, result: Mapping[str, Any]) -> None:
|
||||
with self._connect() as db:
|
||||
updated = db.execute(
|
||||
"UPDATE scoped_leases SET state='USED',idempotency_key=?,result_json=?,updated_at=? WHERE lease_key=? AND state='ACTIVE'",
|
||||
(
|
||||
idempotency_key, json.dumps(dict(result), sort_keys=True),
|
||||
_iso(_now()), lease_key,
|
||||
),
|
||||
)
|
||||
if updated.rowcount != 1:
|
||||
raise ScopedLeaseError("LEASE_ALREADY_USED")
|
||||
|
||||
def delete(self, lease_key: str) -> None:
|
||||
with self._connect() as db:
|
||||
db.execute("DELETE FROM scoped_leases WHERE lease_key=? AND state='ACTIVE'", (lease_key,))
|
||||
@@ -22,12 +22,11 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from release_version import validate_release_version
|
||||
|
||||
|
||||
OID_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
CANDIDATE_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{2,127}$")
|
||||
VERSION_RE = re.compile(r"^V\d+R\d+C\d+(?:-[A-Za-z0-9_.-]+)?$")
|
||||
SECRET_PATTERNS = (
|
||||
re.compile(r"(?i)(authorization\s*[:=]\s*)(?:bearer|token)\s+\S+"),
|
||||
re.compile(r"(?i)((?:access_)?token\s*[:=]\s*)\S+"),
|
||||
@@ -770,10 +769,8 @@ class TagApprovalEnvelope:
|
||||
def validate(self) -> None:
|
||||
if self.action != "production_tag":
|
||||
raise ApprovalError("approval does not authorize production tag")
|
||||
try:
|
||||
validate_release_version(self.version)
|
||||
except ValueError as exc:
|
||||
raise ApprovalError("invalid release version") from exc
|
||||
if not VERSION_RE.fullmatch(self.version):
|
||||
raise ApprovalError("invalid release version")
|
||||
_validate_oid("tag_oid", self.tag_oid)
|
||||
_validate_oid("target_oid", self.target_oid)
|
||||
if _parse_utc(self.expires_at) <= datetime.now(timezone.utc):
|
||||
|
||||
@@ -3457,19 +3457,6 @@ class SilentReleaseActionService:
|
||||
}
|
||||
|
||||
def get_release_saga(self, candidate_id: str) -> dict[str, Any]:
|
||||
# A read of a never-created candidate is a normal empty-state. Do
|
||||
# not turn a missing journal into a durable manual-review snapshot.
|
||||
saga_path = self.sagas._path(candidate_id)
|
||||
journal_path = self.sagas._journal(candidate_id)
|
||||
if not saga_path.exists() and not journal_path.exists():
|
||||
return {
|
||||
"candidate_id": candidate_id,
|
||||
"status": "NOT_FOUND",
|
||||
"state": "NOT_FOUND",
|
||||
"execution_enabled": self.execution_enabled,
|
||||
"shadow_mode": not self.execution_enabled,
|
||||
"side_effects_executed": False,
|
||||
}
|
||||
return {
|
||||
**self.sagas.load(candidate_id).to_dict(),
|
||||
"execution_enabled": self.execution_enabled,
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
"""V2R2C1 adapter using the existing V2R1C7 deployment primitives.
|
||||
|
||||
The service identity and loopback port remain stable for a safe cutover. The
|
||||
new release is installed under its own immutable directory and keeps the
|
||||
previous V2R1C7 release available for an explicit, owner-approved rollback.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from argparse import Namespace
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
import v2r1c7_production_adapter as base
|
||||
|
||||
|
||||
VERSION = "V2R2C1"
|
||||
SERVICE = "aios-v2r1c7-production.service"
|
||||
PORT = 18927
|
||||
RELEASE_ROOT = Path("/opt/aios/releases")
|
||||
CURRENT_LINK = Path("/opt/aios/v2r2c1")
|
||||
ENV_FILE = Path("/etc/aios/aios-v2r2c1.env")
|
||||
STATE_FILE = Path("/var/lib/aios/v2r2c1/deployment-state.json")
|
||||
UNIT_FILE = Path("/etc/systemd/system/aios-v2r1c7-production.service")
|
||||
ROLLBACK_ROOT = Path("/var/lib/aios/v2r2c1/rollback")
|
||||
|
||||
REQUIRED_MEMBERS = {
|
||||
"payload/VERSION",
|
||||
"payload/active-runtime/app/deployment_state.py",
|
||||
"payload/active-runtime/app/v2r1c6_privacy_tools.py",
|
||||
"payload/active-runtime/app/v2r2c1_health_service.py",
|
||||
"payload/deploy/aios-v2/systemd/aios-v2r1c7-production.service",
|
||||
"payload/deploy/aios-v2/v2r2c1-runtime-config.json",
|
||||
"payload/deploy/aios-v2/v2r2c1-rollback.json",
|
||||
"payload/scripts/probe_v2r2c1_health.py",
|
||||
"payload/scripts/rollback_v2r2c1_release.sh",
|
||||
"payload/BUILD-METADATA.json",
|
||||
"payload/ARTIFACT-MANIFEST.json",
|
||||
"payload/ROLLBACK-METADATA.json",
|
||||
}
|
||||
|
||||
|
||||
def _configure_base() -> None:
|
||||
base.VERSION = VERSION
|
||||
base.SERVICE = SERVICE
|
||||
base.PORT = PORT
|
||||
base.REQUIRED_MEMBERS = REQUIRED_MEMBERS
|
||||
|
||||
|
||||
def _args() -> Namespace:
|
||||
return Namespace(
|
||||
release_root=RELEASE_ROOT,
|
||||
current_link=CURRENT_LINK,
|
||||
env_file=ENV_FILE,
|
||||
state_file=STATE_FILE,
|
||||
unit_file=UNIT_FILE,
|
||||
health_timeout=45,
|
||||
)
|
||||
|
||||
|
||||
def load_request() -> dict[str, Any]:
|
||||
_configure_base()
|
||||
value = base.load_request()
|
||||
if value.get("version") != VERSION or value.get("production_service") != SERVICE or int(value.get("production_port", -1)) != PORT:
|
||||
raise ValueError("V2R2C1 production binding mismatch")
|
||||
return value
|
||||
|
||||
|
||||
def _backup(path: Path, name: str) -> None:
|
||||
if path.is_file() and not path.is_symlink():
|
||||
ROLLBACK_ROOT.mkdir(parents=True, exist_ok=True)
|
||||
destination = ROLLBACK_ROOT / name
|
||||
if not destination.exists():
|
||||
shutil.copy2(path, destination)
|
||||
|
||||
|
||||
def execute_request(value: Mapping[str, Any]) -> dict[str, Any]:
|
||||
_configure_base()
|
||||
if value.get("schema") != "aios.production-executor-request.v1":
|
||||
raise ValueError("request_schema_invalid")
|
||||
if value.get("operation") == "apply":
|
||||
_backup(UNIT_FILE, "aios-v2r1c7-production.service.previous")
|
||||
_backup(Path("/etc/aios/aios-v2r1c7.env"), "aios-v2r1c7.env.previous")
|
||||
_backup(Path("/var/lib/aios/v2r1c7/deployment-state.json"), "v2r1c7-deployment-state.previous")
|
||||
return base.install_release(_args(), value)
|
||||
if value.get("operation") == "probe":
|
||||
return base.probe(_args(), value)
|
||||
if value.get("operation") == "rollback":
|
||||
return rollback(value)
|
||||
raise ValueError("unsupported_operation")
|
||||
|
||||
|
||||
def rollback(value: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""Explicit rollback only; this adapter never invokes it automatically."""
|
||||
import subprocess
|
||||
|
||||
subprocess.run(["systemctl", "stop", SERVICE], check=False, capture_output=True, text=True, timeout=45)
|
||||
previous_unit = ROLLBACK_ROOT / "aios-v2r1c7-production.service.previous"
|
||||
previous_env = ROLLBACK_ROOT / "aios-v2r1c7.env.previous"
|
||||
previous_state = ROLLBACK_ROOT / "v2r1c7-deployment-state.previous"
|
||||
if not previous_unit.is_file() or not previous_env.is_file():
|
||||
raise RuntimeError("ROLLBACK_RECEIPT_MISSING")
|
||||
UNIT_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
ENV_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(previous_unit, UNIT_FILE)
|
||||
shutil.copy2(previous_env, Path("/etc/aios/aios-v2r1c7.env"))
|
||||
if previous_state.is_file():
|
||||
Path("/var/lib/aios/v2r1c7").mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(previous_state, Path("/var/lib/aios/v2r1c7/deployment-state.json"))
|
||||
subprocess.run(["systemctl", "daemon-reload"], check=True, capture_output=True, text=True, timeout=45)
|
||||
subprocess.run(["systemctl", "restart", SERVICE], check=True, capture_output=True, text=True, timeout=45)
|
||||
result = base.health("http://127.0.0.1:18927/health", {
|
||||
"version": "V2R1C7",
|
||||
"target_oid": str(json.loads(Path("/var/lib/aios/v2r1c7/deployment-state.json").read_text(encoding="utf-8")).get("commit_oid")),
|
||||
"artifact_sha256": str(json.loads(Path("/var/lib/aios/v2r1c7/deployment-state.json").read_text(encoding="utf-8")).get("artifact_sha256")),
|
||||
})
|
||||
return {"status": "ROLLED_BACK", "rollback_health": result, "automatic_rollback": False}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
value = load_request()
|
||||
result = execute_request(value)
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
return 0
|
||||
except Exception as exc:
|
||||
print(json.dumps({"status": "FAIL_CLOSED", "error": type(exc).__name__, "reason": str(exc)}, sort_keys=True))
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,20 +0,0 @@
|
||||
[Service]
|
||||
User=aiman
|
||||
Group=gitops
|
||||
WorkingDirectory=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime
|
||||
ExecStart=
|
||||
ExecStart=/usr/bin/python3 -B /opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime/app/aios_chatgpt_bridge_v2_server.py
|
||||
Environment=AIOS_CONTROL_PLANE_TARGET_OID=@SOURCE_OID@
|
||||
Environment=AIOS_CONTROL_PLANE_TARGET_VERSION=V2R2C1
|
||||
Environment=AIOS_CONTROL_PLANE_RUNTIME_PATH=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime
|
||||
Environment=AIOS_CONTROL_PLANE_ARTIFACT=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime/manifest.json
|
||||
Environment=AIOS_CONTROL_PLANE_ARTIFACT_SHA256=@ARTIFACT_SHA256@
|
||||
Environment=AIOS_GITOPS_WRITES_ENABLED=false
|
||||
Environment=AIOS_GITOPS_DURABLE_JOB_EXECUTION_ENABLED=true
|
||||
Environment=AIOS_GITOPS_TOKEN_FILE=%d/action_tokens
|
||||
Environment=AIOS_GITEA_API_BASE=https://g.cnnetmkt.top/git/api/v1
|
||||
Environment=AIOS_BRIDGE_V2_PORT=18892
|
||||
Environment=PYTHONPATH=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime:/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime/app:/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime/runtime-agent-os
|
||||
LoadCredential=action_tokens:/data/aios-gitops/runtime/secrets/gitops.tokens
|
||||
ReadOnlyPaths=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime /data/aios-gitops/repo.git
|
||||
ReadWritePaths=/var/lib/aios-gitops/bridge-v2-staging
|
||||
@@ -4,32 +4,19 @@ After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=aiman
|
||||
Group=gitops
|
||||
PermissionsStartOnly=true
|
||||
WorkingDirectory=@RUNTIME_ROOT@
|
||||
User=aios-bridge-staging
|
||||
Group=aios-bridge-staging
|
||||
WorkingDirectory=/opt/aios/gitops-control-plane/current
|
||||
Environment=AIOS_BRIDGE_SCHEMA_VERSION=aios.chatgpt-gitops-bridge.v2
|
||||
Environment=AIOS_GITOPS_WRITES_ENABLED=false
|
||||
Environment=AIOS_GITOPS_DURABLE_JOB_EXECUTION_ENABLED=true
|
||||
Environment=AIOS_GITOPS_WRITES_ENABLED=false
|
||||
Environment=AIOS_GITEA_API_BASE=https://g.cnnetmkt.top/git/api/v1
|
||||
Environment=AIOS_GITEA_TOKEN_FILE=/run/credentials/aios-chatgpt-bridge-v2-staging.service/gitea_token
|
||||
Environment=AIOS_GITEA_REMOTE=gitea-http
|
||||
Environment=AIOS_GITOPS_BASELINE_AUTHORITY=/var/lib/aios-gitops/model-api-staging/baseline/current.json
|
||||
Environment=AIOS_CONTROL_PLANE_TARGET_VERSION=V2R2C1
|
||||
Environment=AIOS_CONTROL_PLANE_TARGET_OID=@SOURCE_OID@
|
||||
Environment=AIOS_CONTROL_PLANE_ARTIFACT_SHA256=@ARTIFACT_SHA256@
|
||||
Environment=PYTHONPATH=@RUNTIME_ROOT@:@RUNTIME_ROOT@/app:@RUNTIME_ROOT@/runtime-agent-os
|
||||
Environment=AIOS_DEPLOYMENT_STATE=STAGING
|
||||
LoadCredential=gitea_token:/run/credentials/aios-governance-executor.service/gitea-governance-executor-token
|
||||
ExecStartPre=/usr/bin/install -d -o aiman -g gitops -m 0750 /var/lib/aios-gitops/bridge-v2-staging
|
||||
ExecStartPre=/usr/bin/setfacl -m u:aiman:--x /usr/local/libexec
|
||||
ExecStart=/usr/bin/python3 -B @RUNTIME_ROOT@/app/aios_chatgpt_bridge_v2_server.py
|
||||
ExecStart=/usr/bin/python3 /opt/aios/gitops-control-plane/current/bridge-v2-staging-server.py
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/var/lib/aios-gitops/bridge-v2-staging /data/aios-gitops/repo.git
|
||||
ReadWritePaths=/var/lib/aios-gitops/bridge-v2-staging
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
[Service]
|
||||
User=aiman
|
||||
Group=gitops
|
||||
WorkingDirectory=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime
|
||||
ExecStart=
|
||||
ExecStart=/usr/bin/python3 -B /opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime/app/aios_model_api_staging_list_patches_overlay.py
|
||||
Environment=AIOS_GITOPS_WORKSPACE=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime
|
||||
Environment=AIOS_GITOPS_RUNTIME_OID=@SOURCE_OID@
|
||||
Environment=AIOS_GITOPS_ARTIFACT=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime/manifest.json
|
||||
Environment=AIOS_GITOPS_ARTIFACT_SHA256=@ARTIFACT_SHA256@
|
||||
Environment=AIOS_GITOPS_DEPLOYMENT_STATE=STAGING
|
||||
Environment=AIOS_GITOPS_WRITES_ENABLED=false
|
||||
Environment=AIOS_GITOPS_DURABLE_JOB_EXECUTION_ENABLED=true
|
||||
Environment=AIOS_GITOPS_JOB_CONTROLLER_ENABLED=false
|
||||
Environment=AIOS_GITOPS_TOKEN_FILE=%d/action_tokens
|
||||
Environment=AIOS_GITOPS_GITEA_API_URL=https://g.cnnetmkt.top/git/api/v1
|
||||
Environment=AIOS_BRIDGE_V2_URL=http://127.0.0.1:18892
|
||||
Environment=AIOS_GITOPS_PORT=18893
|
||||
Environment=PYTHONPATH=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime:/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime/app:/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime/runtime-agent-os
|
||||
LoadCredential=action_tokens:/data/aios-gitops/runtime/secrets/gitops.tokens
|
||||
ReadOnlyPaths=/opt/aios/gitops-model-api/@SOURCE_OID@-minimal-autonomous-loop/runtime /data/aios-gitops/repo.git
|
||||
ReadWritePaths=/var/lib/aios-gitops/model-api-staging
|
||||
@@ -1,67 +0,0 @@
|
||||
[Unit]
|
||||
Description=AIOS GitOps Model API V2R2C1 immutable staging runtime
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=aiman
|
||||
Group=gitops
|
||||
PermissionsStartOnly=true
|
||||
ExecStartPre=/usr/bin/install -d -o aiman -g gitops -m 0750 /var/lib/aios-gitops/model-api-staging
|
||||
ExecStartPre=/usr/bin/install -d -o aiman -g gitops -m 0750 /var/lib/aios-gitops/model-api-staging/silent-release
|
||||
ExecStartPre=/usr/bin/install -d -o root -g gitops -m 0750 /var/lib/aios-gitops/model-api-staging/baseline
|
||||
ExecStartPre=/usr/bin/setfacl -m u:aiman:--x /usr/local/libexec
|
||||
WorkingDirectory=@RUNTIME_ROOT@
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
Environment=PYTHONDONTWRITEBYTECODE=1
|
||||
Environment=AIOS_GITOPS_ROOT=/var/lib/aios-gitops
|
||||
Environment=AIOS_GITOPS_WORKSPACE=@RUNTIME_ROOT@
|
||||
Environment=AIOS_GITOPS_REPO=/data/aios-gitops/repo.git
|
||||
Environment=AIOS_GITOPS_BARE_REPO=/data/aios-gitops/repo.git
|
||||
Environment=AIOS_GITOPS_AUTHORITATIVE_GIT_DIR=/data/aios-gitops/repo.git
|
||||
Environment=AIOS_GITOPS_REPOSITORY_IDENTITY=aios/aios
|
||||
Environment=AIOS_GITOPS_BASELINE_AUTHORITY=/var/lib/aios-gitops/model-api-staging/baseline/current.json
|
||||
Environment=AIOS_GITOPS_WRITES_ENABLED=false
|
||||
Environment=AIOS_GITOPS_DURABLE_JOB_EXECUTION_ENABLED=false
|
||||
Environment=AIOS_GITOPS_JOB_CONTROLLER_ENABLED=false
|
||||
Environment=AIOS_GITOPS_WORKSPACE_ROLE=runtime-anchor
|
||||
Environment=AIOS_GITOPS_RUNTIME_OID=@SOURCE_OID@
|
||||
Environment=AIOS_GITOPS_ARTIFACT_SHA256=@ARTIFACT_SHA256@
|
||||
Environment=AIOS_GITOPS_DEPLOYMENT_STATE=STAGING
|
||||
Environment=AIOS_GITOPS_MODEL_API_SERVICE=aios-gitops-model-api-v2r2c1-staging.service
|
||||
Environment=AIOS_SILENT_RELEASE_EXECUTION_ENABLED=false
|
||||
Environment=AIOS_SILENT_RELEASE_STATE_ROOT=/var/lib/aios-gitops/model-api-staging/silent-release
|
||||
Environment=AIOS_GITOPS_GITEA_API_URL=https://g.cnnetmkt.top/git/api/v1
|
||||
Environment=AIOS_GITOPS_GITEA_REPOSITORY=aios/aios
|
||||
Environment=AIOS_GITOPS_GITEA_REMOTE=gitea-http
|
||||
Environment=AIOS_GITOPS_GITEA_TOKEN_FILE=/run/credentials/aios-gitops-model-api-v2r2c1-staging.service/gitea_token
|
||||
Environment=GIT_ASKPASS=/var/lib/aios-gitops/bridge-v2-staging/bridge-v2-askpass.sh
|
||||
Environment=GIT_ASKPASS_REQUIRE=force
|
||||
Environment=GIT_TERMINAL_PROMPT=0
|
||||
Environment=GITEA_MACHINE_ACTOR=aios-autonomy-agent
|
||||
Environment=CREDENTIAL_FILE=/run/credentials/aios-gitops-model-api-v2r2c1-staging.service/gitea_token
|
||||
Environment=AIOS_GITOPS_GITEA_TOKEN_LINE=1
|
||||
LoadCredential=gitea_token:/run/credentials/aios-governance-executor.service/gitea-governance-executor-token
|
||||
Environment=AIOS_BRIDGE_V2_URL=http://127.0.0.1:18892
|
||||
Environment=AIOS_GITOPS_HOST=127.0.0.1
|
||||
Environment=AIOS_GITOPS_PORT=18893
|
||||
Environment=PYTHONPATH=@RUNTIME_ROOT@:@RUNTIME_ROOT@/app:@RUNTIME_ROOT@/runtime-agent-os
|
||||
ExecStart=/usr/bin/python3 @RUNTIME_ROOT@/app/aios_model_api_staging.py
|
||||
Restart=on-failure
|
||||
RestartSec=2
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectHome=true
|
||||
ProtectSystem=strict
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
ProtectControlGroups=true
|
||||
LockPersonality=true
|
||||
RestrictSUIDSGID=true
|
||||
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
||||
ReadOnlyPaths=@RUNTIME_ROOT@ /data/aios-gitops/repo.git /var/lib/aios-gitops-runtime-anchor/baseline
|
||||
ReadWritePaths=/var/lib/aios-gitops/model-api-staging
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -1,5 +0,0 @@
|
||||
AIOS governed Action loop smoke
|
||||
task=fix-action-contracts-20260825-1407
|
||||
generation=5
|
||||
expected_parent=f104e1244fcbc36d1debf1aa0c6720f734ea04cf
|
||||
purpose=verify read-lease-commit-idempotency-cas
|
||||
@@ -1,6 +1,20 @@
|
||||
# Merge this fragment into docs/gitops/openapi-chatgpt-actions.yaml.
|
||||
components:
|
||||
schemas:
|
||||
WriterLeaseRequestV2:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [schema, task_id, repository, branch_mode, base_oid, expected_branch_oid, target_branch, generation, lease_seconds]
|
||||
properties:
|
||||
schema: {type: string, const: aios.task-writer-lease.v2}
|
||||
task_id: {type: string}
|
||||
repository: {type: string, const: aios/aios}
|
||||
branch_mode: {type: string, const: CONTINUE_EXISTING}
|
||||
base_oid: {type: string, pattern: '^[0-9a-f]{40}$'}
|
||||
expected_branch_oid: {type: string, pattern: '^[0-9a-f]{40}$'}
|
||||
target_branch: {type: string, pattern: '^agent/'}
|
||||
generation: {type: integer, minimum: 1}
|
||||
lease_seconds: {type: integer, minimum: 1, maximum: 86400}
|
||||
AuthorizedTaskWriterProvisionRequest:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
@@ -90,6 +104,20 @@ components:
|
||||
- production_marker_write
|
||||
- history_rewrite
|
||||
|
||||
ControlPlaneSnapshot:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [version, runtime, repository, production, task, capabilities, credential_broker, secret_material_exposed]
|
||||
properties:
|
||||
version: {type: object}
|
||||
runtime: {type: object}
|
||||
repository: {type: object}
|
||||
production: {type: object}
|
||||
task: {type: object}
|
||||
capabilities: {type: object}
|
||||
credential_broker: {type: object}
|
||||
secret_material_exposed: {type: boolean, const: false}
|
||||
|
||||
paths:
|
||||
/api/task-writer/provision-authorized:
|
||||
post:
|
||||
@@ -119,3 +147,10 @@ paths:
|
||||
description: Base drift, branch conflict, or idempotency scope conflict
|
||||
'503':
|
||||
description: Signer, validator, provisioner, or attestation unavailable
|
||||
|
||||
/v2/control-plane-snapshot:
|
||||
get:
|
||||
operationId: getControlPlaneSnapshot
|
||||
responses:
|
||||
'200':
|
||||
description: Non-sensitive control-plane snapshot
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: AIOS GitOps Controlled Access API
|
||||
version: V2R2C1-chatgpt-actions-28ops
|
||||
version: V1R1C0-chatgpt-actions
|
||||
description: Controlled ChatGPT Actions API for AIOS online GitOps baseline. Read endpoints are public. Write endpoints require Bearer token and create Git commits on non-main branches.
|
||||
servers:
|
||||
- url: https://cnnetmkt.top
|
||||
@@ -241,102 +241,6 @@ components:
|
||||
properties:
|
||||
candidate_id: {type: string}
|
||||
paths:
|
||||
/readRepositoryFile:
|
||||
post:
|
||||
operationId: readRepositoryFile
|
||||
summary: Read one bounded file from an approved repository ref
|
||||
security: [{bearerAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [repository, ref, path, max_bytes]
|
||||
properties:
|
||||
repository: {type: string, enum: [aios/aios]}
|
||||
ref: {type: string, description: agent branch, main, V2R2C1, or full commit OID}
|
||||
path: {type: string, minLength: 1, maxLength: 512}
|
||||
max_bytes: {type: integer, minimum: 1, maximum: 262144}
|
||||
responses:
|
||||
'200': {description: Bounded read-only source content}
|
||||
'400': {description: Invalid repository, ref, path, or size}
|
||||
'404': {description: Ref or file not found}
|
||||
x-openai-isConsequential: false
|
||||
/acquireWriterLease:
|
||||
post:
|
||||
operationId: acquireWriterLease
|
||||
summary: Acquire a short-lived generation-scoped writer lease
|
||||
security: [{bearerAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [schema, task_id, repository, branch_mode, base_oid, expected_branch_oid, target_branch, generation, lease_seconds]
|
||||
properties:
|
||||
schema: {type: string, enum: [aios.task-writer-lease.v2]}
|
||||
task_id: {type: string, minLength: 1, maxLength: 200}
|
||||
repository: {type: string, enum: [aios/aios]}
|
||||
branch_mode: {type: string, enum: [CONTINUE_EXISTING]}
|
||||
base_oid: {type: string, pattern: '^[0-9a-f]{40}$'}
|
||||
expected_branch_oid: {type: string, pattern: '^[0-9a-f]{40}$'}
|
||||
target_branch: {type: string, pattern: '^agent/[A-Za-z0-9._/-]+$'}
|
||||
generation: {type: integer, minimum: 1}
|
||||
lease_seconds: {type: integer, minimum: 1, maximum: 3600}
|
||||
responses:
|
||||
'200': {description: Acquired or idempotently replayed scoped lease}
|
||||
'409': {description: Binding, stale, expired, or already-used lease}
|
||||
'423': {description: Governed writes disabled}
|
||||
x-openai-isConsequential: true
|
||||
/v2/commit-files:
|
||||
post:
|
||||
operationId: commitFilesGoverned
|
||||
summary: Submit one atomic governed commit containing multiple files
|
||||
security: [{bearerAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- task_id
|
||||
- repository
|
||||
- expected_branch_oid
|
||||
- target_branch
|
||||
- generation
|
||||
- idempotency_key
|
||||
- files
|
||||
- message
|
||||
properties:
|
||||
task_id: {type: string}
|
||||
repository: {type: string, example: aios/aios}
|
||||
expected_branch_oid: {type: string, pattern: '^[0-9a-f]{40}$'}
|
||||
target_branch: {type: string, pattern: '^agent/[A-Za-z0-9._/-]+$'}
|
||||
generation: {type: integer, minimum: 1}
|
||||
idempotency_key: {type: string, minLength: 8, maxLength: 128, pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$'}
|
||||
files:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 50
|
||||
items:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [path, content_base64]
|
||||
properties:
|
||||
path: {type: string, minLength: 1, maxLength: 512}
|
||||
content_base64: {type: string}
|
||||
message: {type: string, minLength: 1, maxLength: 200}
|
||||
responses:
|
||||
'200': {description: Governed commit job and verified branch result}
|
||||
'400': {description: Contract or policy rejection}
|
||||
'409': {description: Branch CAS or idempotency conflict}
|
||||
x-openai-isConsequential: true
|
||||
/createReleaseIntent:
|
||||
post:
|
||||
operationId: createReleaseIntent
|
||||
@@ -416,6 +320,20 @@ paths:
|
||||
'403': {description: Signature, key, expiry, or revocation failure}
|
||||
'409': {description: Conflicting release plan}
|
||||
x-openai-isConsequential: true
|
||||
/submitSignedApproval:
|
||||
post:
|
||||
operationId: submitSignedApproval
|
||||
summary: Alias for immutable signed owner approval submission
|
||||
security: [{bearerAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/SignedReleasePlanApproval'}
|
||||
responses:
|
||||
'200': {description: Signature verified and approval stored}
|
||||
'403': {description: Production approval backend unavailable or signature invalid}
|
||||
x-openai-isConsequential: true
|
||||
/startDeployment:
|
||||
post:
|
||||
operationId: startDeployment
|
||||
@@ -479,6 +397,17 @@ paths:
|
||||
operationId: listPatches
|
||||
summary: List patch records
|
||||
responses: {'200': {description: OK}}
|
||||
post:
|
||||
operationId: createPatch
|
||||
summary: Create a patch branch and commit metadata
|
||||
security: [{bearerAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/PatchRequest'}
|
||||
responses: {'200': {description: Patch branch committed}, '401': {description: Unauthorized}, '403': {description: Forbidden}}
|
||||
x-openai-isConsequential: true
|
||||
/api/model:
|
||||
get:
|
||||
operationId: readModelRegistry
|
||||
@@ -500,6 +429,61 @@ paths:
|
||||
operationId: getRuntimeStatus
|
||||
summary: Read runtime status
|
||||
responses: {'200': {description: OK}}
|
||||
/api/branch:
|
||||
post:
|
||||
operationId: createBranch
|
||||
summary: Create a non-main branch and commit branch metadata
|
||||
security: [{bearerAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/BranchRequest'}
|
||||
responses: {'200': {description: Branch created}, '401': {description: Unauthorized}, '403': {description: Forbidden}}
|
||||
x-openai-isConsequential: true
|
||||
/api/file:
|
||||
post:
|
||||
operationId: commitFile
|
||||
summary: Write a file and create a Git commit on a non-main branch
|
||||
security: [{bearerAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/FileCommitRequest'}
|
||||
responses: {'200': {description: File committed}, '400': {description: Secret rejected or invalid path}, '401': {description: Unauthorized}}
|
||||
x-openai-isConsequential: true
|
||||
/api/commit-file:
|
||||
post:
|
||||
operationId: commitFileAtomic
|
||||
summary: Atomically write one allowlisted file, commit, push, and verify using Token Policy V2
|
||||
security: [{bearerAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/AtomicFileCommitRequest'}
|
||||
responses:
|
||||
'200': {description: Completed or idempotently replayed}
|
||||
'400': {description: Invalid canonical request}
|
||||
'401': {description: Missing, invalid, expired, or revoked Token Policy V2 grant}
|
||||
'403': {description: Audience, source, branch, operation, path, or policy denied}
|
||||
'409': {description: Idempotency conflict or manual review required}
|
||||
'413': {description: Request too large}
|
||||
'503': {description: Push or remote verification unavailable; recoverable}
|
||||
x-openai-isConsequential: true
|
||||
/api/commit:
|
||||
post:
|
||||
operationId: commitChanges
|
||||
summary: Commit existing workspace changes on a non-main branch
|
||||
security: [{bearerAuth: []}]
|
||||
requestBody:
|
||||
required: false
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/CommitRequest'}
|
||||
responses: {'200': {description: Commit result}, '401': {description: Unauthorized}}
|
||||
x-openai-isConsequential: true
|
||||
/api/tag-publication-status:
|
||||
get:
|
||||
operationId: getTagPublicationStatus
|
||||
@@ -583,3 +567,53 @@ paths:
|
||||
'200': {description: Safe GitOps plan}
|
||||
'401': {description: Unauthorized}
|
||||
x-openai-isConsequential: true
|
||||
/api/v2/governed-capabilities:
|
||||
get:
|
||||
operationId: getGovernedWriteCapabilities
|
||||
responses: {'200': {description: Governed write capabilities with legacy writes disabled}}
|
||||
/api/v2/governed-task:
|
||||
post:
|
||||
operationId: createGovernedTask
|
||||
requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: false, required: [task_id, repository, base_oid, target_branch, risk, description, idempotency_key], properties: {task_id: {type: string}, repository: {type: string, const: aios/aios}, base_oid: {type: string, pattern: '^[0-9a-f]{40}$'}, target_branch: {type: string, pattern: '^agent/'}, risk: {type: string}, description: {type: string}, idempotency_key: {type: string}}}}}}
|
||||
responses: {'200': {description: Exact governed task binding}}
|
||||
x-openai-isConsequential: true
|
||||
/api/v2/writer-lease:
|
||||
post:
|
||||
operationId: acquireWriterLease
|
||||
requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: false, required: [schema, task_id, repository, branch_mode, base_oid, expected_branch_oid, target_branch, generation, lease_seconds], properties: {schema: {type: string}, task_id: {type: string}, repository: {type: string, const: aios/aios}, branch_mode: {type: string, enum: [CREATE_NEW, CONTINUE_EXISTING]}, base_oid: {type: string, pattern: '^[0-9a-f]{40}$'}, expected_branch_oid: {type: string, pattern: '^[0-9a-f]{40}$'}, target_branch: {type: string, pattern: '^agent/'}, generation: {type: integer, minimum: 1}, lease_seconds: {type: integer, minimum: 1, maximum: 86400}}}}}}
|
||||
responses: {'200': {description: Detached CONTINUE_EXISTING lease}}
|
||||
x-openai-isConsequential: true
|
||||
/api/v2/commit-file:
|
||||
post:
|
||||
operationId: commitFileGoverned
|
||||
requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: false, required: [task_id, repository, expected_branch_oid, target_branch, generation, idempotency_key, path, content_base64, message], properties: {task_id: {type: string}, repository: {type: string, const: aios/aios}, expected_branch_oid: {type: string, pattern: '^[0-9a-f]{40}$'}, target_branch: {type: string, pattern: '^agent/'}, generation: {type: integer, minimum: 1}, idempotency_key: {type: string}, path: {type: string}, content_base64: {type: string}, message: {type: string}}}}}}
|
||||
responses: {'202': {description: Durable governed Job}}
|
||||
x-openai-isConsequential: true
|
||||
/api/v2/commit-files:
|
||||
post:
|
||||
operationId: commitFilesGoverned
|
||||
requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: false, required: [task_id, repository, expected_branch_oid, target_branch, generation, idempotency_key, files, message], properties: {task_id: {type: string}, repository: {type: string, const: aios/aios}, expected_branch_oid: {type: string, pattern: '^[0-9a-f]{40}$'}, target_branch: {type: string, pattern: '^agent/'}, generation: {type: integer, minimum: 1}, idempotency_key: {type: string}, files: {type: object, additionalProperties: {type: string}}, message: {type: string}}}}}}
|
||||
responses: {'202': {description: One atomic multi-file governed Job}}
|
||||
x-openai-isConsequential: true
|
||||
/api/v2/job:
|
||||
post:
|
||||
operationId: getGitOpsJob
|
||||
requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: false, required: [job_id], properties: {job_id: {type: string}}}}}}
|
||||
responses: {'200': {description: Non-sensitive Job metadata}}
|
||||
/api/v2/job/resume:
|
||||
post:
|
||||
operationId: resumeGitOpsJob
|
||||
requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: false, required: [job_id, expected_revision], properties: {job_id: {type: string}, expected_revision: {type: integer, minimum: 0}}}}}}
|
||||
responses: {'202': {description: Revision-CAS resume}}
|
||||
x-openai-isConsequential: true
|
||||
/api/v2/job/reconcile:
|
||||
post:
|
||||
operationId: reconcileGitOpsJob
|
||||
requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: false, required: [job_id, expected_revision], properties: {job_id: {type: string}, expected_revision: {type: integer, minimum: 0}}}}}}
|
||||
responses: {'202': {description: Observation-first reconciliation}}
|
||||
x-openai-isConsequential: true
|
||||
|
||||
/v2/control-plane-snapshot:
|
||||
get:
|
||||
operationId: getControlPlaneSnapshot
|
||||
responses: {'200': {description: Non-sensitive control-plane snapshot}}
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
umask 027
|
||||
|
||||
ROOT="/data/aios-gitops"
|
||||
NGINX_SITE="/etc/nginx/sites-enabled/aios-user-portal.conf"
|
||||
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
BACKUP_DIR="$ROOT/backups/action-surface-final-$STAMP"
|
||||
LOG="$ROOT/logs/action-surface-final-$STAMP.log"
|
||||
|
||||
mkdir -p "$BACKUP_DIR" "$ROOT/logs"
|
||||
exec > >(tee -a "$LOG") 2>&1
|
||||
|
||||
sudo cp -a "$NGINX_SITE" "$BACKUP_DIR/aios-user-portal.conf"
|
||||
SITE_BACKUP="$BACKUP_DIR/aios-user-portal.conf"
|
||||
|
||||
python3 - "$SITE_BACKUP" "$BACKUP_DIR/aios-user-portal.conf.next" <<'PY'
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
source, output = map(Path, sys.argv[1:])
|
||||
text = source.read_text(encoding="utf-8")
|
||||
bridge_marker = " # AIOS external Action Bridge v2 staging route"
|
||||
bridge_block = r''' # AIOS external Action Bridge v2 staging route
|
||||
# The published Action schema uses the site-root /v2 paths and must reach
|
||||
# the non-production Bridge v2 listener, never the production 18920 unit.
|
||||
location ^~ /v2/ {
|
||||
proxy_pass http://127.0.0.1:18892;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
proxy_set_header X-AIOS-Token $http_x_aios_token;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 1100k;
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_send_timeout 120s;
|
||||
proxy_read_timeout 120s;
|
||||
}
|
||||
'''
|
||||
if bridge_marker not in text:
|
||||
needle = " # BEGIN AIOS CHATGPT AUTONOMOUS RELEASE TASK ROUTE"
|
||||
if text.count(needle) != 1:
|
||||
raise SystemExit("expected exactly one legacy Action route marker")
|
||||
text = text.replace(needle, bridge_block + "\n" + needle, 1)
|
||||
elif "location ^~ /v2/" not in text or "proxy_pass http://127.0.0.1:18892;" not in text:
|
||||
raise SystemExit("staging Bridge v2 route marker exists but route is incomplete")
|
||||
|
||||
marker = " # AIOS external Action governed-read ownership"
|
||||
block = r''' # AIOS external Action governed-read ownership
|
||||
# These reads are owned by the authenticated 18890 facade, not the 18893 model API.
|
||||
location = /api/governed-write-capabilities {
|
||||
proxy_pass http://127.0.0.1:18890/api/governed-write-capabilities;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
proxy_set_header X-AIOS-Token $http_x_aios_token;
|
||||
}
|
||||
location = /api/control-plane-snapshot {
|
||||
proxy_pass http://127.0.0.1:18890/api/control-plane-snapshot;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
proxy_set_header X-AIOS-Token $http_x_aios_token;
|
||||
}
|
||||
location = /api/online-agent-task {
|
||||
proxy_pass http://127.0.0.1:18890/api/online-agent-task;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
proxy_set_header X-AIOS-Token $http_x_aios_token;
|
||||
}
|
||||
location = /api/online-agent-task-events {
|
||||
proxy_pass http://127.0.0.1:18890/api/online-agent-task-events;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
proxy_set_header X-AIOS-Token $http_x_aios_token;
|
||||
}
|
||||
'''
|
||||
needle = " location /api/ {"
|
||||
if text.count(needle) != 1:
|
||||
raise SystemExit("expected exactly one generic /api/ location")
|
||||
if marker not in text:
|
||||
text = text.replace(needle, block + "\n" + needle, 1)
|
||||
output.write_text(text, encoding="utf-8")
|
||||
PY
|
||||
|
||||
sudo cp "$BACKUP_DIR/aios-user-portal.conf.next" "$NGINX_SITE"
|
||||
sudo nginx -t
|
||||
sudo systemctl reload nginx
|
||||
|
||||
printf 'ACTION_SURFACE_FINAL_OK backup=%s log=%s\n' "$BACKUP_DIR" "$LOG"
|
||||
@@ -1,4 +0,0 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
python_files = test_*.py
|
||||
addopts = -ra --import-mode=importlib
|
||||
@@ -1,21 +0,0 @@
|
||||
"""Canonical AIOS release-version parser shared by runtime and release tools."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
|
||||
# The suffix preserves already-supported annotated release names while the
|
||||
# canonical VnRnCn namespace remains accepted exactly.
|
||||
RELEASE_VERSION_PATTERN = r"^V[0-9]+R[0-9]+C[0-9]+(?:-[A-Za-z0-9_.-]+)?$"
|
||||
RELEASE_VERSION_RE = re.compile(RELEASE_VERSION_PATTERN)
|
||||
|
||||
|
||||
def parse_release_version(version: object) -> str:
|
||||
value = str(version or "").strip()
|
||||
if not RELEASE_VERSION_RE.fullmatch(value):
|
||||
raise ValueError("invalid release version")
|
||||
return value
|
||||
|
||||
|
||||
def validate_release_version(version: object) -> str:
|
||||
return parse_release_version(version)
|
||||
@@ -1,243 +0,0 @@
|
||||
{
|
||||
"authority_proof": {
|
||||
"branch_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"commit_visible": true,
|
||||
"main_oid": "2e8fa22989808a448065d1d76b5b18948774a637",
|
||||
"v2r2c1_tag_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad"
|
||||
},
|
||||
"baseline_authority": {
|
||||
"artifact_sha256": "492338b895b152a55015fd92ea1d9dba2314894ab00c0ba219a78f3cef544b8a",
|
||||
"authority_sha256": "d8e23bad49bdb3e4192ba708c3dfe7fc5b7cdc6a513c2f87acd6412a51867231",
|
||||
"current_baseline": "V2R2C1",
|
||||
"raw_byte_sidecar_verification": "PASS",
|
||||
"target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad"
|
||||
},
|
||||
"control_plane_source_oid": "b781129bd5a8b53c05ab648361424d2800166ee4",
|
||||
"diff_stat": "active-runtime/app/aios_authority_git_executor.py | 24 +\n active-runtime/app/aios_chatgpt_actions_api.py | 48 +-\n active-runtime/app/aios_chatgpt_bridge_v2.py | 167 ++++\n .../app/aios_chatgpt_bridge_v2_server.py | 431 +++++++++\n active-runtime/app/aios_continuation_executor.py | 594 ++++++++++++\n active-runtime/app/aios_continuation_lease.py | 6 +\n active-runtime/app/aios_control_plane_snapshot.py | 26 +\n active-runtime/app/aios_credential_broker.py | 78 ++\n active-runtime/app/aios_gitea_publisher.py | 93 ++\n active-runtime/app/aios_gitops_job_controller.py | 16 +-\n .../app/aios_gitops_reconciliation_core.py | 80 ++\n active-runtime/app/aios_governed_policy.py | 59 ++\n active-runtime/app/aios_governed_task_bootstrap.py | 84 ++\n active-runtime/app/aios_model_api_staging.py | 1022 ++++++++++++++++++++\n .../app/authorized_task_writer_provisioning.py | 4 +-\n active-runtime/app/baseline_authority.py | 84 ++\n active-runtime/app/governed_production_release.py | 568 +++++++++++\n active-runtime/app/v2r2c1_production_adapter.py | 135 +++\n .../systemd/aios-chatgpt-bridge-v2-staging.service | 23 +\n .../aios-gitops-model-api-v2r2c1-staging.service | 51 +\n ...09-bridge-v2.1-durable-reconciliation-design.md | 15 +\n ...t-bridge-v2-control-plane-convergence-design.md | 150 +++\n pytest.ini | 4 +\n scripts/build_v2r2c1_model_api_staging.py | 145 +++\n .../aios_release_controller/manifest.py | 4 +-\n .../test_v2r1c6_release_consistency.py | 4 +-\n .../aios_v2_candidate/test_v2r1c6_release_ready.py | 16 +-\n tests/conftest.py | 65 ++\n tests/test_bridge_v2_governed_http_bootstrap.py | 90 ++\n tests/test_governed_local_writer.py | 6 +-\n tests/test_model_api_immutable_staging.py | 35 +\n 31 files changed, 4108 insertions(+), 19 deletions(-)",
|
||||
"evidence_closure_oid": "a8b906d1bc24088c19647e98de6a679268f6d0a2",
|
||||
"forbidden_operations": [
|
||||
"direct_main_push",
|
||||
"main_merge_without_owner_approval",
|
||||
"force_push",
|
||||
"tag_mutation",
|
||||
"baseline_mutation",
|
||||
"registry_mutation",
|
||||
"production_restart",
|
||||
"production_cutover",
|
||||
"live_model_api_cutover",
|
||||
"history_rewrite",
|
||||
"secret_commit"
|
||||
],
|
||||
"governance": {
|
||||
"baseline_modified": false,
|
||||
"direct_main_push": false,
|
||||
"force_push_used": false,
|
||||
"history_rewritten": false,
|
||||
"live_model_api_cutover": false,
|
||||
"main_merged": false,
|
||||
"owner_approval_respected": true,
|
||||
"production_changed": false,
|
||||
"production_restarted": false,
|
||||
"registry_modified": false,
|
||||
"secrets_committed": false,
|
||||
"tag_rewritten": false
|
||||
},
|
||||
"included_path_count": 31,
|
||||
"integration_branch": "agent/v2r2c1-post-release-mainline-convergence-20260809",
|
||||
"integration_head_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"logical_commits": [
|
||||
{
|
||||
"message": "feat(v2r2c1): converge durable control-plane core",
|
||||
"oid": "40b685d1c70c767c7a79a2b184348e58e3e319ae",
|
||||
"parent_oid": "2e8fa22989808a448065d1d76b5b18948774a637"
|
||||
},
|
||||
{
|
||||
"message": "docs(v2r2c1): converge durable runtime and design sources",
|
||||
"oid": "5f616311bab38b0dac296ed8b0e69660e031a20e",
|
||||
"parent_oid": "40b685d1c70c767c7a79a2b184348e58e3e319ae"
|
||||
},
|
||||
{
|
||||
"message": "feat(v2r2c1): integrate governed release overlay",
|
||||
"oid": "57780e316e320a5128cc2c9f12adbb19ae57aef5",
|
||||
"parent_oid": "5f616311bab38b0dac296ed8b0e69660e031a20e"
|
||||
},
|
||||
{
|
||||
"message": "feat(v2r2c1): wire governed release operations into durable bridge",
|
||||
"oid": "e41b8d323a3e7a40440f5d32221f524074bea5fe",
|
||||
"parent_oid": "57780e316e320a5128cc2c9f12adbb19ae57aef5"
|
||||
},
|
||||
{
|
||||
"message": "test: repair canonical pytest repository entrypoint",
|
||||
"oid": "b20cb8130e4c68267d5d85b02eed51cb8d4f41c0",
|
||||
"parent_oid": "e41b8d323a3e7a40440f5d32221f524074bea5fe"
|
||||
},
|
||||
{
|
||||
"message": "test: make whole-suite collection deterministic",
|
||||
"oid": "c6a1693efaede9dace9b929d884a09e162a02c89",
|
||||
"parent_oid": "b20cb8130e4c68267d5d85b02eed51cb8d4f41c0"
|
||||
},
|
||||
{
|
||||
"message": "test: preserve legacy suite imports under canonical collection",
|
||||
"oid": "91f2ea0591787d3dbf8c2e27ab0460629d86900e",
|
||||
"parent_oid": "c6a1693efaede9dace9b929d884a09e162a02c89"
|
||||
},
|
||||
{
|
||||
"message": "test: expose repository test helpers to canonical collection",
|
||||
"oid": "85897d3f6d708271dff16767265f9d14b2f29801",
|
||||
"parent_oid": "91f2ea0591787d3dbf8c2e27ab0460629d86900e"
|
||||
},
|
||||
{
|
||||
"message": "fix(v2r2c1): close slash-branch and suite contract regressions",
|
||||
"oid": "f1110d24f30d8441f2df04e0774ee230b95c2e02",
|
||||
"parent_oid": "85897d3f6d708271dff16767265f9d14b2f29801"
|
||||
},
|
||||
{
|
||||
"message": "test: align writer regression with durable idempotent replay",
|
||||
"oid": "c10d2a5dfcc394dde7a7022952d7b423725747a3",
|
||||
"parent_oid": "f1110d24f30d8441f2df04e0774ee230b95c2e02"
|
||||
},
|
||||
{
|
||||
"message": "feat(v2r2c1): source baseline authority for model-api staging",
|
||||
"oid": "f969aedaf61501a866435c712be01ff2cfe43fb1",
|
||||
"parent_oid": "c10d2a5dfcc394dde7a7022952d7b423725747a3"
|
||||
},
|
||||
{
|
||||
"message": "feat(v2r2c1): add immutable model api staging runtime",
|
||||
"oid": "4ab70bfdb4d34aa9d1dabc4230a3367eaa93cc9b",
|
||||
"parent_oid": "f969aedaf61501a866435c712be01ff2cfe43fb1"
|
||||
},
|
||||
{
|
||||
"message": "fix(v2r2c1): avoid builder secret-scan false positives",
|
||||
"oid": "7c4e86bfc1f39e643e672968d1fdedbd72ace56d",
|
||||
"parent_oid": "4ab70bfdb4d34aa9d1dabc4230a3367eaa93cc9b"
|
||||
},
|
||||
{
|
||||
"message": "fix(v2r2c1): isolate model api staging port",
|
||||
"oid": "7564363a30bfa7fa81ac5c7c545ec704984ec543",
|
||||
"parent_oid": "7c4e86bfc1f39e643e672968d1fdedbd72ace56d"
|
||||
},
|
||||
{
|
||||
"message": "fix(v2r2c1): bind baseline authority and openapi staging path",
|
||||
"oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"parent_oid": "7564363a30bfa7fa81ac5c7c545ec704984ec543"
|
||||
}
|
||||
],
|
||||
"main_base_oid": "2e8fa22989808a448065d1d76b5b18948774a637",
|
||||
"mandatory_gates": {
|
||||
"baseline_registry_readback_staging_pass": true,
|
||||
"durable_source_path_manifest_complete": true,
|
||||
"existing_v2r2c1_suite_pass": true,
|
||||
"governed_release_suite_pass": true,
|
||||
"integration_authority_git_api_equal": true,
|
||||
"integration_branch_governed": true,
|
||||
"logical_slice_commits_remote_verified": true,
|
||||
"main_base_exact_before_branch_create": true,
|
||||
"model_api_immutable_runtime_staging_pass": true,
|
||||
"owner_merge_request_generated_execute_false": true,
|
||||
"production_unchanged": true,
|
||||
"pytest_collection_entrypoints_fixed": true,
|
||||
"pytest_tests_results_recorded": true
|
||||
},
|
||||
"model_api_staging": {
|
||||
"artifact_sha256": "492338b895b152a55015fd92ea1d9dba2314894ab00c0ba219a78f3cef544b8a",
|
||||
"baseline": {
|
||||
"authority_sha256": "d8e23bad49bdb3e4192ba708c3dfe7fc5b7cdc6a513c2f87acd6412a51867231",
|
||||
"current_baseline": "V2R2C1",
|
||||
"deployment_state": "ACTIVE",
|
||||
"evidence_closure_oid": "a8b906d1bc24088c19647e98de6a679268f6d0a2",
|
||||
"generation": 4,
|
||||
"previous_baseline": "V2R1C7",
|
||||
"production_deployed": true,
|
||||
"status": "PRODUCTION_DEPLOYED",
|
||||
"tag_oid": "07fc2746b688f5f243f29b39de39f32edc3dd9d2",
|
||||
"target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad"
|
||||
},
|
||||
"baseline_status": 200,
|
||||
"deployment_state": "STAGING",
|
||||
"health": {
|
||||
"artifact_sha256": "492338b895b152a55015fd92ea1d9dba2314894ab00c0ba219a78f3cef544b8a",
|
||||
"commit_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"deployment_state": "STAGING",
|
||||
"governed_release_routing": "bridge-v2",
|
||||
"legacy_global_writes_enabled": false,
|
||||
"production_deployed": false,
|
||||
"runtime_mode": "IMMUTABLE_STAGING",
|
||||
"status": "ok",
|
||||
"version": "V2R2C1"
|
||||
},
|
||||
"health_status": 200,
|
||||
"legacy_write_probe": "423_BLOCKED",
|
||||
"port": 18893,
|
||||
"restart_acceptance": "PASS",
|
||||
"runtime_root": "/opt/aios/gitops-model-api/2c6293160ed567a2098715edbb296741577c5bff/runtime",
|
||||
"source_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"systemd": "MainPID=788782\nExecStart={ path=/usr/bin/python3 ; argv[]=/usr/bin/python3 /opt/aios/gitops-model-api/2c6293160ed567a2098715edbb296741577c5bff/runtime/app/aios_model_api_staging.py ; ignore_errors=no ; start_time=[Sun 2026-08-09 19:11:19 CST] ; stop_time=[n/a] ; pid=788782 ; code=(null) ; status=0/0 }\nActiveState=active\nSubState=running",
|
||||
"unit": "aios-gitops-model-api-v2r2c1-staging.service",
|
||||
"versions": {
|
||||
"authoritative_head_oid": "2e8fa22989808a448065d1d76b5b18948774a637",
|
||||
"baseline_generation": 4,
|
||||
"baseline_sha256": "d8e23bad49bdb3e4192ba708c3dfe7fc5b7cdc6a513c2f87acd6412a51867231",
|
||||
"baseline_version": "V2R2C1",
|
||||
"query_error": null
|
||||
},
|
||||
"versions_status": 200
|
||||
},
|
||||
"owner_merge_request": {
|
||||
"control_plane_source_oid": "b781129bd5a8b53c05ab648361424d2800166ee4",
|
||||
"execute": false,
|
||||
"integration_head_oid": "b2cf510e11b712bb99f20ded81459b6524257394",
|
||||
"main_expected_old_oid": "2e8fa22989808a448065d1d76b5b18948774a637",
|
||||
"release_target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"report_commit_oid": "b2cf510e11b712bb99f20ded81459b6524257394",
|
||||
"status": "OWNER_APPROVAL_REQUIRED"
|
||||
},
|
||||
"placeholder_fields": [],
|
||||
"production": {
|
||||
"baseline_mutation": false,
|
||||
"health": {
|
||||
"artifact_sha256": "ab4ae257346c82863f05abf5e309381a1c86612957608c3a4f4ab5cc9233f052",
|
||||
"commit_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"deployment_state": "ACTIVE",
|
||||
"health_timestamp": "2026-08-09T11:21:16.872581+00:00",
|
||||
"production_deployed": true,
|
||||
"status": "ok",
|
||||
"version": "V2R2C1"
|
||||
},
|
||||
"health_status": 200,
|
||||
"live_model_api_show": "MainPID=2816107\nActiveState=active\nSubState=running",
|
||||
"live_model_api_unchanged": true,
|
||||
"production_cutover": false,
|
||||
"production_restart": false,
|
||||
"registry_mutation": false,
|
||||
"shadow_service_unchanged": true,
|
||||
"shadow_show": "MainPID=1505658\nActiveState=active\nSubState=running",
|
||||
"tag_mutation": false
|
||||
},
|
||||
"release_target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"remote_proof": {
|
||||
"api_branch_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"api_verification": "paginated_exact_name",
|
||||
"commit_visible": true,
|
||||
"git_remote_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"main_api_oid": "2e8fa22989808a448065d1d76b5b18948774a637",
|
||||
"main_git_oid": "2e8fa22989808a448065d1d76b5b18948774a637"
|
||||
},
|
||||
"report_commit_parent_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"repository": "aios/aios",
|
||||
"schema": "aios.v2r2c1.post-release-mainline-convergence.acceptance.v1",
|
||||
"status": "V2R2C1_MAINLINE_CONVERGENCE_READY_FOR_OWNER_MERGE",
|
||||
"success_status": "V2R2C1_MAINLINE_CONVERGENCE_READY_FOR_OWNER_MERGE",
|
||||
"task_id": "TASK-P0-V2R2C1-POST-RELEASE-MAINLINE-CONVERGENCE-20260809",
|
||||
"tests": {
|
||||
"collection": "PASS",
|
||||
"command": "pytest tests",
|
||||
"failed": 0,
|
||||
"passed": 709,
|
||||
"skipped": 2,
|
||||
"skipped_tests": [
|
||||
"tests/test_gitea_tag_publication_live.py (live opt-in)",
|
||||
"tests/test_signer_contract_compatibility.py (live integration opt-in)"
|
||||
],
|
||||
"subtests": 154
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
# V2R2C1 post-release mainline convergence diff summary
|
||||
|
||||
- task: `TASK-P0-V2R2C1-POST-RELEASE-MAINLINE-CONVERGENCE-20260809`
|
||||
- repository: `aios/aios`
|
||||
- main base: `2e8fa22989808a448065d1d76b5b18948774a637`
|
||||
- release target: `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`
|
||||
- control-plane source: `b781129bd5a8b53c05ab648361424d2800166ee4`
|
||||
- implementation integration head before this report commit: `2c6293160ed567a2098715edbb296741577c5bff`
|
||||
- branch: `agent/v2r2c1-post-release-mainline-convergence-20260809`
|
||||
|
||||
## Logical governed commits
|
||||
|
||||
| OID | Parent | Message |
|
||||
|---|---|---|
|
||||
| `40b685d1c70c767c7a79a2b184348e58e3e319ae` | `2e8fa22989808a448065d1d76b5b18948774a637` | feat(v2r2c1): converge durable control-plane core |
|
||||
| `5f616311bab38b0dac296ed8b0e69660e031a20e` | `40b685d1c70c767c7a79a2b184348e58e3e319ae` | docs(v2r2c1): converge durable runtime and design sources |
|
||||
| `57780e316e320a5128cc2c9f12adbb19ae57aef5` | `5f616311bab38b0dac296ed8b0e69660e031a20e` | feat(v2r2c1): integrate governed release overlay |
|
||||
| `e41b8d323a3e7a40440f5d32221f524074bea5fe` | `57780e316e320a5128cc2c9f12adbb19ae57aef5` | feat(v2r2c1): wire governed release operations into durable bridge |
|
||||
| `b20cb8130e4c68267d5d85b02eed51cb8d4f41c0` | `e41b8d323a3e7a40440f5d32221f524074bea5fe` | test: repair canonical pytest repository entrypoint |
|
||||
| `c6a1693efaede9dace9b929d884a09e162a02c89` | `b20cb8130e4c68267d5d85b02eed51cb8d4f41c0` | test: make whole-suite collection deterministic |
|
||||
| `91f2ea0591787d3dbf8c2e27ab0460629d86900e` | `c6a1693efaede9dace9b929d884a09e162a02c89` | test: preserve legacy suite imports under canonical collection |
|
||||
| `85897d3f6d708271dff16767265f9d14b2f29801` | `91f2ea0591787d3dbf8c2e27ab0460629d86900e` | test: expose repository test helpers to canonical collection |
|
||||
| `f1110d24f30d8441f2df04e0774ee230b95c2e02` | `85897d3f6d708271dff16767265f9d14b2f29801` | fix(v2r2c1): close slash-branch and suite contract regressions |
|
||||
| `c10d2a5dfcc394dde7a7022952d7b423725747a3` | `f1110d24f30d8441f2df04e0774ee230b95c2e02` | test: align writer regression with durable idempotent replay |
|
||||
| `f969aedaf61501a866435c712be01ff2cfe43fb1` | `c10d2a5dfcc394dde7a7022952d7b423725747a3` | feat(v2r2c1): source baseline authority for model-api staging |
|
||||
| `4ab70bfdb4d34aa9d1dabc4230a3367eaa93cc9b` | `f969aedaf61501a866435c712be01ff2cfe43fb1` | feat(v2r2c1): add immutable model api staging runtime |
|
||||
| `7c4e86bfc1f39e643e672968d1fdedbd72ace56d` | `4ab70bfdb4d34aa9d1dabc4230a3367eaa93cc9b` | fix(v2r2c1): avoid builder secret-scan false positives |
|
||||
| `7564363a30bfa7fa81ac5c7c545ec704984ec543` | `7c4e86bfc1f39e643e672968d1fdedbd72ace56d` | fix(v2r2c1): isolate model api staging port |
|
||||
| `2c6293160ed567a2098715edbb296741577c5bff` | `7564363a30bfa7fa81ac5c7c545ec704984ec543` | fix(v2r2c1): bind baseline authority and openapi staging path |
|
||||
|
||||
## Exact diff stat
|
||||
|
||||
```text
|
||||
active-runtime/app/aios_authority_git_executor.py | 24 +
|
||||
active-runtime/app/aios_chatgpt_actions_api.py | 48 +-
|
||||
active-runtime/app/aios_chatgpt_bridge_v2.py | 167 ++++
|
||||
.../app/aios_chatgpt_bridge_v2_server.py | 431 +++++++++
|
||||
active-runtime/app/aios_continuation_executor.py | 594 ++++++++++++
|
||||
active-runtime/app/aios_continuation_lease.py | 6 +
|
||||
active-runtime/app/aios_control_plane_snapshot.py | 26 +
|
||||
active-runtime/app/aios_credential_broker.py | 78 ++
|
||||
active-runtime/app/aios_gitea_publisher.py | 93 ++
|
||||
active-runtime/app/aios_gitops_job_controller.py | 16 +-
|
||||
.../app/aios_gitops_reconciliation_core.py | 80 ++
|
||||
active-runtime/app/aios_governed_policy.py | 59 ++
|
||||
active-runtime/app/aios_governed_task_bootstrap.py | 84 ++
|
||||
active-runtime/app/aios_model_api_staging.py | 1022 ++++++++++++++++++++
|
||||
.../app/authorized_task_writer_provisioning.py | 4 +-
|
||||
active-runtime/app/baseline_authority.py | 84 ++
|
||||
active-runtime/app/governed_production_release.py | 568 +++++++++++
|
||||
active-runtime/app/v2r2c1_production_adapter.py | 135 +++
|
||||
.../systemd/aios-chatgpt-bridge-v2-staging.service | 23 +
|
||||
.../aios-gitops-model-api-v2r2c1-staging.service | 51 +
|
||||
...09-bridge-v2.1-durable-reconciliation-design.md | 15 +
|
||||
...t-bridge-v2-control-plane-convergence-design.md | 150 +++
|
||||
pytest.ini | 4 +
|
||||
scripts/build_v2r2c1_model_api_staging.py | 145 +++
|
||||
.../aios_release_controller/manifest.py | 4 +-
|
||||
.../test_v2r1c6_release_consistency.py | 4 +-
|
||||
.../aios_v2_candidate/test_v2r1c6_release_ready.py | 16 +-
|
||||
tests/conftest.py | 65 ++
|
||||
tests/test_bridge_v2_governed_http_bootstrap.py | 90 ++
|
||||
tests/test_governed_local_writer.py | 6 +-
|
||||
tests/test_model_api_immutable_staging.py | 35 +
|
||||
31 files changed, 4108 insertions(+), 19 deletions(-)
|
||||
```
|
||||
|
||||
## Included durable source domains
|
||||
|
||||
- Bridge v2 adapter/server and governed HTTP contracts.
|
||||
- Durable reconciliation core, continuation executor/lease, Authority Git CAS adapter, job controller compatibility.
|
||||
- Gitea publisher/verifier, credential broker, governed policy, control-plane snapshot, release routing.
|
||||
- Canonical pytest entrypoint/conftest and regression coverage.
|
||||
- Source-controlled immutable model-api staging runtime, builder and systemd template.
|
||||
- Selected design specifications required for durable mainline context.
|
||||
|
||||
## Explicitly excluded
|
||||
|
||||
- `main` ref mutation or merge without Owner approval.
|
||||
- Production service, Registry, Baseline body/sidecar, production tags and mutable `/var/lib` state.
|
||||
- Installed `/opt` artifacts, temporary staging transition state and task-local receipts/credentials.
|
||||
- Production cutover/restart, force push, history rewrite and plaintext secrets.
|
||||
|
||||
## Verification
|
||||
|
||||
- `pytest tests`: **709 passed, 2 skipped, 154 subtests, 0 failed**.
|
||||
- Staging model-api: immutable OID/digest bound, port 18893, health/base/ver/OpenAPI readback PASS, restart recovery PASS.
|
||||
- Authority/Gitea Git/Gitea API commit equality and commit visibility PASS.
|
||||
- Production remains V2R2C1 and was not restarted or cut over.
|
||||
@@ -1,254 +0,0 @@
|
||||
{
|
||||
"control_plane_source_oid": "b781129bd5a8b53c05ab648361424d2800166ee4",
|
||||
"diff_stat": "active-runtime/app/aios_authority_git_executor.py | 24 +\n active-runtime/app/aios_chatgpt_actions_api.py | 48 +-\n active-runtime/app/aios_chatgpt_bridge_v2.py | 167 ++++\n .../app/aios_chatgpt_bridge_v2_server.py | 431 +++++++++\n active-runtime/app/aios_continuation_executor.py | 594 ++++++++++++\n active-runtime/app/aios_continuation_lease.py | 6 +\n active-runtime/app/aios_control_plane_snapshot.py | 26 +\n active-runtime/app/aios_credential_broker.py | 78 ++\n active-runtime/app/aios_gitea_publisher.py | 93 ++\n active-runtime/app/aios_gitops_job_controller.py | 16 +-\n .../app/aios_gitops_reconciliation_core.py | 80 ++\n active-runtime/app/aios_governed_policy.py | 59 ++\n active-runtime/app/aios_governed_task_bootstrap.py | 84 ++\n active-runtime/app/aios_model_api_staging.py | 1022 ++++++++++++++++++++\n .../app/authorized_task_writer_provisioning.py | 4 +-\n active-runtime/app/baseline_authority.py | 84 ++\n active-runtime/app/governed_production_release.py | 568 +++++++++++\n active-runtime/app/v2r2c1_production_adapter.py | 135 +++\n .../systemd/aios-chatgpt-bridge-v2-staging.service | 23 +\n .../aios-gitops-model-api-v2r2c1-staging.service | 51 +\n ...09-bridge-v2.1-durable-reconciliation-design.md | 15 +\n ...t-bridge-v2-control-plane-convergence-design.md | 150 +++\n pytest.ini | 4 +\n scripts/build_v2r2c1_model_api_staging.py | 145 +++\n .../aios_release_controller/manifest.py | 4 +-\n .../test_v2r1c6_release_consistency.py | 4 +-\n .../aios_v2_candidate/test_v2r1c6_release_ready.py | 16 +-\n tests/conftest.py | 65 ++\n tests/test_bridge_v2_governed_http_bootstrap.py | 90 ++\n tests/test_governed_local_writer.py | 6 +-\n tests/test_model_api_immutable_staging.py | 35 +\n 31 files changed, 4108 insertions(+), 19 deletions(-)",
|
||||
"evidence_closure_oid": "a8b906d1bc24088c19647e98de6a679268f6d0a2",
|
||||
"excluded_paths": [
|
||||
{
|
||||
"path": "refs/heads/main",
|
||||
"reason": "main merge requires separate Owner approval; unchanged"
|
||||
},
|
||||
{
|
||||
"path": "refs/tags/*",
|
||||
"reason": "formal tags are outside engineering convergence scope; unchanged"
|
||||
},
|
||||
{
|
||||
"path": "baseline/current.json and sidecar",
|
||||
"reason": "production mutable authority and sidecar; read-only verified"
|
||||
},
|
||||
{
|
||||
"path": "/var/lib/aios-gitops/**",
|
||||
"reason": "host runtime state and receipts excluded from repository source"
|
||||
},
|
||||
{
|
||||
"path": "/opt/aios/**",
|
||||
"reason": "installed immutable staging artifacts excluded; digest recorded in reports"
|
||||
},
|
||||
{
|
||||
"path": "credentials and secrets",
|
||||
"reason": "availability-only; no plaintext credential committed"
|
||||
},
|
||||
{
|
||||
"path": "production runtime and Registry",
|
||||
"reason": "production cutover/registry mutation forbidden"
|
||||
}
|
||||
],
|
||||
"included_paths": [
|
||||
{
|
||||
"path": "active-runtime/app/aios_authority_git_executor.py",
|
||||
"status": "M"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_chatgpt_actions_api.py",
|
||||
"status": "M"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_chatgpt_bridge_v2.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_chatgpt_bridge_v2_server.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_continuation_executor.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_continuation_lease.py",
|
||||
"status": "M"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_control_plane_snapshot.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_credential_broker.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_gitea_publisher.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_gitops_job_controller.py",
|
||||
"status": "M"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_gitops_reconciliation_core.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_governed_policy.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_governed_task_bootstrap.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/aios_model_api_staging.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/authorized_task_writer_provisioning.py",
|
||||
"status": "M"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/baseline_authority.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/governed_production_release.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "active-runtime/app/v2r2c1_production_adapter.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "deploy/systemd/aios-chatgpt-bridge-v2-staging.service",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "deploy/systemd/aios-gitops-model-api-v2r2c1-staging.service",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "docs/superpowers/specs/2026-08-09-bridge-v2.1-durable-reconciliation-design.md",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "docs/superpowers/specs/2026-08-09-chatgpt-bridge-v2-control-plane-convergence-design.md",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "pytest.ini",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "scripts/build_v2r2c1_model_api_staging.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "services/aios-release-controller/aios_release_controller/manifest.py",
|
||||
"status": "M"
|
||||
},
|
||||
{
|
||||
"path": "tests/aios_v2_candidate/test_v2r1c6_release_consistency.py",
|
||||
"status": "M"
|
||||
},
|
||||
{
|
||||
"path": "tests/aios_v2_candidate/test_v2r1c6_release_ready.py",
|
||||
"status": "M"
|
||||
},
|
||||
{
|
||||
"path": "tests/conftest.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "tests/test_bridge_v2_governed_http_bootstrap.py",
|
||||
"status": "A"
|
||||
},
|
||||
{
|
||||
"path": "tests/test_governed_local_writer.py",
|
||||
"status": "M"
|
||||
},
|
||||
{
|
||||
"path": "tests/test_model_api_immutable_staging.py",
|
||||
"status": "A"
|
||||
}
|
||||
],
|
||||
"integration_branch": "agent/v2r2c1-post-release-mainline-convergence-20260809",
|
||||
"integration_head_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"logical_commits": [
|
||||
{
|
||||
"message": "feat(v2r2c1): converge durable control-plane core",
|
||||
"oid": "40b685d1c70c767c7a79a2b184348e58e3e319ae",
|
||||
"parent_oid": "2e8fa22989808a448065d1d76b5b18948774a637"
|
||||
},
|
||||
{
|
||||
"message": "docs(v2r2c1): converge durable runtime and design sources",
|
||||
"oid": "5f616311bab38b0dac296ed8b0e69660e031a20e",
|
||||
"parent_oid": "40b685d1c70c767c7a79a2b184348e58e3e319ae"
|
||||
},
|
||||
{
|
||||
"message": "feat(v2r2c1): integrate governed release overlay",
|
||||
"oid": "57780e316e320a5128cc2c9f12adbb19ae57aef5",
|
||||
"parent_oid": "5f616311bab38b0dac296ed8b0e69660e031a20e"
|
||||
},
|
||||
{
|
||||
"message": "feat(v2r2c1): wire governed release operations into durable bridge",
|
||||
"oid": "e41b8d323a3e7a40440f5d32221f524074bea5fe",
|
||||
"parent_oid": "57780e316e320a5128cc2c9f12adbb19ae57aef5"
|
||||
},
|
||||
{
|
||||
"message": "test: repair canonical pytest repository entrypoint",
|
||||
"oid": "b20cb8130e4c68267d5d85b02eed51cb8d4f41c0",
|
||||
"parent_oid": "e41b8d323a3e7a40440f5d32221f524074bea5fe"
|
||||
},
|
||||
{
|
||||
"message": "test: make whole-suite collection deterministic",
|
||||
"oid": "c6a1693efaede9dace9b929d884a09e162a02c89",
|
||||
"parent_oid": "b20cb8130e4c68267d5d85b02eed51cb8d4f41c0"
|
||||
},
|
||||
{
|
||||
"message": "test: preserve legacy suite imports under canonical collection",
|
||||
"oid": "91f2ea0591787d3dbf8c2e27ab0460629d86900e",
|
||||
"parent_oid": "c6a1693efaede9dace9b929d884a09e162a02c89"
|
||||
},
|
||||
{
|
||||
"message": "test: expose repository test helpers to canonical collection",
|
||||
"oid": "85897d3f6d708271dff16767265f9d14b2f29801",
|
||||
"parent_oid": "91f2ea0591787d3dbf8c2e27ab0460629d86900e"
|
||||
},
|
||||
{
|
||||
"message": "fix(v2r2c1): close slash-branch and suite contract regressions",
|
||||
"oid": "f1110d24f30d8441f2df04e0774ee230b95c2e02",
|
||||
"parent_oid": "85897d3f6d708271dff16767265f9d14b2f29801"
|
||||
},
|
||||
{
|
||||
"message": "test: align writer regression with durable idempotent replay",
|
||||
"oid": "c10d2a5dfcc394dde7a7022952d7b423725747a3",
|
||||
"parent_oid": "f1110d24f30d8441f2df04e0774ee230b95c2e02"
|
||||
},
|
||||
{
|
||||
"message": "feat(v2r2c1): source baseline authority for model-api staging",
|
||||
"oid": "f969aedaf61501a866435c712be01ff2cfe43fb1",
|
||||
"parent_oid": "c10d2a5dfcc394dde7a7022952d7b423725747a3"
|
||||
},
|
||||
{
|
||||
"message": "feat(v2r2c1): add immutable model api staging runtime",
|
||||
"oid": "4ab70bfdb4d34aa9d1dabc4230a3367eaa93cc9b",
|
||||
"parent_oid": "f969aedaf61501a866435c712be01ff2cfe43fb1"
|
||||
},
|
||||
{
|
||||
"message": "fix(v2r2c1): avoid builder secret-scan false positives",
|
||||
"oid": "7c4e86bfc1f39e643e672968d1fdedbd72ace56d",
|
||||
"parent_oid": "4ab70bfdb4d34aa9d1dabc4230a3367eaa93cc9b"
|
||||
},
|
||||
{
|
||||
"message": "fix(v2r2c1): isolate model api staging port",
|
||||
"oid": "7564363a30bfa7fa81ac5c7c545ec704984ec543",
|
||||
"parent_oid": "7c4e86bfc1f39e643e672968d1fdedbd72ace56d"
|
||||
},
|
||||
{
|
||||
"message": "fix(v2r2c1): bind baseline authority and openapi staging path",
|
||||
"oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"parent_oid": "7564363a30bfa7fa81ac5c7c545ec704984ec543"
|
||||
}
|
||||
],
|
||||
"main_base_oid": "2e8fa22989808a448065d1d76b5b18948774a637",
|
||||
"release_target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"remote_proof": {
|
||||
"api_branch_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"api_verification": "paginated_exact_name",
|
||||
"commit_visible": true,
|
||||
"git_remote_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"main_api_oid": "2e8fa22989808a448065d1d76b5b18948774a637",
|
||||
"main_git_oid": "2e8fa22989808a448065d1d76b5b18948774a637"
|
||||
},
|
||||
"report_commit_parent_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"repository": "aios/aios",
|
||||
"schema": "aios.v2r2c1.post-release-mainline-convergence.path-manifest.v1",
|
||||
"task_id": "TASK-P0-V2R2C1-POST-RELEASE-MAINLINE-CONVERGENCE-20260809"
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
{
|
||||
"artifact_sha256": "492338b895b152a55015fd92ea1d9dba2314894ab00c0ba219a78f3cef544b8a",
|
||||
"baseline_authority_path": "/var/lib/aios-gitops-runtime-anchor/baseline/current.json",
|
||||
"checks": {
|
||||
"artifact_sha256": "PASS",
|
||||
"baseline_registry_readback": "PASS",
|
||||
"health_contract": "PASS",
|
||||
"legacy_write_rejection": "PASS",
|
||||
"live_service_unchanged": "PASS",
|
||||
"manifest_binding": "PASS",
|
||||
"openapi_readback": "PASS",
|
||||
"restart_recovery": "PASS"
|
||||
},
|
||||
"current_live_port": 18890,
|
||||
"current_live_service": "aios-gitops-model-api.service",
|
||||
"deployment_state": "STAGING",
|
||||
"execute": false,
|
||||
"governed_release_routing": "bridge-v2",
|
||||
"legacy_global_writes_enabled": false,
|
||||
"live_cutover": false,
|
||||
"owner_actions_required": [
|
||||
"review exact source OID and artifact SHA",
|
||||
"approve a separate future live model-api cutover",
|
||||
"approve any production service transition"
|
||||
],
|
||||
"production_restart": false,
|
||||
"repository_identity": "aios/aios",
|
||||
"runtime_mode": "IMMUTABLE_STAGING",
|
||||
"schema": "aios.v2r2c1.model-api-runtime-activation-plan.v1",
|
||||
"source_oid": "2c6293160ed567a2098715edbb296741577c5bff",
|
||||
"staging_port": 18893,
|
||||
"staging_runtime_root": "/opt/aios/gitops-model-api/2c6293160ed567a2098715edbb296741577c5bff/runtime",
|
||||
"staging_service": "aios-gitops-model-api-v2r2c1-staging.service",
|
||||
"status": "OWNER_APPROVAL_REQUIRED",
|
||||
"target_version": "V2R2C1",
|
||||
"task_id": "TASK-P0-V2R2C1-POST-RELEASE-MAINLINE-CONVERGENCE-20260809"
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
bcd2be5e87cc55610bacb80dd69b65749b6549e246d28698b8afa86b4bd9cd36 reports/V2R2C1-production-release-evidence-closure-20260809.json
|
||||
1d78fcfd0ee4486859b41d1e925b5d34a8e6292cbf2a4db33bc0efdf7c10550e reports/V2R2C1-production-release-evidence-closure-20260809.md
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"created_at": "2026-08-09T07:41:55Z",
|
||||
"engineering": {
|
||||
"authority_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"commit_visible": true,
|
||||
"final_target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"gitea_api_branch_collection": "GET /api/v1/repos/aios/aios/branches?page=1&limit=50 exact-name match",
|
||||
"gitea_api_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"gitea_api_tag_collection": "GET /api/v1/repos/aios/aios/tags?page=1&limit=50 exact-name absence",
|
||||
"gitea_git_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"gitea_git_readback": "PASS",
|
||||
"target_is_ancestor": true
|
||||
},
|
||||
"engineering_branch": "agent/p0-bridge-v21-durable-reconciliation-20260809",
|
||||
"evidence_closure_scope": "engineering_and_staging_acceptance_only",
|
||||
"governance": {
|
||||
"direct_main_push": false,
|
||||
"direct_ref_write": false,
|
||||
"force_push_used": false,
|
||||
"history_rewritten": false,
|
||||
"owner_approval_respected": true,
|
||||
"production_changed": false,
|
||||
"production_restarted": false,
|
||||
"secrets_committed": false,
|
||||
"tag_rewritten": false
|
||||
},
|
||||
"production_baseline_modified": false,
|
||||
"production_deployed": false,
|
||||
"production_precondition": {
|
||||
"baseline_version": "V2R1C7",
|
||||
"main_oid": "2e8fa22989808a448065d1d76b5b18948774a637",
|
||||
"production_release_authorized": false,
|
||||
"restarted": false,
|
||||
"target_oid": "c7adece1cc8beffe7c718d53c775898b45d6c7f8",
|
||||
"unchanged": true,
|
||||
"v2r2c1_registry_present": false,
|
||||
"v2r2c1_tag_present": false
|
||||
},
|
||||
"production_release_authorized": false,
|
||||
"production_tag_created": false,
|
||||
"schema": "aios.production-release-evidence-closure.v1",
|
||||
"staging": {
|
||||
"artifact_path": "/opt/aios/gitops-control-plane/998d30304787e31e5ae607c0bd86b5edb2b0e5ad/bridge-v2-staging.pyz",
|
||||
"artifact_sha256": "f6a98893da14320cbca9ee4f25702a8d986ac2e1795f3cadb3ec5bf76e90da8d",
|
||||
"deployment_state": "STAGING",
|
||||
"getControlPlaneSnapshot": "PASS",
|
||||
"getGovernedWriteCapabilities": "PASS",
|
||||
"getRuntimeStatus": "PASS",
|
||||
"manifest_drift": "PASS",
|
||||
"restart_recovery": "PASS",
|
||||
"runtime_release_commit": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"runtime_target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"secret_material_exposed": false
|
||||
},
|
||||
"target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"tests": {
|
||||
"full_repo_pytest_status": "COLLECTION_BLOCKED_BY_EXISTING_ENTRYPOINT_MAPPING_DEBT",
|
||||
"known_collection_debt": [
|
||||
"aios_autonomous_release_candidate",
|
||||
"active_runtime"
|
||||
],
|
||||
"mandatory_suite_failed": 0,
|
||||
"mandatory_suite_passed": 59,
|
||||
"mandatory_suite_result": "59 passed / 0 failed"
|
||||
},
|
||||
"version": "V2R2C1"
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
# V2R2C1 Production Release Evidence Closure
|
||||
|
||||
- Schema: `aios.production-release-evidence-closure.v1`
|
||||
- Created: `2026-08-09T07:41:55Z`
|
||||
- Scope: engineering and staging acceptance only
|
||||
|
||||
## Exact engineering binding
|
||||
|
||||
- Version: `V2R2C1`
|
||||
- Target OID: `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`
|
||||
- Engineering branch: `agent/p0-bridge-v21-durable-reconciliation-20260809`
|
||||
- Authority branch OID: `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`
|
||||
- Gitea Git branch OID: `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`
|
||||
- Gitea API branch OID: `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`
|
||||
- `commit_visible=true`
|
||||
- `target_is_ancestor=true`
|
||||
- Gitea Git readback: `PASS`
|
||||
- Gitea API slash-branch proof: collection endpoint with exact-name match, `PASS`
|
||||
|
||||
## Staging acceptance
|
||||
|
||||
- Artifact: `/opt/aios/gitops-control-plane/998d30304787e31e5ae607c0bd86b5edb2b0e5ad/bridge-v2-staging.pyz`
|
||||
- Artifact SHA-256: `f6a98893da14320cbca9ee4f25702a8d986ac2e1795f3cadb3ec5bf76e90da8d`
|
||||
- `deployment_state=STAGING`
|
||||
- Manifest drift: `PASS`
|
||||
- Runtime target OID: `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`
|
||||
- Runtime release commit: `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`
|
||||
- `getRuntimeStatus`: `PASS`
|
||||
- `getGovernedWriteCapabilities`: `PASS`
|
||||
- `getControlPlaneSnapshot`: `PASS`
|
||||
- Restart recovery: `PASS`
|
||||
- `secret_material_exposed=false`
|
||||
|
||||
## Tests
|
||||
|
||||
- Mandatory V2R2C1 suite: `59 passed / 0 failed`
|
||||
- Whole-repository pytest: `COLLECTION_BLOCKED_BY_EXISTING_ENTRYPOINT_MAPPING_DEBT`
|
||||
- Known collection debt: `aios_autonomous_release_candidate`, `active_runtime`
|
||||
|
||||
The whole-repository collection debt is retained explicitly and is not reported as a full-suite pass.
|
||||
|
||||
## Production precondition and freeze
|
||||
|
||||
- Production Baseline: `V2R1C7`
|
||||
- Production target OID: `c7adece1cc8beffe7c718d53c775898b45d6c7f8`
|
||||
- Production main OID: `2e8fa22989808a448065d1d76b5b18948774a637`
|
||||
- V2R2C1 production Tag: absent
|
||||
- V2R2C1 production Registry registration: absent
|
||||
- Production changed: `false`
|
||||
- Production restarted: `false`
|
||||
|
||||
This commit is evidence metadata only. It does not authorize or perform production Tag creation, production deployment, Baseline modification, Registry modification, main merge/push, or production restart.
|
||||
|
||||
## Governance
|
||||
|
||||
```yaml
|
||||
force_push_used: false
|
||||
tag_rewritten: false
|
||||
direct_main_push: false
|
||||
direct_ref_write: false
|
||||
secrets_committed: false
|
||||
history_rewritten: false
|
||||
production_restarted: false
|
||||
production_changed: false
|
||||
owner_approval_respected: true
|
||||
production_release_authorized: false
|
||||
production_tag_created: false
|
||||
production_baseline_modified: false
|
||||
production_deployed: false
|
||||
```
|
||||
@@ -1,98 +0,0 @@
|
||||
# AIOS Action Connector Schema Final Closure — 2026-08-25
|
||||
|
||||
## Disposition
|
||||
|
||||
`NEEDS_REWORK`.
|
||||
|
||||
The staging runtime and published OpenAPI contract are repaired and the public `/v2` staging route is now reachable. The final P0-C acceptance cannot be claimed because this execution environment has no callable ChatGPT Action/connector inspection or registration tool, and the deployed repository intentionally has no connector acknowledgement/write endpoint. Therefore the required proof of the actual callable tool schema, a real public two-file batch commit, and its public terminal reconcile are not available. The task must not be marked `SUCCEEDED`.
|
||||
|
||||
No main, protected tag, baseline registry, or production write was performed.
|
||||
|
||||
## Scope and live identity
|
||||
|
||||
- Repository: `aios/aios`
|
||||
- Task: `fix-action-contracts-20260825-1407`
|
||||
- Branch: `agent/fix-action-contracts-20260825-1407`
|
||||
- Source worktree: `/var/lib/aios-gitops/bridge-v2-staging/worktrees/fix-action-contracts-20260825-1407`
|
||||
- Source HEAD before this closure patch: `eb72fcd8dce242abaef15f03a21b43ba2c5197fd`
|
||||
- Deployed staging Bridge runtime commit: `2ec49005bde44f6981b14351500847d594e0276c`
|
||||
- Deployed Bridge artifact SHA-256: `f67aed6cc0cce1f08197485c3eea204d3ef4d3989f44dc98e8ea2691e5886cbf`
|
||||
- Bridge unit: `aios-chatgpt-bridge-v2-staging.service`, `aiman:gitops`, `127.0.0.1:18892`
|
||||
- Model API unit: `aios-gitops-model-api-v2r2c1-staging.service`, `127.0.0.1:18893`
|
||||
- Gitea API base projected by staging systemd: `https://g.cnnetmkt.top/git/api/v1`
|
||||
- Runtime state: `STAGING`, `drift_status=PASS`, `legacy_global_writes_enabled=false`, `main_write=false`, `tag_write=false`, `baseline_write=false`, `production_write=false`
|
||||
|
||||
## Root causes and contract chain
|
||||
|
||||
1. Runtime source was already repaired to require `files` for `commitFilesGoverned`. `active-runtime/app/aios_chatgpt_bridge_v2.py` declares the canonical required tuple and `render_openapi_contract_fragment()` emits the operation fragment.
|
||||
2. `scripts/build_v2r2c1_model_api_staging.py` copies the canonical `docs/gitops/openapi-chatgpt-actions.yaml` into the immutable staging artifact and rejects a build missing `/v2/commit-files`.
|
||||
3. The deployed public OpenAPI is served from the model API workspace at `/api/openapi-chatgpt-actions.yaml`; its SHA-256 was `a0775b0719a76e08a95f3257a3d3b2a73b70e1c55c162914250f80dd28da022d`. It contains `/v2/commit-files`, `files`, and item fields `path` and `content_base64`.
|
||||
4. The missing deployment link was Nginx: OpenAPI `servers.url` is `https://cnnetmkt.top` and its operation paths are `/v2/...`, but the live site had no `/v2/` location and the old `/api/v2/` location pointed at absent production port `18920`. The old `/api/file` route is an inactive legacy single-file router.
|
||||
5. A repository-wide and host-side inspection found no formal external ChatGPT connector registration source, schema cache, re-registration command, or acknowledgement endpoint. The existing durable-owner design explicitly states that no connector acknowledgement/write endpoint is provided and the only valid state is `PENDING_EXTERNAL_CONNECTOR`. This is the remaining external blocker, not a reason to create a parallel local schema or reuse another credential.
|
||||
|
||||
## Changes made
|
||||
|
||||
- `ops/gitops-migration/bind_external_action_surface_final_staging.sh`
|
||||
- added an idempotent exact `/v2/` route to staging Bridge `127.0.0.1:18892`;
|
||||
- forwards `Authorization` and `X-AIOS-Token`;
|
||||
- keeps the existing exact governed-read routes on `18890` and generic `/api/` on `18893`;
|
||||
- refuses an incomplete existing staging route and never adds a route to production `18920`.
|
||||
- `tests/test_action_contract_regressions.py`
|
||||
- added a parity/deployment test tying published `/v2/commit-files` to the staging route and asserting no `18920` target in the staging installer.
|
||||
- `runbooks/action-connector-schema-refresh-20260825.md`
|
||||
- added the durable connector refresh and fail-closed acceptance procedure.
|
||||
- `reports/action-connector-schema-final-closure-20260825.md`
|
||||
- this evidence report.
|
||||
|
||||
The source/runtime contract parity test remains in place and still compares runtime required fields, generated fragment, and published schema. The live connector layer cannot be parity-tested because no connector layer is deployed or callable from this environment; the gate therefore remains fail-closed rather than accepting a fixture as proof.
|
||||
|
||||
## Deployment and restart evidence
|
||||
|
||||
The existing staging installer was run after `git diff --check` and focused tests. It created the Nginx backup `/data/aios-gitops/backups/action-surface-final-20260825T105656Z`, passed `nginx -t`, and reloaded Nginx. Public readback then returned HTTP 200 for:
|
||||
|
||||
- `https://cnnetmkt.top/v2/runtime`
|
||||
- `https://cnnetmkt.top/v2/capabilities`
|
||||
- `https://cnnetmkt.top/api/openapi-chatgpt-actions.yaml`
|
||||
|
||||
The staging Bridge and Model API were subsequently restarted once. Both `systemctl is-active` checks returned `active`. Post-restart `/v2/runtime` retained the staging identity and artifact SHA above; `/v2/capabilities` retained `commitFilesGoverned.required_fields` including `files`.
|
||||
|
||||
## Tests and live smoke
|
||||
|
||||
Passing results:
|
||||
|
||||
- `python3 -m pytest -q tests/test_action_contract_regressions.py tests/test_bridge_v2_governed_http_bootstrap.py` — `17 passed`.
|
||||
- Mandatory suite — `264 passed, 28 subtests passed in 4.81s`.
|
||||
- Full repository suite — `720 passed, 2 skipped, 2 failed, 154 subtests passed in 34.02s`. The two failures are unchanged known failures: stale `/tmp/aios-agent-events-test` fixture and deployed signer self-test return code `42`.
|
||||
|
||||
Post-restart live results:
|
||||
|
||||
- `getReleaseConsistency(V2R2C1, ...)`: HTTP 200 structured consistency response; no Gitea URL validation failure. Gitea listing and peeled target readback were visible.
|
||||
- `runReleaseAcceptance(V2R2C1, ...)`: HTTP 200 structured policy result with `accepted=false`; it reached policy evaluation rather than failing URL validation.
|
||||
- `getTagPublicationStatus("V2R2C1")`: HTTP 200 structured state (`REMOTE_PUSH_PENDING` on Bridge v2; the legacy model read surface returned structured `UNKNOWN`).
|
||||
- `getReleaseSaga(nonexistent)`: HTTP 404, normal NOT_FOUND behavior.
|
||||
- Existing terminal job `job-93138017f3afd7f709f691fd05c77923`: HTTP 200, `COMPLETED`, revision `8`; terminal `/v2/job/reconcile` returned HTTP 200 with the same `COMPLETED` receipt and Authority/API/Git remote OID `904e7ea0cd376d204bad19628c36a9dd90ca6621`.
|
||||
- Empty diff: HTTP 200, zero paths/size, `truncated=false`.
|
||||
- Non-empty diff: HTTP 200 with identities, changed paths, stats, total size, patch limit `262144`, and bounded response fields.
|
||||
- Public `POST /v2/commit-files` probes returned `BRIDGE_REQUEST_FIELDS_MISSING` for incomplete bodies; the body containing `files` was not rejected as an unknown field. No write side effect occurred.
|
||||
|
||||
## Missing final acceptance
|
||||
|
||||
The following required evidence is not available and is intentionally not inferred:
|
||||
|
||||
- actual ChatGPT callable Action tool schema showing required `files`;
|
||||
- formal connector re-register/cache invalidation acknowledgement;
|
||||
- an authorized public `commitFilesGoverned` request containing two files;
|
||||
- Authority/Gitea/API remote OID equality for that new batch commit;
|
||||
- its batch Job `COMPLETED` readback and public terminal reconcile;
|
||||
- post-batch connector callable smoke.
|
||||
|
||||
The prior single-file public commit `904e7ea0cd376d204bad19628c36a9dd90ca6621` and its terminal reconcile are preserved as baseline evidence only; they are not substituted for the required batch proof.
|
||||
|
||||
## Protected boundaries and rollback
|
||||
|
||||
No source or deployment operation wrote `main`, a protected tag, the baseline registry, or production. The production-facing `18920` route was not changed; the new `/v2/` location targets only the staging Bridge listener. No secret value was printed, rotated, or reused. Automatic rollback was not triggered because Nginx syntax, staging service health, runtime identity, Gitea readback, and protected-ref boundaries remained valid. If a future connector refresh breaks these checks, restore the Nginx backup and the preceding staging artifact through the existing governed installer, then re-run the same probes.
|
||||
|
||||
## Next required owner/platform action
|
||||
|
||||
Provide the supported staging external Action connector lifecycle (registration/re-registration/cache invalidation) and an authorized staging Action bearer, or have the legitimate external Agent claim the existing continuation task and produce its durable callable-schema and batch-commit evidence. Until then the correct disposition remains `NEEDS_REWORK`; do not mark `SUCCEEDED` based on the server-side OpenAPI alone.
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
# Action Contract Regression Remediation — 2026-08-25
|
||||
|
||||
## Scope
|
||||
|
||||
Governed task: `fix-action-contracts-20260825-1407`
|
||||
Base: `3244f0f17f8845592ac94d585f5ebd65693c9f29`
|
||||
Target branch: `agent/fix-action-contracts-20260825-1407`
|
||||
|
||||
## Verified regressions
|
||||
|
||||
1. `getReleaseConsistency` and `runReleaseAcceptance` fail before evaluation with:
|
||||
`Gitea API URL must be HTTP(S)`.
|
||||
V2R2C1 release evidence at `a8b906d1bc24088c19647e98de6a679268f6d0a2`
|
||||
proves Gitea API readback passed for target `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`.
|
||||
Therefore current staging/contract overlay configuration has regressed.
|
||||
|
||||
2. `getReleaseSaga` fails with:
|
||||
`Permission denied: '/var/lib/aios-gitops/silent-release'`.
|
||||
Runtime service identity must have read/traverse access to the durable release state root.
|
||||
Fix ownership/group/ACL at deployment time; do not broaden to world-writable permissions.
|
||||
|
||||
3. `getTagPublicationStatus` rejects the authoritative approved version `V2R2C1`
|
||||
as `invalid release version`, while `getGovernedWriteCapabilities` returns the same
|
||||
version as the approved release scope. The two Action contracts are internally inconsistent.
|
||||
Release-version validation must accept the canonical AIOS `^V[0-9]+R[0-9]+C[0-9]+$`
|
||||
namespace (or, preferably, use one shared validator for all release Actions).
|
||||
|
||||
4. `commitFilesGoverned` is unusable from the published Action schema.
|
||||
Runtime capability metadata declares required fields:
|
||||
`task_id, repository, expected_branch_oid, target_branch, generation, idempotency_key, files, message`,
|
||||
but the exposed tool contract has no `files` input. Regenerate/publish the Action schema from
|
||||
the same operation contract source and add a contract-parity test.
|
||||
|
||||
5. `reconcileGitOpsJob` returned `DURABLE_BINDING_INVALID` for a completed governed
|
||||
single-file job that was otherwise read back as `COMPLETED`.
|
||||
Reconciliation of a valid terminal job should be idempotent/read-only and must not require
|
||||
a stale or absent active lease. Add a regression case for terminal completed jobs.
|
||||
|
||||
6. `getDiff` returns `ResponseTooLargeError` / `GIT_OUTPUT_LIMIT_EXCEEDED` for large diffs.
|
||||
Add server-side bounded output: path/stat summary plus truncation metadata, or pagination.
|
||||
The Action must never fail merely because a valid repository diff is large.
|
||||
|
||||
## Required implementation changes
|
||||
|
||||
- Centralize release-version parsing and reuse it in tag status, candidate, consistency, and acceptance.
|
||||
- Validate/normalize Gitea API URL at service startup and fail health checks with a configuration-specific diagnostic.
|
||||
- Ensure the deployment unit projects a valid HTTP(S) Gitea API base URL into the staging overlay.
|
||||
- Correct durable release-state directory ownership/ACL for the runtime service account.
|
||||
- Generate the external Action schema from the runtime operation contract; parity-test required fields.
|
||||
- Make terminal reconciliation idempotent and independent of expired active writer leases.
|
||||
- Bound diff output and return `truncated=true` with deterministic metadata rather than transport failure.
|
||||
|
||||
## Acceptance gates
|
||||
|
||||
All must pass on the same deployed overlay:
|
||||
|
||||
- `getReleaseConsistency(V2R2C1, 998d303..., a8b906d..., approved_plan)` returns a structured result, not URL error.
|
||||
- `runReleaseAcceptance(...)` reaches policy evaluation, not URL error.
|
||||
- `getTagPublicationStatus("V2R2C1")` returns structured publication state.
|
||||
- `getReleaseSaga(nonexistent_candidate)` returns NOT_FOUND/empty-state semantics, never filesystem permission failure.
|
||||
- Published `commitFilesGoverned` schema exposes `files` and a two-file isolated branch commit succeeds.
|
||||
- Reconcile of a completed governed job is idempotent.
|
||||
- Large diff returns bounded/truncated data rather than transport exception.
|
||||
- Existing protected-ref controls remain unchanged: no direct main/tag/baseline/production write.
|
||||
|
||||
## Proven stable reference
|
||||
|
||||
V2R2C1 evidence closure (`a8b906d1bc24088c19647e98de6a679268f6d0a2`) records:
|
||||
- Gitea Git/API readback PASS
|
||||
- staging runtime PASS
|
||||
- restart recovery PASS
|
||||
- 59 mandatory tests passed / 0 failed
|
||||
|
||||
This evidence should be used as the compatibility baseline when repairing the current
|
||||
`contract-overlay-v2` / `scheme-a-323b615b...` staging layer.
|
||||
@@ -1,119 +0,0 @@
|
||||
# AIOS Action contract repair evidence — 2026-08-25
|
||||
|
||||
## Disposition
|
||||
|
||||
Final disposition: `NEEDS_REWORK`.
|
||||
|
||||
The contract repair is deployed to staging and the focused acceptance checks are green. The task is not eligible for `SUCCEEDED`: `runReleaseAcceptance` returns structured policy output with `accepted=false` because the existing publication state for protected tag `V2R2C1` is `REMOTE_PUSH_PENDING`, and the repository-wide suite still has the two pre-existing signer/event-bus failures recorded below. The online Task API row is still `QUEUED`; it was not changed by direct database manipulation or an unauthorized synthetic claim/result.
|
||||
|
||||
No production release, `main`, release tag, baseline registry, or production service was directly modified.
|
||||
|
||||
## Scope and pre-change facts
|
||||
|
||||
- Repository: `aios/aios`; governed branch: `agent/fix-action-contracts-20260825-1407`.
|
||||
- Initial task branch HEAD: `35eec9afe1432e8466d60040b2fb1049bb41242a`.
|
||||
- Stable reference: `V2R2C1`; source commit `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`; evidence closure `a8b906d1bc24088c19647e98de6a679268f6d0a2`.
|
||||
- Pre-change refs: authority `main=3244f0f17f8845592ac94d585f5ebd65693c9f29`, tag `V2R2C1=07fc2746b688f5f243f29b39de39f32edc3dd9d2`; these remained unchanged.
|
||||
- Staging services run as `User=aiman`, `Group=gitops`. The actual staging Gitea API base is `https://g.cnnetmkt.top/git/api/v1`, supplied by systemd environment rather than business-code host constants.
|
||||
- Pre-change full test baseline: `707 passed, 2 skipped, 154 subtests passed, 2 failed`. The failures were the stale `/tmp/aios-agent-events-test` event-bus fixture and the real signer self-test.
|
||||
|
||||
## Root causes and repairs
|
||||
|
||||
1. Gitea URL validation occurred at release-operation time while the staging overlay's API environment was not consistently projected into all runtime paths. The canonical HTTP(S) validator is now called during model and Bridge startup; `getReleaseConsistency` and `runReleaseAcceptance` use the actual staging environment URL.
|
||||
|
||||
2. `silent-release` was not consistently writable by the real service identity, and the credential helper parent directory blocked `aiman` traversal. The persisted staging systemd overlay creates the state directory as `aiman:gitops` mode `0750` and grants only `u:aiman:--x` on `/usr/local/libexec`; no world-writable mode was used. The staging bridge also has the minimum repository write path required by the governed AuthorityGitExecutor/CAS flow.
|
||||
|
||||
3. Release version parsing was split across callers and rejected `V2R2C1`. A shared canonical parser now accepts `^V[0-9]+R[0-9]+C[0-9]+$` plus the existing bounded suffix form, and is used by capabilities, release candidate, consistency, acceptance, tag publication, and release/tag queries.
|
||||
|
||||
4. The runtime operation contract required `files` but the published Action schema omitted it. `commitFilesGoverned` now has one contract source and published schema projection, with parity tests. A real governed two-file commit completed on isolated branch `agent/action-contract-integration-20260825-1407`; authority, Git remote, and Gitea API all read back OID `0345cd8c70967940bc8e9132dff7d6ea11efa304`.
|
||||
|
||||
5. `reconcileGitOpsJob` reconstructed active lease state before checking terminal state. Terminal `COMPLETED`, `FAILED`, and `CANCELLED` jobs now short-circuit to idempotent read-back; active jobs retain strict lease validation. The two-file job reconciled as `COMPLETED` and a second reconcile returned the same receipt.
|
||||
|
||||
6. `getDiff` returned unbounded patch data and could fail the transport. It now returns identities, changed paths, stats, total bytes, bounded patch output, patch limit, and `truncated`. The large smoke returned `total_size_bytes=350222`, `stdout_bytes=262144`, `patch_limit_bytes=262144`, `truncated=true`; no `ResponseTooLargeError` or `GIT_OUTPUT_LIMIT_EXCEEDED` escaped.
|
||||
|
||||
During live integration, two additional staging-only contract defects were found and repaired: CREATE_NEW branch normalization/CAS recovery, and release executor projection of the configured staging baseline plus immutable runtime `versions/V2R2C1.json`. The latter removed the missing publication-workspace baseline/version errors without writing production state.
|
||||
|
||||
## Source, test, and operational changes
|
||||
|
||||
Source commits on the governed branch include the six contract repairs, focused regression tests, `versions/V2R2C1.json`, governed CREATE_NEW/reconcile recovery, and final runtime projection commits. The final source before this evidence commit is `2ec49005bde44f6981b14351500847d594e0276c`.
|
||||
|
||||
The runbook update is in `runbooks/agent-fix-action-contracts-20260825.md`. This report is the required durable evidence artifact. Existing untracked `runtime/agent-observability/` and `runtime/task-center/` directories were preserved and were not staged.
|
||||
|
||||
Tests run on the final source:
|
||||
|
||||
```text
|
||||
PYTHONPATH=active-runtime/app python3 -m pytest -q tests/test_silent_release_execution_readiness.py tests/test_silent_release_controller.py tests/test_silent_release_hardening.py tests/test_silent_release_production_contract.py tests/test_chatgpt_actions_tag.py tests/test_gitea_tag_publication.py tests/test_authoritative_git_context.py
|
||||
264 passed, 28 subtests passed in 4.78s
|
||||
|
||||
PYTHONPATH=active-runtime/app python3 -m pytest -q tests
|
||||
717 passed, 2 skipped, 154 subtests passed, 2 failed in 33.98s
|
||||
```
|
||||
|
||||
The full-suite failures remain the known event-bus fixture failure and the real signer adapter self-test (`returncode=42`); no new mandatory-suite regression was observed. Focused contract/reconcile tests and the exact mandatory suite passed.
|
||||
|
||||
## Staging deployment identity
|
||||
|
||||
- Final deployed source OID at the last completed runtime smoke: `2ec49005bde44f6981b14351500847d594e0276c`.
|
||||
- Final deployed artifact: `/opt/aios/gitops-model-api/2ec49005bde44f6981b14351500847d594e0276c-action-contract-repair/runtime`.
|
||||
- Artifact SHA256: `f67aed6cc0cce1f08197485c3eea204d3ef4d3989f44dc98e8ea2691e5886cbf`.
|
||||
- Deployment state: `STAGING`; production-deployed flag: `false`.
|
||||
- A lexically highest staging-only systemd drop-in was installed for each affected service, followed by `daemon-reload` and restart. `systemctl is-active` returned `active` for both services, and `systemctl show` confirmed the final OID, artifact SHA, API URL, and baseline authority.
|
||||
|
||||
## Runtime smoke evidence
|
||||
|
||||
- Model health returned `status=ok`, `version=V2R2C1`, final commit/artifact identity, `deployment_state=STAGING`, and `production_deployed=false`.
|
||||
- Bridge/API readback was available; the bridge's `/health` path is not exposed by this runtime and returned `404`, while its governed endpoints were healthy.
|
||||
- `getReleaseConsistency("V2R2C1", ...)` returned structured `status=PASS`, with Gitea listing/peeled target and tag object matching the stable reference.
|
||||
- `runReleaseAcceptance(...)` entered policy evaluation and returned structured `accepted=false`; it did not fail URL validation. The independent pre-existing tag publication state is `REMOTE_PUSH_PENDING`, with the remote rejection explicitly reporting protected tag `V2R2C1`.
|
||||
- `getTagPublicationStatus("V2R2C1")` returned structured `REMOTE_PUSH_PENDING`, not `invalid release version`.
|
||||
- `getReleaseSaga` for a nonexistent candidate returned HTTP `404` with `status=NOT_FOUND`, `state=NOT_FOUND`, `execution_enabled=false`, and no filesystem permission error.
|
||||
- `commitFilesGoverned` published schema includes required `files`, with per-file `path` and `content_base64`.
|
||||
- Two-file governed commit: branch `agent/action-contract-integration-20260825-1407`, OID `0345cd8c70967940bc8e9132dff7d6ea11efa304` at authority/Git remote/API; protected-ref flags remained false.
|
||||
- Terminal reconcile: `COMPLETED` read-back was idempotent across two calls; focused tests cover `FAILED` and `CANCELLED` terminal semantics.
|
||||
- Small diff returned bounded non-truncated output; empty diff returned zero paths and zero bytes; large diff returned bounded/truncated output as recorded above.
|
||||
- Main, protected tag, baseline registry, and production OIDs were re-read after deployment and remained unchanged.
|
||||
|
||||
## Restart persistence and remaining risk
|
||||
|
||||
The final staging services were restarted after deployment and health/runtime identity were re-read. The post-restart `systemctl is-active` result was `active` for both services; model health again reported OID `2ec49005bde44f6981b14351500847d594e0276c`, artifact SHA `f67aed6cc0cce1f08197485c3eea204d3ef4d3989f44dc98e8ea2691e5886cbf`, staging mode, and `production_deployed=false`. Post-restart consistency remained `PASS`, acceptance remained structured `accepted=false` for the pre-existing protected-tag publication state, saga remained `NOT_FOUND` for the nonexistent candidate, and the large diff remained bounded/truncated. The task cannot be promoted to `SUCCEEDED` until the protected-tag publication state and the two known repository-wide failures are resolved through their respective governed owners. No automatic rollback was performed because the staging services stayed healthy, mandatory tests passed, Gitea readback passed, and protected-ref boundaries remained intact.
|
||||
|
||||
Task disposition is `NEEDS_REWORK`, not `SUCCEEDED`: the staging contract repair is materially complete, but the deployed acceptance result is not all-green and the task row has not been legitimately claimed/verified by the online task worker.
|
||||
|
||||
## External Action Surface final closure evidence — 2026-08-25
|
||||
|
||||
### Disposition
|
||||
NEEDS_REWORK. Staging is deployed and P0-A/P0-B have live closure evidence. P0-C is blocked: no formal staging external Action bearer issuance path was available, so the required real public two-file commit and terminal reconcile were not authorized or executed. Do not mark SUCCEEDED. No main, tag, baseline, or production write occurred; untracked runtime/agent-observability and runtime/task-center were preserved.
|
||||
|
||||
### Identity and before-change facts
|
||||
Authority /data/aios-gitops/repo.git; worktree /var/lib/aios-gitops/bridge-v2-staging/worktrees/fix-action-contracts-20260825-1407; branch agent/fix-action-contracts-20260825-1407; initial HEAD 35eec9afe1432e8466d60040b2fb1049bb41242a1. Stable V2R2C1 source 998d30304787e31e5ae607c0bd86b5edb2b0e5ad; evidence closure a8b906d1bc24088c19647e98de6a679268f6d0a2. Repair commit 174e64dd0218cef6d49dd13d58bbd90c78fecadd; protected refs unchanged.
|
||||
|
||||
### P0-A governed-read ownership
|
||||
Root cause: generic /api/ sent governed-write-capabilities to model API 18893 (404), while governed facade 18890 owned it. Fix: ops/gitops-migration/bind_external_action_surface_final_staging.sh installs exact locations for governed-write-capabilities, control-plane-snapshot, online-agent-task, and online-agent-task-events to 18890; generic /api/ remains 18893; auth headers forward and no business host is hard-coded. Backup /data/aios-gitops/backups/action-surface-final-20260825T101714Z; log /data/aios-gitops/logs/action-surface-final-20260825T101714Z.log. nginx -t passed, Nginx active, public GET /api/governed-write-capabilities HTTP 200. Contract reports governed writes enabled but legacy/main/tag/baseline/production writes false.
|
||||
|
||||
### P0-B release semantics
|
||||
Root cause: public model GET used local TagPublisher/PublicationStore lacking tag object binding, so consistency was FAIL/tag_object=false; Bridge v2 had authoritative durable binding. Fix: active-runtime/app/aios_model_api_staging.py constructs one canonical publication request and routes release-consistency/release-acceptance through Bridge v2 getReleaseConsistency/runReleaseAcceptance; tests/test_action_contract_regressions.py covers this. Live V2R2C1 consistency with target 998d30304787e31e5ae607c0bd86b5edb2b0e5ad, closure a8b906d1bc24088c19647e98de6a679268f6d0a2, plan sha256:c0df52008ae7f64cec5ee2d28947aa7b892066c670ab8295e4549140b1a7500e returned HTTP 200 PASS, all checks true, tag object 07fc2746b688f5f243f29b39de39f32edc3dd9d2 and peeled target correct. Acceptance entered structured policy evaluation with accepted=false, not URL failure. Tag publication V2R2C1 returned structured UNKNOWN, not invalid version.
|
||||
|
||||
### P0-C credential and commit blocker
|
||||
Hash-only Action record: account chatgpt-gitops-bot; id chatgpt-action-0a3e55b7659a4d4e8125feabce5e8bf5; kind gpt_action_api_key; consumer aios-gitops-model-api.service; issuer owner_ssh_breakglass_rotation; issued 2026-08-10T04:51:58.900488Z; expires 2026-09-09T04:51:58.900488Z; scopes file:write and agent-task:control; disabled false; owner approval required true. Plaintext was not printed/reused. agent_task_control_token is not an Action bearer. Inspected Writer grants, Gitea consumer, SSH, task broker and old token candidates provide no formal issuer; no unrelated credential substituted. Empty public POST /api/commitFilesGoverned reached staging and returned HTTP 423 gitops_writes_disabled with AIOS_GITOPS_WRITES_ENABLED=false. Writes were not enabled. No real public two-file commit or COMPLETED reconcile is claimed. Blocker: FORMAL_STAGING_ACTION_BEARER_ISSUANCE_NOT_AVAILABLE.
|
||||
|
||||
### Schema/deployment/runtime
|
||||
Source 174e64dd0218cef6d49dd13d58bbd90c78fecadd. Artifact /data/aios-gitops/artifacts/action-contract-final-174e64d/aios-v2r2c1-model-api-174e64dd0218cef6d49dd13d58bbd90c78fecadd.tar.gz; SHA256 8fc811cfb9dbb22d6eb7ca418d58f9ada1d6fdd12e566e3e8f5a02bec47c4f37. Runtime /opt/aios/gitops-model-api/174e64dd0218cef6d49dd13d58bbd90c78fecadd-action-surface-final/runtime. Drop-in /etc/systemd/system/aios-gitops-model-api-v2r2c1-staging.service.d/zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz-action-contract-zzzz-final-999.conf; backup /data/aios-gitops/backups/action-contract-final-deploy-20260825T101959Z/drop-in-directory. User/Group aiman:gitops; API base from systemd https://g.cnnetmkt.top/git/api/v1; writes false; Bridge 18892; STAGING; production_deployed=false. /api/run proved active runtime/readable authority /data/aios-gitops/repo.git and main 3244f0f17f8845592ac94d585f5ebd65693c9f29. /api/openapi.yaml required commitFilesGoverned files, each with path/content_base64.
|
||||
|
||||
### Tests
|
||||
Before mandatory: 264 passed, 28 subtests, 4.82s. After mandatory: 264 passed, 28 subtests, 4.80s. Focused action regression: 11 passed, 0.12s. Full: 719 passed, 2 skipped, 154 subtests, 2 failed, 34.03s. Same known failures: stale /tmp/aios-agent-events-test in test_unified_event_flow; signer adapter self-test return 42 in test_real_signer_help_and_self_test_are_available.
|
||||
|
||||
### Restart and smoke
|
||||
After first deployment, model and Bridge staging services were restarted and remained active. Post-restart health retained source/artifact identity, V2R2C1, STAGING, production false. Capability HTTP 200; consistency HTTP 200/PASS; tag status structured UNKNOWN; nonexistent saga HTTP 404/NOT_FOUND with execution false, shadow true, side effects false. Empty diff HTTP 200, zero paths/size, truncated false. Bounded non-empty diff returned identities, paths/stats, bounded output and patch limit 262144; local pipe-to-head caused only expected curl broken-pipe. Existing large-diff behavior remains bounded/truncated with no transport exception. Gitea readback proven by consistency PASS; protected-ref boundary remained fail-closed.
|
||||
|
||||
### Task continuity and remaining work
|
||||
Earlier execution observed TASK_NOT_FOUND and created continuation fix-action-contracts-20260825-1407-external-surface-closure with parent/source/OID and staging constraints. Later recheck returned parent HTTP 200 QUEUED; continuation also QUEUED, revision 1, claimed_by null, result null. Neither has claim, execution, terminal result, or success evidence. Required rework is formal bearer lifecycle, isolated real two-file public commit and OID/reconcile verification, disposition of the two pre-existing full-suite failures, then full smoke before SUCCEEDED.
|
||||
### Health endpoint clarification
|
||||
|
||||
The service health contract is /api/health: local model port 18893 and public https://cnnetmkt.top/api/health both returned HTTP 200 with the deployed source/artifact identity, STAGING, and production_deployed=false. Public root /health returned HTTP 502 because the existing Nginx root location proxies the separate portal upstream on 127.0.0.1:3000; it is not the Action model health route. This unrelated portal-ingress 502 is recorded as an observed remaining staging risk, and was not changed because this task scope is the Action/Bridge/release surface.
|
||||
|
||||
\n
|
||||
### Formal task-state boundary
|
||||
|
||||
The deployed Task API exposes verification decisions SUCCEEDED, NEEDS_REWORK, and FAILED only through POST /v1/tasks/{id}/verify while the task is VERIFYING. Both the parent and continuation were QUEUED with no claim, so a direct NEEDS_REWORK transition was not a legal API operation. No cancel, database edit, fake claim, or lifecycle bypass was performed. This report is the authoritative disposition for this run: NEEDS_REWORK.
|
||||
|
||||
\n
|
||||
@@ -1,92 +0,0 @@
|
||||
# Action 最小自治修复闭环证据(2026-08-25)
|
||||
|
||||
## 最终状态
|
||||
|
||||
`BLOCKED`(staging 代码/配置已部署并健康,但缺少本次可用的正式 Action bearer,未宣称真实 governed commit 或完整外部 smoke 成功)。
|
||||
|
||||
本轮没有写入 production、`main`、release tag 或 baseline。
|
||||
|
||||
## 修改前事实
|
||||
|
||||
- repository: `aios/aios`
|
||||
- branch: `agent/fix-action-contracts-20260825-1407`
|
||||
- 修改前 HEAD: `d7a0d0db09826d513cb19451a4f018c998c00191`
|
||||
- production baseline: `V2R2C1`
|
||||
- baseline source commit: `998d30304787e31e5ae607c0bd86b5edb2b0e5ad`
|
||||
- Action schema 已限制为 26 operations,但没有外部 read-source/lease 入口;Bridge lease 主要是进程内 runtime binding;Bridge 未做 operation-specific bearer 校验。
|
||||
- 真实 staging model-api source/artifact 在本轮前为 `7e5525cfcbbaa3898c2e5ed3dc9c13e321908e61` / `2163c2e0467f3bd0a97f8d2b95e3277391c47dcf3ebafb8fa372a01c3f530ac0`。
|
||||
|
||||
## 根因与修复
|
||||
|
||||
1. Autonomous Agent 没有安全 read seam:增加 `AuthorityGitExecutor.read_file` 和 `readRepositoryFile`,只读 authoritative bare Git object database,固定响应上限并返回 resolved commit/OID、size、SHA-256、base64。
|
||||
2. Lease 没有跨重启 durable binding:增加 `ScopedLeaseStore` SQLite CAS 状态,绑定 task/repository/branch/expected OID/generation/TTL,支持同 binding 幂等、冲突、过期和 USED replay;commit 先校验 lease,再走既有 detached worktree/Job Controller/Authority CAS chain。
|
||||
3. Lease 曾可由调用者声明治理身份:现在必须命中 durable task binding,公开路径只接受 `CONTINUE_EXISTING`,并要求 expected OID 等于当前 authority branch head。
|
||||
4. Auth scope 曾混合:Bridge 按 read/lease/commit operation 分别检查 scope;model-api facade 认证后透传 bearer。
|
||||
5. runtime contract 与 published schema:增加 read/lease operation,保留 `commitFilesGoverned.files[] = {path, content_base64}`,builder 将 `scoped_lease_store.py` 纳入 immutable artifact。
|
||||
|
||||
## 修改文件与配置
|
||||
|
||||
- `active-runtime/app/aios_authority_git_executor.py`:安全 ref/path/size/read helper。
|
||||
- `active-runtime/app/scoped_lease_store.py`:SQLite durable lease state。
|
||||
- `active-runtime/app/aios_chatgpt_bridge_v2.py`:read operation contract。
|
||||
- `active-runtime/app/aios_chatgpt_bridge_v2_server.py`:read route、task binding、lease store、Bearer/scope matrix、structured errors。
|
||||
- `active-runtime/app/aios_model_api_staging.py`:认证 facade 与 Bridge control proxy。
|
||||
- `docs/gitops/openapi-chatgpt-actions.yaml`:新增 `readRepositoryFile`、`acquireWriterLease`,公开 operation 数 28。
|
||||
- `scripts/build_v2r2c1_model_api_staging.py`:纳入 `scoped_lease_store.py`。
|
||||
- `tests/test_minimum_autonomous_loop.py`:read/path/size、contract、lease 幂等/冲突测试。
|
||||
- `runbooks/agent-minimum-autonomous-loop-20260825.md`:部署与验收手册。
|
||||
- `deploy/*minimal-autonomous-loop.conf`:待随最终 source OID 渲染的 staging unit 配置模板;实际 drop-in 使用 systemd `LoadCredential` 投影 `/data/aios-gitops/runtime/secrets/gitops.tokens`,不复制 token。
|
||||
|
||||
## Git 与构建结果
|
||||
|
||||
- 第一实现提交:`f3a4485be7c803c3769c518578cf4bf86db32c6e`。
|
||||
- 绑定与 scope 收紧提交:`04b69beb369365a1522268e16c3ac7cd1dd745ce`。
|
||||
- 最终实现/部署 source OID:`9f32b26eba5bdaaa0e7c89042ce336426d465dbd`。
|
||||
- build artifact:`/var/lib/aios-gitops/bridge-v2-staging/candidate-artifacts/min-autonomous-9f32b26/aios-v2r2c1-model-api-9f32b26eba5bdaaa0e7c89042ce336426d465dbd.tar.gz`
|
||||
- artifact SHA-256:`ff2031b9ef8a39811c15086c2577d33cc6f187fd060136b7be7a8d6b4152e9f1`
|
||||
- artifact source OID:`9f32b26eba5bdaaa0e7c89042ce336426d465dbd`
|
||||
|
||||
## 测试与真实 staging 结果
|
||||
|
||||
已通过:
|
||||
|
||||
```text
|
||||
pytest -q tests/test_minimum_autonomous_loop.py tests/test_action_contract_regressions.py tests/test_bridge_v2_governed_http_bootstrap.py
|
||||
21 passed
|
||||
python3 -m py_compile ... # changed runtime modules
|
||||
git diff --check
|
||||
```
|
||||
|
||||
完整 mandatory suite(使用仓库需要的 `PYTHONPATH=.:services/aios-release-controller`)结果:
|
||||
|
||||
`724 passed, 2 skipped, 2 failed, 154 subtests passed`。
|
||||
|
||||
两个失败与本轮改动无关,和修改前已知基线一致:`tests/test_agent_event_bus.py::test_unified_event_flow` 受残留 `/tmp/aios-agent-events-test` 数据污染;`tests/test_signer_contract_compatibility.py::SignerContractCompatibilityTests::test_real_signer_help_and_self_test_are_available` 的已部署 signer self-test 返回码为 `42`。
|
||||
|
||||
已验证:
|
||||
|
||||
- `aios-chatgpt-bridge-v2-staging.service`: restart 后 active,ExecStart 指向 source `9f32b26...` runtime,PID `2061371`。
|
||||
- `aios-gitops-model-api-v2r2c1-staging.service`: restart 后 active,ExecStart 指向 source `9f32b26...` runtime,PID `2061686`。
|
||||
- `/api/health` 与 `/v2/runtime`: restart 后 HTTP 200,`STAGING`、`production_deployed=false`、runtime OID `9f32b26...`、artifact SHA `ff2031...`,`drift_status=PASS`。
|
||||
- 实际 staging `/api/openapi-chatgpt-actions.yaml`: HTTP 200,版本 `V2R2C1-chatgpt-actions-28ops`,28 个 `operationId`,含 `readRepositoryFile`、`acquireWriterLease`、`commitFilesGoverned`;`commitFilesGoverned.files` required 且每项 required `path`、`content_base64`。
|
||||
- 无 Bearer 的 model-api read 请求和 loopback Bridge read 请求均返回 HTTP 401;writes runtime flag 保持 false。
|
||||
- systemd effective User/Group 为 `aiman:gitops`;Gitea API 来源为 staging service effective `AIOS_GITOPS_GITEA_API_URL=https://g.cnnetmkt.top/git/api/v1` 与 Bridge `AIOS_GITEA_API_BASE=https://g.cnnetmkt.top/git/api/v1`,不是业务代码硬编码。
|
||||
- effective silent-release root 为 `/var/lib/aios-gitops/model-api-staging/silent-release`,ownership/mode 为 `aiman:gitops 750`,父目录同为 `aiman:gitops 750`;旧报错路径 `/var/lib/aios-gitops/silent-release` 不存在,未被错误地当作当前 runtime 路径。
|
||||
- systemd 使用 `LoadCredential=action_tokens:/data/aios-gitops/runtime/secrets/gitops.tokens` 和 `%d/action_tokens` 投影;registry 文件 `root:root 600`,未打印或复制 bearer。
|
||||
- 当前 token registry 是 hash-only 记录;本次没有打印、重用 Gitea/SSH/service token,也没有启用 dev auth bypass。
|
||||
|
||||
重启后的 service restart acceptance 已完成:URL、权限、Action schema、version parser 代码产物和 writes=false 均保持有效;production service 未重启。
|
||||
|
||||
未通过/未执行:
|
||||
|
||||
- 无法执行正式 bearer 下的 `read -> lease -> commitFilesGoverned`,因此没有伪造两文件 commit OID、lease USED、Gitea Git/API readback 或 idempotency replay 证据。
|
||||
- 未执行临时 writes=true governed commit;staging 最终保持 `AIOS_GITOPS_WRITES_ENABLED=false`。
|
||||
- 未宣称完整 Action smoke、restart 后 governed commit 或 `TASK_VERIFIED`。
|
||||
|
||||
## 保护边界
|
||||
|
||||
本轮只安装 staging artifact/drop-in;production service 未重启。`main`、`V2R2C1` tag、baseline target/evidence closure 未写入。两个既有 untracked 目录 `runtime/agent-observability/`、`runtime/task-center/` 原样保留。
|
||||
|
||||
## 剩余风险与下一步
|
||||
|
||||
主要闭环阻塞是:需要 Owner/正式 Action broker 提供当前有效 bearer(不在聊天中传递)。此外 mandatory suite 仍有上述两个已知环境/部署失败。拿到 bearer 后应从当前 branch HEAD 重新读取 source OID,按 runbook 执行一次真实两文件 governed commit、Gitea 三方 OID readback、idempotency/stale-OID 负例、staging restart 后复测;在此之前 Task 必须保持 `BLOCKED/NEEDS_REWORK`,不能标记 `SUCCEEDED`。
|
||||
@@ -1,224 +0,0 @@
|
||||
# AIOS Action OpenAPI 操作数上限修复证据
|
||||
|
||||
## 结论
|
||||
|
||||
staging 上的 `https://cnnetmkt.top/api/openapi-chatgpt-actions.yaml` 已从 32 个
|
||||
实际 OpenAPI operations 收缩到 26 个,低于 ChatGPT Action 的 30 操作限制。
|
||||
公网重新抓取返回 HTTP 200,schema version 为
|
||||
`V2R2C1-chatgpt-actions-26ops`。`commitFilesGoverned` 仍是公开的批量 governed
|
||||
writer,并且现在在 OpenAPI 中显式要求 `bearerAuth`、标记为
|
||||
`x-openai-isConsequential: true`,required `files` 契约保持一致。
|
||||
|
||||
本次只修改 branch/staging overlay;没有写入 production service、main、release
|
||||
tag 或 baseline registry。ChatGPT Action 编辑器仍需要重新导入或刷新这个 URL,
|
||||
因为客户端可能缓存旧的 32-operation schema。
|
||||
|
||||
## 修改前事实
|
||||
|
||||
- Repository:`aios/aios`
|
||||
- Branch:`agent/fix-action-contracts-20260825-1407`
|
||||
- 修复前 branch tip:`767c7ff6a975fe18a701b95cd6dacca8600eddc0`
|
||||
- 本轮最终 HEAD:`7e5525cfcbbaa3898c2e5ed3dc9c13e321908e61`
|
||||
- staging model-api unit:`aios-gitops-model-api-v2r2c1-staging.service`
|
||||
- staging model-api port:`127.0.0.1:18893`
|
||||
- staging Bridge port:`127.0.0.1:18892`
|
||||
- systemd Gitea API URL:`https://g.cnnetmkt.top/git/api/v1`
|
||||
- 当前 service User/Group:`aiman:gitops`
|
||||
- 修复前公网 schema:HTTP 200,24,721 bytes,SHA256
|
||||
`a0775b0719a76e08a95f3257a3d3b2a73b70e1c55c162914250f80dd28da022d`;30 paths、
|
||||
32 operations。两个 path 同时有多个 method,因此 path 数不是 operation 数。
|
||||
- 修复前触发错误:`OpenAPI 规范最多可以包含 30 个操作`。
|
||||
|
||||
## 根因与决策
|
||||
|
||||
根因不是 URL host 或 YAML 传输错误,而是公开 Action projection 中混入了旧式
|
||||
Git 写原语和同义 approval alias。公开 schema 同时暴露 legacy primitives 与
|
||||
`commitFilesGoverned`,最终 operation 数为 32。
|
||||
|
||||
本次投影收缩为 26 个 operation:
|
||||
|
||||
- 先前修复中移除粗粒度旧别名 `POST /api/file` (`commitFile`);
|
||||
- 先前修复中移除当前 isolated-writer policy 明确禁止的 `POST /api/commit`
|
||||
(`commitChanges`);
|
||||
- 本轮移除 `submitSignedApproval`,因为它是 `submitOwnerApproval` 的 alias;
|
||||
- 本轮从 Actions projection 隐藏 `createPatch`、`createBranch`、
|
||||
`commitFileAtomic` 三个旧式 Git 写原语。runtime 兼容处理没有删除,canonical
|
||||
对外批量写入为 `/v2/commit-files`;
|
||||
- 保留 release candidate、release consistency、release acceptance、tag
|
||||
publication status、release saga、getDiff 和 recovery 相关既有能力,满足本任务
|
||||
的既有 smoke contract。尚未实现的 `getReleaseSnapshot`/`getReleaseVerification`
|
||||
聚合 API 不在本次冒险重构范围内。
|
||||
|
||||
此外,`commitFilesGoverned` 的 runtime fragment 生成器现在生成:
|
||||
|
||||
- `security: [{bearerAuth: []}]`;
|
||||
- `x-openai-isConsequential: true`;
|
||||
- `files.maxItems: 50`;
|
||||
- `idempotency_key` 的长度和字符约束。
|
||||
|
||||
## 修改文件与提交
|
||||
|
||||
- `docs/gitops/openapi-chatgpt-actions.yaml`:canonical Action projection,26-op
|
||||
allowlist、移除 legacy/alias、补齐 batch writer security。
|
||||
- `active-runtime/app/aios_chatgpt_bridge_v2.py`:runtime contract fragment 的
|
||||
单一生成来源与公开 security/batch constraints。
|
||||
- `tests/test_action_contract_regressions.py`:26-operation gate、legacy operation
|
||||
negative assertions、runtime/schema parity、bearer/consequential assertions。
|
||||
- `runbooks/action-openapi-operation-limit-20260825.md`:操作上限、projection
|
||||
allowlist、构建和刷新手册。
|
||||
- `ops/gitops-migration/bind_external_action_surface_final_staging.sh` 及先前的
|
||||
staging binding 测试/报告:本任务分支已将 `/v2/` 公开路由绑定到 staging Bridge
|
||||
`127.0.0.1:18892`,没有使用 production `18920`。
|
||||
|
||||
提交:
|
||||
|
||||
- `4313f3e44a1e4be69d2608fb1fc18833aa0c82e8`
|
||||
`fix(action): keep public schema within operation limit`
|
||||
- `7e5525cfcbbaa3898c2e5ed3dc9c13e321908e61`
|
||||
`fix(action): project governed core within 26 operations`
|
||||
|
||||
保留的未跟踪目录 `runtime/agent-observability/`、`runtime/task-center/` 未被加入
|
||||
提交或删除。
|
||||
|
||||
## 测试结果
|
||||
|
||||
修改后 focused regression:
|
||||
|
||||
```text
|
||||
13 passed in 0.15s
|
||||
```
|
||||
|
||||
包含既有 Action/release/staging focused tests:
|
||||
|
||||
```text
|
||||
32 passed, 11 subtests passed in 0.36s
|
||||
```
|
||||
|
||||
mandatory suite:
|
||||
|
||||
```text
|
||||
264 passed, 28 subtests passed in 4.79s
|
||||
```
|
||||
|
||||
完整 suite:
|
||||
|
||||
```text
|
||||
721 passed, 2 skipped, 2 failed, 154 subtests passed in 34.02s
|
||||
```
|
||||
|
||||
两个失败与本次变更无关且在修改前已复现:
|
||||
|
||||
1. `tests/test_agent_event_bus.py::test_unified_event_flow` 使用了残留的
|
||||
`/tmp/aios-agent-events-test`,已有 1 个旧 event,断言得到 2;
|
||||
2. `tests/test_signer_contract_compatibility.py::test_real_signer_help_and_self_test_are_available`
|
||||
的已部署 signer `self-test` 返回 42。`sign --help` 仍正常,live signer integration
|
||||
另行 skip。
|
||||
|
||||
没有出现由本次 schema/runtime 改动引入的 mandatory regression。
|
||||
|
||||
## staging 构建与部署
|
||||
|
||||
使用仓库现有流程:
|
||||
|
||||
```text
|
||||
scripts/build_v2r2c1_model_api_staging.py
|
||||
source_oid: 7e5525cfcbbaa3898c2e5ed3dc9c13e321908e61
|
||||
artifact: /data/aios-gitops/artifacts/action-openapi-limit-20260825-7e5525cf/aios-v2r2c1-model-api-7e5525cfcbbaa3898c2e5ed3dc9c13e321908e61.tar.gz
|
||||
artifact_sha256: 2163c2e0467f3bd0a97f8d2b95e3277391c47dcf3ebafb8fa372a01c3f530ac0
|
||||
deployment_state: STAGING
|
||||
```
|
||||
|
||||
systemd 新 drop-in 持久化了 artifact/runtime identity、Gitea URL、`STAGING`、
|
||||
`AIOS_GITOPS_WRITES_ENABLED=false`、`aiman:gitops` 和精确的 read/write paths。
|
||||
当前生效 runtime:
|
||||
|
||||
```text
|
||||
/opt/aios/gitops-model-api/7e5525cfcbbaa3898c2e5ed3dc9c13e321908e61-action-openapi-limit/runtime
|
||||
```
|
||||
|
||||
silent-release 权限在两次重启后均为:
|
||||
|
||||
```text
|
||||
/var/lib/aios-gitops/model-api-staging/silent-release aiman:gitops 750
|
||||
ACL: user::rwx, group::r-x, other::---
|
||||
```
|
||||
|
||||
部署前的原生 final drop-in 已备份至:
|
||||
|
||||
```text
|
||||
/data/aios-gitops/backups/action-openapi-limit-deploy-20260825T112700Z/
|
||||
```
|
||||
|
||||
第一次 restart 后 MainPID 为 `1775067`;第二次按要求 restart 后 MainPID 为
|
||||
`1788253`,两次均 active/running。
|
||||
|
||||
## 公网 Action smoke
|
||||
|
||||
最终公网抓取:
|
||||
|
||||
```text
|
||||
HTTP 200
|
||||
Content-Type: application/yaml; charset=utf-8
|
||||
bytes: 21553
|
||||
SHA256: 798cac0ebd40097c63e5e01ab52c9fdbc255707c4f3820b77161c83349cd5199
|
||||
info.version: V2R2C1-chatgpt-actions-26ops
|
||||
paths: 25
|
||||
operations: 26
|
||||
```
|
||||
|
||||
关键 operation contract:
|
||||
|
||||
```text
|
||||
commitFilesGoverned required:
|
||||
task_id, repository, expected_branch_oid, target_branch, generation,
|
||||
idempotency_key, files, message
|
||||
files item required: path, content_base64
|
||||
security: bearerAuth
|
||||
x-openai-isConsequential: true
|
||||
```
|
||||
|
||||
restart 后复测:
|
||||
|
||||
- `/api/health`:200,`status=ok`,`deployment_state=STAGING`,runtime OID 为
|
||||
`7e5525cf…`,artifact SHA 与 receipt 一致,`production_deployed=false`;
|
||||
- `/v2/runtime`:200,active,Bridge schema `aios.chatgpt-gitops-bridge.v2`;
|
||||
- `/v2/capabilities`:200,governed writes enabled、legacy/main/baseline writes
|
||||
false;
|
||||
- `/api/release-consistency?version=V2R2C1...`:200,`status=PASS`,包含
|
||||
Gitea listing/tag/OID readback;
|
||||
- `/api/release-acceptance?version=V2R2C1...`:200,进入 policy evaluation,
|
||||
`accepted=false` 是既有 acceptance policy 结果,不是 URL 校验错误;
|
||||
- `/api/tag-publication-status?version=V2R2C1`:200,结构化 `UNKNOWN` 状态;
|
||||
- `/getReleaseSaga?candidate_id=nonexistent-action-limit-20260825`:404,结构化
|
||||
`NOT_FOUND`/empty-state,不是权限错误;
|
||||
- empty diff:200,`total_size_bytes=0`、`truncated=false`;
|
||||
- non-empty diff:200,31 changed paths、208,639 bytes;
|
||||
- large diff:200,732 changed paths、3,577,251 bytes、`truncated=true`、patch
|
||||
bounded at 262,144 bytes,无 transport exception。
|
||||
|
||||
保护边界复测:
|
||||
|
||||
```text
|
||||
refs/heads/main = 3244f0f17f8845592ac94d585f5ebd65693c9f29
|
||||
refs/tags/V2R2C1 = 07fc2746b688f5f243f29b39de39f32edc3dd9d2
|
||||
service writes_enabled = false
|
||||
service deployment_state = STAGING
|
||||
```
|
||||
|
||||
main/tag/baseline registry/production 未被本次部署写入。
|
||||
|
||||
## 剩余风险与后续动作
|
||||
|
||||
- ChatGPT 客户端是否已刷新不能由 staging 服务端证明;请在 Action 编辑器重新导入
|
||||
URL。若仍显示旧数量,删除旧 schema 后重新导入,确认 `V2R2C1-chatgpt-actions-26ops`。
|
||||
- 完整 suite 的两个环境失败仍待独立清理 `/tmp` fixture 和修复 signer self-test;
|
||||
它们不是本次 Action schema 修复的回归。
|
||||
- 未来若实现正式 `getReleaseSnapshot`、`getReleaseVerification` 和 governed task
|
||||
Action projection,应单独设计/测试,不应通过隐藏本任务仍要求的 release read paths
|
||||
来制造假收缩。
|
||||
|
||||
## 状态
|
||||
|
||||
`STAGING_REPAIR_PASS`:公网 staging schema、runtime、release/Gitea readback、
|
||||
restart 后 smoke 和保护边界均通过;production 未触碰。外部 ChatGPT Action UI
|
||||
刷新仍是客户端侧动作,不作为服务端部署失败。
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"schema": "aios.bridge-v2-engineering-staging-acceptance.v1",
|
||||
"task_id": "TASK-P0-CHATGPT-BRIDGE-V2-CONTROL-PLANE-CONVERGENCE-20260809",
|
||||
"repository": "aios/aios",
|
||||
"branch": "agent/p0-chatgpt-bridge-v2-control-plane-convergence-20260809",
|
||||
"control_plane_release_version": "bridge-v2-aa0c37b8ab33",
|
||||
"control_plane_target_oid": "aa0c37b8ab333616e1bab9686cf6d10557f2ebda",
|
||||
"artifact_sha256": "08670c78cf760bfe693e3553e676eb751dadd7834116aa6d40e7c094f1357ae4",
|
||||
"runtime_path": "/opt/aios/gitops-control-plane/aa0c37b8ab333616e1bab9686cf6d10557f2ebda",
|
||||
"bridge_schema_version": "aios.chatgpt-gitops-bridge.v2",
|
||||
"deployment_state": "STAGING",
|
||||
"drift_status": "PASS",
|
||||
"restart_acceptance": {
|
||||
"pid_before": 3158850,
|
||||
"pid_after": 3159889,
|
||||
"runtime_response_equal": true
|
||||
},
|
||||
"governed_capabilities": {
|
||||
"legacy_writes_enabled": false,
|
||||
"governed_writes_enabled": true,
|
||||
"force_push": false,
|
||||
"main_write": false,
|
||||
"tag_write": false,
|
||||
"baseline_write": false,
|
||||
"production_write": false
|
||||
},
|
||||
"production_invariants": {
|
||||
"authority_main_oid": "2e8fa22989808a448065d1d76b5b18948774a637",
|
||||
"authority_tags_sha256": "bd2b6e30b76f28e7fcdcb447e7296690f0a65ad855209294c36b0f3f1d96098d",
|
||||
"baseline_current_sha256": "57651eb819584ab7c1d67f01b0ef66d6408cdc322ae5f6d4ff0aacd96f8327e1",
|
||||
"production_service_main_pid": 2816107,
|
||||
"production_service_nrestarts": 0,
|
||||
"production_service_active_enter_timestamp_monotonic": 2919386492273
|
||||
},
|
||||
"bridge_operation_sequence": {
|
||||
"createGovernedTask": "PASS",
|
||||
"acquireWriterLease": "PASS",
|
||||
"commitFilesGoverned": "REAL_GOVERNED_COMMIT",
|
||||
"getGitOpsJob": "PASS",
|
||||
"expected_branch_oid": "8fe3b85c1be592326473e81a502a23eeb9511d30",
|
||||
"generation": 7
|
||||
},
|
||||
"production_changed": false
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"schema": "aios.bridge-v2.1-durable-reconciliation.bootstrap-acceptance.v1",
|
||||
"task_id": "TASK-P0-BRIDGE-V21-DURABLE-RECONCILIATION-20260809",
|
||||
"repository": "aios/aios",
|
||||
"base_oid": "3f670c387692b8865a10d5b419468d8a0b64d7a4",
|
||||
"target_branch": "agent/p0-bridge-v21-durable-reconciliation-20260809",
|
||||
"branch_mode": "CREATE_NEW",
|
||||
"generation": 1,
|
||||
"implementation": "not_started",
|
||||
"production_changed": false,
|
||||
"required_proofs": [
|
||||
"absent_ref_cas",
|
||||
"observation_first_reconciliation",
|
||||
"authority_gitea_api_commit_equality",
|
||||
"commit_visible"
|
||||
]
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
# Runbook Addendum — External Action Connector Schema Refresh
|
||||
|
||||
This addendum is staging-only and applies to the `fix-action-contracts-20260825-1407` closure.
|
||||
|
||||
## Contract source
|
||||
|
||||
Use `active-runtime/app/aios_chatgpt_bridge_v2.py` as the runtime source of required fields. Use `render_openapi_contract_fragment()` and `docs/gitops/openapi-chatgpt-actions.yaml` for the generated/published projection. `commitFilesGoverned` must require `files`, and each item must require `path` and `content_base64`.
|
||||
|
||||
The public OpenAPI server is the site root and its Bridge v2 paths are `/v2/...`. Install the route with `ops/gitops-migration/bind_external_action_surface_final_staging.sh`; it must target `127.0.0.1:18892`, preserve the Authorization headers, pass `nginx -t`, reload Nginx, and never target production `18920`.
|
||||
|
||||
## Connector lifecycle gate
|
||||
|
||||
The external Action connector must be refreshed through its supported registration or re-registration lifecycle. Record the connector identity, schema source URL, fetched schema digest, cache invalidation or registration acknowledgement, and a callable-tool inspection showing required `files`. Do not make a local fixture or a second hand-written schema a substitute for this evidence.
|
||||
|
||||
If the connector registration API, cache lifecycle, callable inspection, or formal staging Action bearer is unavailable, stop at `PENDING_EXTERNAL_CONNECTOR` and record `FORMAL_STAGING_ACTION_BEARER_ISSUANCE_NOT_AVAILABLE`. Never reuse Gitea, SSH, task-control, Writer, or old token credentials.
|
||||
|
||||
## Acceptance
|
||||
|
||||
After connector refresh, use the actual callable Action once to submit two files through `commitFilesGoverned` on an isolated `agent/*` branch. Verify the task/lease lineage, Authority ref, Git remote ref, and Gitea API branch OID are equal. Read the durable job, require `COMPLETED`, then call terminal reconcile and require an idempotent successful read-back. Restart only staging Action/Bridge/model services and repeat callable schema inspection and the batch/reconcile smoke.
|
||||
|
||||
Do not mark `SUCCEEDED` until the callable schema and batch evidence exist. If refresh breaks health, routes, auth, schema, or protected-ref boundaries, restore the recorded Nginx backup and previous staging artifact through the governed deployment procedure, then diagnose.
|
||||
@@ -1,58 +0,0 @@
|
||||
# ChatGPT Action OpenAPI 操作数上限运行手册
|
||||
|
||||
## 目的
|
||||
|
||||
`https://cnnetmkt.top/api/openapi-chatgpt-actions.yaml` 必须保持不超过 ChatGPT
|
||||
Action 导入支持的 30 个实际操作;当前投影硬门槛收紧为 26,为未来治理、诊断
|
||||
和任务协议保留余量。OpenAPI 中同一路径的多个 HTTP method 分别计数;路径数量
|
||||
不等于操作数量。
|
||||
|
||||
## 单一来源与构建
|
||||
|
||||
规范唯一来源是 `docs/gitops/openapi-chatgpt-actions.yaml`。模型 API staging
|
||||
构建脚本 `scripts/build_v2r2c1_model_api_staging.py` 将该文件复制到 immutable
|
||||
artifact,并同时校验 `/v2/commit-files` runtime contract。禁止直接编辑已部署
|
||||
artifact 或 production 文件。
|
||||
|
||||
变更后至少执行:
|
||||
|
||||
```bash
|
||||
python3 - <<'PY'
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
doc = yaml.safe_load(Path('docs/gitops/openapi-chatgpt-actions.yaml').read_text())
|
||||
methods = {'get', 'post', 'put', 'patch', 'delete', 'head', 'options'}
|
||||
operations = [(p, m) for p, item in doc['paths'].items() for m in item if m in methods]
|
||||
assert len(operations) <= 26, len(operations)
|
||||
print(f'paths={len(doc["paths"])} operations={len(operations)}')
|
||||
PY
|
||||
PYTHONPATH=active-runtime/app python3 -m pytest -q tests/test_action_contract_regressions.py
|
||||
```
|
||||
|
||||
## 公开面选择
|
||||
|
||||
公开 schema 保留受治理的 `/v2/commit-files` 以及 release、
|
||||
tag publication、consistency、acceptance、saga 和 diff 操作。粗粒度旧别名
|
||||
`/api/file`、`/api/commit`、`/api/branch`、`/api/patch` POST、`/api/commit-file`
|
||||
以及 `/submitSignedApproval` 等旧别名/旧写原语不得重新加入公开 Action schema;
|
||||
批量写入使用 `/v2/commit-files`。完整 runtime 兼容路由不因此删除。
|
||||
|
||||
`commitFilesGoverned` 必须显式声明 `security: [{bearerAuth: []}]` 和
|
||||
`x-openai-isConsequential: true`;schema 与 Bridge runtime 的 required fields、
|
||||
batch limits 必须由同一生成链维护。
|
||||
|
||||
## 部署与复验
|
||||
|
||||
只使用 `scripts/build_v2r2c1_model_api_staging.py` 生成 staging artifact,保留
|
||||
当前 systemd drop-in 备份,更新 staging model-api 的 artifact 路径后执行
|
||||
`daemon-reload` 和 staging unit restart。部署后从公网重新抓取 schema,验证:
|
||||
|
||||
- HTTP 200,Content-Type 为 YAML;
|
||||
- 实际操作数为 30 或更少;
|
||||
- `commitFilesGoverned` 仍包含 required `files`,每项包含 `path`、`content_base64`;
|
||||
- `/v2/runtime`、capabilities、release consistency/acceptance、tag status、
|
||||
saga empty-state、diff small/empty/large smoke 均正常;
|
||||
- staging unit active,production/main/tag/baseline 未写入。
|
||||
|
||||
Action 客户端可能缓存旧规范。公网 schema 复验通过后,在 ChatGPT Action 编辑器
|
||||
重新导入该 URL 或执行刷新;服务端无法替代客户端已保存的旧 schema cache。
|
||||
@@ -1,225 +0,0 @@
|
||||
# Agent Execution Contract — Action Contract Regression Repair
|
||||
|
||||
## Objective
|
||||
|
||||
Fully repair the current AIOS Action runtime/contract overlay regressions on the single server, without modifying protected refs directly and without introducing new infrastructure. The task is not complete until the deployed staging/action overlay passes all acceptance gates.
|
||||
|
||||
## Authority and scope
|
||||
|
||||
- Repository: `aios/aios`
|
||||
- Base at task creation: `3244f0f17f8845592ac94d585f5ebd65693c9f29`
|
||||
- Governed task: `fix-action-contracts-20260825-1407`
|
||||
- Target branch: `agent/fix-action-contracts-20260825-1407`
|
||||
- Protected refs must not be directly written: `main`, release tags, baseline registry, production runtime.
|
||||
- No new SaaS, database, agent framework, or monitoring platform may be introduced.
|
||||
|
||||
## Non-interactive rules
|
||||
|
||||
The Agent must run the whole flow unnattended:
|
||||
|
||||
1. Collect facts.
|
||||
2. Determine root causes.
|
||||
3. Make the smallest correct changes.
|
||||
4. Run unit/integration/contract tests.
|
||||
5. Deploy to staging only.
|
||||
6. Restart only the affected non-production services.
|
||||
7. Run the full Action smoke suite.
|
||||
8. On failure, automatically collect logs, diagnose, fix, and retry.
|
||||
9. If a change causes a new regression, automatically roll back the staging change to the previous known-good configuration and record the failure.
|
||||
10. Stop only if an owner decision is required for a high-risk, irreversible, or production-boundary action.
|
||||
|
||||
## Fact collection — required before editing
|
||||
|
||||
Record all of the following in the final evidence bundle:
|
||||
|
||||
- `id`, `hostname`, `uname -a`, `date --iso-seconds`
|
||||
- `git rev-parse --show HEAD` for authority worktree and running overlay source
|
||||
- `git status --porcelaine=v2`
|
||||
- `git remote -v`
|
||||
- current systemd service unit(s), drop-ins, Environment/EnvironmentFile sources for GitOps/Bredge/release services
|
||||
- `systemctl show <affected-service>` including `User=`, `Group=`, `Environment=`, `EnvironmentFile=`, `ExecStart=`
|
||||
- resolved Gitea API base URL after env/config expansion; redact secrets but not scheme/host
|
||||
- `stat -c, `namei -l`, `getfacl`, als -ld on `/var/lib/aios-gitops/silent-release` and its parents
|
||||
- find Action OpenAPI/schema generator and runtime operation definitions for `commitFilesGoverned`
|
||||
- find the release version validator(s) and all callers of `getTagPublicationStatus`
|
||||
- find `reconcileGitOpsJob` implementation and durable binding validation logic
|
||||
- find `getDiff implementation and transport output limits
|
||||
|
||||
Do not edit any file until the actual implementation and configuration sources have been located.
|
||||
|
||||
## Repair 1 — Gitea API URL
|
||||
|
||||
Symptoms:
|
||||
|
||||
- `getReleaseConsistency` → `Gitea API URL must be HTTP(S)`
|
||||
- `runReleaseAcceptance` → `Gitea API URL must be HTTP(ÊX
|
||||
|
||||
Required behavior:
|
||||
|
||||
- Determine which env/config key is projected into the current contract overlay.
|
||||
- Compare the deployed overlay with V2R2C1 known-good configuration/deployment manifests.
|
||||
- Restore a valid `HTTP://` or `HTTPS://` Gitea API base URL.
|
||||
- Add startup config validation so invalid schemes fail at health/startup with a config-specific message, not during a release check.
|
||||
- Never hard-code a different Gitea host if the existing deployment already has a single authoritative source.
|
||||
|
||||
## Repair 2 — durable release state permissions
|
||||
|
||||
Symptom:
|
||||
|
||||
- `getReleaseSaga` → `Permission denied: '/var/lib/aios-gitops/silent-release'`
|
||||
|
||||
Required behavior:
|
||||
|
||||
- Identify the actual runtime service User/Group.
|
||||
- Grant only the required traverse/read/write permissions for the durable state directories the service must use.
|
||||
- Prefer ownership + group mode or a specific ACL; keep the directory non-world-writable.
|
||||
- Persist the permission in deployment/install logic so restart/reboot does not regress.
|
||||
- Verify create/read/update of a staging-only saga state file under the service identity.
|
||||
|
||||
## Repair 3 — release version contract
|
||||
|
||||
Symptom:
|
||||
|
||||
- `getTagPublicationStatus("V2R2C1")` → `invalid release version`
|
||||
- The same runtime exposes `V2R2C1` as `approved_release_version`.
|
||||
|
||||
Required behavior:
|
||||
|
||||
- Locate all version validators; consolidate onto one canonical parser.
|
||||
- Accept the AIOS canonical namespace `^V[0-9]+R[0-9]+C[0-9]+$`.
|
||||
- Preserve any additional already-supported legacy formats unless they are security-sensitive.
|
||||
- Add contract tests proving that the version accepted by capabilities is accepted by status, candidate, consistency, acceptance, and tag publication.
|
||||
|
||||
## Repair 4 — `commitFilesGoverned` schema parity
|
||||
|
||||
Symptom:
|
||||
|
||||
- Runtime capability metadata requires `files`.
|
||||
- Published Action tool schema does not expose `files`.
|
||||
- Call reaches Bridge and fails `BRIDGE_REQUEST_FIELDS_MISSING`.
|
||||
|
||||
Required behavior:
|
||||
|
||||
- Find the canonical runtime operation contract.
|
||||
- Generate the external tool schema from the same source of truth; do not manually copy a parallel schema.
|
||||
- `files` must be required and must represent a list of file objects with at least `path` and `content_base64`.
|
||||
- Add a parity test that compares runtime required fields with published Action required fields.
|
||||
- Add a real governed commit test that writes two test files to an isolated `agent/` ibranch and verifies remote OID.
|
||||
|
||||
## Repair 5 — terminal reconciliation
|
||||
|
||||
Symptom:
|
||||
|
||||
- A governed job read back as `COMPLETED' but `reconcileGitOpsJob` failed `DURABLE_BINDING_INVALID`.
|
||||
|
||||
Required behavior:
|
||||
|
||||
- Reconciling a terminal successful job must be idempotent.
|
||||
- An expired writer lease must not invalidate a durable binding for a job that is already terminal.
|
||||
- Active-job reconciliation may require a live lease; terminal read-back must not.
|
||||
- Add cases for COMPLETED, FAILED, CANCELLED / equivalent terminal states.
|
||||
|
||||
## Repair 6 — bounded `getDiff` output
|
||||
|
||||
Symptom:
|
||||
|
||||
- Large valid diffs fail with `ResponseTooLargeError` or `GIT_OUTPUT_LIMIT_EXCEEDED`.
|
||||
|
||||
Required behavior:
|
||||
|
||||
- Do not load unbounded diff text into the Action response.
|
||||
- Return bounded summary data: commit identities, changed paths/stats, total bytes, and `truncated: true` when the full patch exceeds the safe limit.
|
||||
- If pagination already exists in the contract use it; otherwise prefer deterministic truncation over a breaking schema change.
|
||||
- Add tests for small, empty, and oversize diffs.
|
||||
|
||||
## Staging deployment procedure
|
||||
|
||||
1. Run the existing mandatory test suite before modification; record baseline.
|
||||
2. Apply code and config changes only on the governed branch/worktree.
|
||||
3. Run focused regression tests.
|
||||
4. Run the full mandatory suite.
|
||||
5. Build the staging contract overlay using the repository's existing build/deploy path.
|
||||
6. Deploy to staging/non-production only.
|
||||
7. If systemd units are changed: `systemctl daemon-reload`, then restart only the affected staging services.
|
||||
8. Wait for the existing health endpoint/runtime status to become healthy.
|
||||
9. Run the acceptance suite below.
|
||||
|
||||
If any step fails:
|
||||
- collect `journalctl` logs and relevant app logs;
|
||||
- diagnose root cause;
|
||||
- automatically repair and retry when non-destructive;
|
||||
- if a new change breaks staging, restore the previous staging artifact/config and restart the affected service;
|
||||
- never silently continue after a failed gate.
|
||||
|
||||
## Acceptance suite
|
||||
|
||||
All of the following must pass on the same deployed staging overlay:
|
||||
|
||||
- Runtime status is `active` and healthy after restart.
|
||||
- Gitea Git/API readback works from the runtime service identity.
|
||||
- `getReleaseConsistency(V2R2C1, 998d30304787e31e5ae607c0bd86b5edb2b0e5ad, a8b906d1bc24088c19647e98de6a679268f6d0a2, approved_plan) returns a structured result and reaches evaluation.
|
||||
- `runReleaseAcceptance` for the same identities reaches policy evaluation, not URL validation error.
|
||||
- `getTagPublicationStatus("V2R2C1")` returns structured state, not `invalid release version`.
|
||||
- `getReleaseSaga` for a nonexistent candidate returns NOT_FOUND/empty-state semantics, not filesystem permission failure.
|
||||
- `commitFilesGoverned` exposes its required `files` parameter in the published Action schema.
|
||||
- A real two-file governed commit to an isolated `agent/` branch succeeds and remote branch OID matches.
|
||||
- Resuming a COMPLETED job returns the existing `JOB_TERMINAL` semantics or idempotent success as designed.
|
||||
- Reconciling a COMPLETED governed job is successful/idempotent and does not require an active lease.
|
||||
- Small/empty `getDiff still works.
|
||||
- Large `getDiff` returns bounded output with truncation metadata instead of a transport exception.
|
||||
- Existing protected-ref controls remain unchange: no direct main/tag/baseline/production write.
|
||||
|
||||
## Restart / reboot persistence
|
||||
|
||||
After the first full pass:
|
||||
|
||||
- Restart the staging Action/Bridge/release services one more time without changing files.
|
||||
- Rerun the acceptance suite.
|
||||
- Permissions, Gitea URL, and schema must still be correct after restart.
|
||||
- If the repository already has a safe staging reboot test, run it as well.
|
||||
|
||||
## Evidence and completion
|
||||
|
||||
Create a single durable report in the repository, e.g. `reports/action-contract-repair-evidence-20260825.md`, containing:
|
||||
|
||||
- pre-change facts
|
||||
- root cause for each regression
|
||||
- files changed and why
|
||||
- config/permission changes
|
||||
- test commands and exact results
|
||||
- staging deployment identity (commit/artifact/config digest)
|
||||
- restart-persistence results
|
||||
- final Action smoke results
|
||||
- any remaining risks
|
||||
|
||||
Commit all source, test, deployment config, and runbook changes to the governed task branch. Do not mark the task SUCCEEDED until all acceptance gates pass on the actually deployed staging overlay.
|
||||
|
||||
## Automatic rollback conditions
|
||||
|
||||
Automatically roll back the staging deployment if any of the following occur:
|
||||
|
||||
- service fails to become healthy after restart
|
||||
- protected-ref write boundary is broken
|
||||
- Gitea readback that worked before the change stops working
|
||||
- durable saga state cannot be read or recovered
|
||||
- mandatory test suite regresses below the pre-change baseline
|
||||
|
||||
Do not automatically roll back an existing production release. Rollback here refers only to the staging overlay/service configuration changes made by this task.
|
||||
|
||||
## 2026-08-25 execution record
|
||||
|
||||
The repair branch was deployed through the existing immutable staging builder. The final source code before the evidence commit was `2ec49005bde44f6981b14351500847d594e0276c`; the deployed artifact was built from that source with SHA256 `f67aed6cc0cce1f08197485c3eea204d3ef4d3989f44dc98e8ea2691e5886cbf`. The final staging drop-ins use a lexically highest `zzzz...-999.conf` layer so they override earlier diagnostic overlays.
|
||||
|
||||
The runtime configuration is staging-only: `User=aiman`, `Group=gitops`, API base `https://g.cnnetmkt.top/git/api/v1`, baseline authority `/var/lib/aios-gitops/model-api-staging/baseline/current.json`, and read/write access to the staging state plus the authoritative bare repository required by the governed Writer/CAS path. No `main`, protected tag, baseline registry, or production write is enabled.
|
||||
|
||||
The release executor now binds both the configured staging baseline and the immutable runtime package's `versions/V2R2C1.json` projection. The bridge passes `AIOS_GITOPS_BASELINE_AUTHORITY` into `RuntimeConfig`; this prevents release consistency and acceptance from falling back to missing publication-workspace files.
|
||||
|
||||
The final acceptance result is recorded in `reports/action-contract-repair-evidence-20260825.md`. Contract smoke is green, and release consistency is `PASS`; release acceptance is structured policy output but remains `accepted=false` because the pre-existing publication state is `REMOTE_PUSH_PENDING` for the protected `V2R2C1` tag. The task must therefore remain `NEEDS_REWORK` until an authorized owner resolves that independent protected-tag state.
|
||||
|
||||
## External Action Surface final closure attempt (2026-08-25)
|
||||
|
||||
本轮仅部署 staging/non-production;没有直接写入 main�release tag�baseline registry 或 production。
|
||||
|
||||
Public route ownership: /api/governed-write-capabilities, /api/control-plane-snapshot, /api/online-agent-task, and /api/online-agent-task-events are exact-location proxied to 127.0.0.1:18890; generic /api/ remains on 127.0.0.1:18893. The durable installer is ops/gitops-migration/bind_external_action_surface_final_staging.sh; it backs up Nginx, runs nginx -t, reloads, and forwards Authorization/X-AIOS-Token.
|
||||
|
||||
A task-control token, local Writer grant, Gitea consumer, SSH credential, or old token file is not an external Action bearer. If formal issuance is unavailable, do not print or rotate secrets, enable disabled writes, or manufacture commit evidence; record FORMAL_STAGING_ACTION_BEARER_ISSUANCE_NOT_AVAILABLE. Public release-consistency and release-acceptance use the canonical Bridge v2 evaluator. A Task API continuation remains QUEUED until a legitimate Agent claims it and gives durable result evidence.
|
||||
@@ -1,81 +0,0 @@
|
||||
# AIOS 最小自治修复闭环运行手册
|
||||
|
||||
## 范围
|
||||
|
||||
本手册只覆盖 staging/non-production 的最小链路:
|
||||
|
||||
```text
|
||||
readRepositoryFile -> acquireWriterLease -> commitFilesGoverned
|
||||
-> immutable staging build/reload -> runtime/read-back
|
||||
```
|
||||
|
||||
不覆盖 release/recovery/listPatches 语义,不得写入 `main`、release tag、baseline
|
||||
或 production。
|
||||
|
||||
## Action contract
|
||||
|
||||
公开 Action schema 的 canonical URL 是:
|
||||
`https://cnnetmkt.top/api/openapi-chatgpt-actions.yaml`。
|
||||
|
||||
本轮增加两个 operation,公开面共 28 个,保留 30 个上限余量:
|
||||
|
||||
- `readRepositoryFile`:`POST /readRepositoryFile`,必填 `repository`, `ref`, `path`, `max_bytes`;只从 authoritative bare Git object database 读取,禁止绝对路径、`..`、反斜线、NUL 和 `.git`,单次最多 262144 bytes。
|
||||
- `acquireWriterLease`:`POST /acquireWriterLease`,只接受 `CONTINUE_EXISTING`,必须绑定 durable task、repository、target branch、base OID、当前 expected branch OID、generation 和短 TTL。
|
||||
- `commitFilesGoverned`:既有 `POST /v2/commit-files`,必须先有同一 task/generation/expected OID 的 lease;`files` 为数组,每项必须含 `path` 与 `content_base64`。
|
||||
|
||||
model-api facade 对上述三个入口执行 Action bearer 认证,并把 Authorization/X-AIOS-Token 透传给 loopback Bridge。Bridge 再执行 operation-specific scope:read 允许 `repository:read` 或兼容的 `file:write`,lease 需要 `agent-task:control`,commit 需要 `file:write`。
|
||||
|
||||
## 构建与部署
|
||||
|
||||
从当前隔离 agent branch 的完整 source OID 构建:
|
||||
|
||||
```bash
|
||||
python3 scripts/build_v2r2c1_model_api_staging.py \
|
||||
--source-root . \
|
||||
--output-root /var/lib/aios-gitops/bridge-v2-staging/candidate-artifacts/<id> \
|
||||
--source-oid <40-hex-source-oid>
|
||||
```
|
||||
|
||||
构建 receipt 必须声明 `STAGING`、`aios/aios`、`legacy_global_writes_enabled=false`,并记录 artifact SHA-256。使用 versioned systemd drop-in template,将 source OID、artifact SHA-256 和 immutable runtime path 渲染到 staging 两个 unit;同时使用:
|
||||
|
||||
```ini
|
||||
LoadCredential=action_tokens:/data/aios-gitops/runtime/secrets/gitops.tokens
|
||||
Environment=AIOS_GITOPS_TOKEN_FILE=%d/action_tokens
|
||||
```
|
||||
|
||||
这样由 systemd 投影已有 Action token registry,不复制或打印 token,不使用 Gitea token 代替 Action bearer。部署后只执行:
|
||||
|
||||
```bash
|
||||
systemctl daemon-reload
|
||||
systemctl restart aios-chatgpt-bridge-v2-staging.service
|
||||
systemctl restart aios-gitops-model-api-v2r2c1-staging.service
|
||||
```
|
||||
|
||||
## 验收顺序
|
||||
|
||||
1. `systemctl is-active` 两个 staging unit;读取 `/api/health`、`/v2/runtime`。
|
||||
2. 从公网 URL 重新抓取 YAML,解析 operation 数量,确认 `<=30`,并确认 `files`/`path`/`content_base64` required parity。
|
||||
3. 使用正式 Action bearer:
|
||||
|
||||
```text
|
||||
readRepositoryFile(repository, ref=agent/<branch> or exact OID, path, max_bytes)
|
||||
acquireWriterLease(task_id, repository, CONTINUE_EXISTING, base_oid,
|
||||
expected_branch_oid=<read resolved OID>, target_branch,
|
||||
generation, lease_seconds)
|
||||
commitFilesGoverned(task_id, repository, expected_branch_oid, target_branch,
|
||||
generation, idempotency_key, two files, message)
|
||||
```
|
||||
|
||||
4. 校验 authority branch OID、Gitea Git ref OID、Gitea API branch OID 和 `commit_visible` 一致;重复相同 idempotency key 不得生成第二个 commit,旧 expected OID 必须拒绝。
|
||||
5. 验证 staging runtime source OID/artifact SHA-256 与 build receipt 一致,再重复完整 smoke。
|
||||
6. 若 bearer 不可用,状态必须是 `BLOCKED`,不能用 SSH、root、Gitea、旧 token、service credential 或 dev bypass 代替。
|
||||
|
||||
完整 suite 使用:
|
||||
|
||||
```bash
|
||||
PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=.:services/aios-release-controller pytest -p no:cacheprovider -q
|
||||
```
|
||||
|
||||
## 回滚边界
|
||||
|
||||
只回滚本轮创建的 staging artifact/drop-in;不得回滚 production release。若 health、Gitea readback、protected-ref boundary 或 mandatory suite 回归,恢复前一份 staging drop-in,采集 `journalctl -u` 日志,再继续诊断。
|
||||
@@ -1,169 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
SCHEMA = 'aios.v2r2c1.model-api-staging-manifest.v1'
|
||||
REQUIRED_APP = (
|
||||
'aios_model_api_staging.py',
|
||||
'aios_gitops_write_guard.py',
|
||||
'authoritative_git.py',
|
||||
'baseline_authority.py',
|
||||
'gitea_tag_publication.py',
|
||||
'silent_release_controller.py',
|
||||
'silent_release_hardening.py',
|
||||
'aios_gitops_job_controller.py',
|
||||
'aios_chatgpt_bridge_v2.py',
|
||||
'aios_chatgpt_bridge_v2_server.py',
|
||||
'governed_production_release.py',
|
||||
'v2r2c1_production_adapter.py',
|
||||
'v2r1c7_production_adapter.py',
|
||||
'aios_governed_task_bootstrap.py',
|
||||
'aios_continuation_executor.py',
|
||||
'aios_continuation_lease.py',
|
||||
'aios_authority_git_executor.py',
|
||||
'scoped_lease_store.py',
|
||||
'aios_gitops_reconciliation_core.py',
|
||||
'authorized_task_writer_provisioning.py',
|
||||
'signer_contract_compatibility.py',
|
||||
)
|
||||
OPTIONAL_APP = (
|
||||
'aios_chatgpt_actions_api.py',
|
||||
'aios_model_api_staging_list_patches_overlay.py',
|
||||
'aios_continuation_executor.py',
|
||||
'aios_continuation_lease.py',
|
||||
'aios_control_plane_snapshot.py',
|
||||
)
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with path.open('rb') as fh:
|
||||
for chunk in iter(lambda: fh.read(1024 * 1024), b''):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
def private_marker(path: Path) -> bool:
|
||||
import re
|
||||
text = path.read_text(encoding='utf-8', errors='ignore')
|
||||
patterns = (
|
||||
r'-----BEGIN [A-Z ]*PRIVATE KEY-----',
|
||||
r'(?<![A-Za-z0-9])sk-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])',
|
||||
r'(?<![A-Za-z0-9])ghp_[A-Za-z0-9]{20,}(?![A-Za-z0-9])',
|
||||
r'(?i)aws_secret_access_key\s*[:=]\s*[A-Za-z0-9/+=]{16,}',
|
||||
)
|
||||
return any(re.search(pattern, text) for pattern in patterns)
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--source-root', required=True, type=Path)
|
||||
ap.add_argument('--output-root', required=True, type=Path)
|
||||
ap.add_argument('--source-oid', required=True)
|
||||
args = ap.parse_args()
|
||||
oid = args.source_oid.lower()
|
||||
if len(oid) != 40 or any(c not in '0123456789abcdef' for c in oid):
|
||||
raise SystemExit('source oid must be exact 40 hex')
|
||||
source = args.source_root.resolve(strict=True)
|
||||
output = args.output_root.resolve()
|
||||
app = source / 'active-runtime' / 'app'
|
||||
sys.path.insert(0, str(app))
|
||||
from aios_chatgpt_bridge_v2 import render_openapi_contract_fragment
|
||||
|
||||
runtime = source / 'runtime' / 'agent-os'
|
||||
docs = source / 'docs' / 'gitops'
|
||||
if not app.is_dir():
|
||||
raise SystemExit('active-runtime/app missing')
|
||||
paths = []
|
||||
root_version = source / 'release_version.py'
|
||||
if not root_version.is_file():
|
||||
raise SystemExit('required source dependency missing: release_version.py')
|
||||
paths.append((Path('release_version.py'), root_version))
|
||||
for name in REQUIRED_APP:
|
||||
path = app / name
|
||||
if not path.is_file():
|
||||
raise SystemExit(f'required app dependency missing: {name}')
|
||||
paths.append((Path('app') / name, path))
|
||||
for name in OPTIONAL_APP:
|
||||
path = app / name
|
||||
if path.is_file():
|
||||
paths.append((Path('app') / name, path))
|
||||
for rel in ('orchestrator/__init__.py', 'orchestrator/action_monitor.py'):
|
||||
path = runtime / rel
|
||||
if not path.is_file():
|
||||
raise SystemExit(f'required runtime dependency missing: {rel}')
|
||||
paths.append((Path('runtime-agent-os') / rel, path))
|
||||
openapi = docs / 'openapi-chatgpt-actions.yaml'
|
||||
if openapi.is_file():
|
||||
if ' /v2/commit-files:' not in openapi.read_text(encoding='utf-8'):
|
||||
raise SystemExit('published OpenAPI is missing generated commitFilesGoverned contract')
|
||||
paths.append((Path('docs') / 'gitops' / 'openapi-chatgpt-actions.yaml', openapi))
|
||||
for folder in ('config/model_registry', 'config/model_priority', 'patches', 'versions'):
|
||||
root = source / folder
|
||||
if root.is_dir():
|
||||
for path in sorted(root.rglob('*')):
|
||||
if path.is_file() and path.suffix.lower() in {'.json', '.yaml', '.yml', '.md'}:
|
||||
paths.append((Path(folder) / path.relative_to(root), path))
|
||||
for rel, path in paths:
|
||||
if private_marker(path):
|
||||
raise SystemExit(f'private marker rejected: {rel}')
|
||||
included = [str(rel).replace('\\', '/') for rel, _ in paths]
|
||||
manifest = {
|
||||
'schema': SCHEMA,
|
||||
'target_version': 'V2R2C1',
|
||||
'source_oid': oid,
|
||||
'repository_identity': 'aios/aios',
|
||||
'deployment_state': 'STAGING',
|
||||
'runtime_mode': 'IMMUTABLE_STAGING',
|
||||
'runtime_entrypoint': 'app/aios_model_api_staging_list_patches_overlay.py',
|
||||
'legacy_global_writes_enabled': False,
|
||||
'governed_release_routing': 'bridge-v2',
|
||||
'artifact_sha256': 'provided-by-build-receipt-and-install-manifest',
|
||||
'included_paths': included,
|
||||
}
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
archive = output / f'aios-v2r2c1-model-api-{oid}.tar.gz'
|
||||
with tempfile.TemporaryDirectory(prefix='v2r2c1-model-api-', dir=str(output)) as tmp:
|
||||
root = Path(tmp) / 'runtime'
|
||||
for rel, path in paths:
|
||||
target = root / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(path.read_bytes())
|
||||
(root / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + '\n', encoding='utf-8')
|
||||
with tarfile.open(archive, 'w:gz', format=tarfile.PAX_FORMAT) as tf:
|
||||
for path in sorted(root.rglob('*')):
|
||||
rel = path.relative_to(root.parent)
|
||||
info = tf.gettarinfo(str(path), arcname=str(rel).replace('\\', '/'))
|
||||
info.mtime = 0
|
||||
info.uid = 0
|
||||
info.gid = 0
|
||||
info.uname = 'root'
|
||||
info.gname = 'root'
|
||||
if path.is_file():
|
||||
with path.open('rb') as fh:
|
||||
tf.addfile(info, fh)
|
||||
else:
|
||||
tf.addfile(info)
|
||||
digest = sha256(archive)
|
||||
receipt = {
|
||||
'schema': 'aios.v2r2c1.model-api-staging-build-receipt.v1',
|
||||
'target_version': 'V2R2C1',
|
||||
'source_oid': oid,
|
||||
'repository_identity': 'aios/aios',
|
||||
'artifact_path': str(archive),
|
||||
'artifact_sha256': digest,
|
||||
'deployment_state': 'STAGING',
|
||||
'manifest_schema': SCHEMA,
|
||||
'included_paths': included,
|
||||
}
|
||||
receipt_path = output / f'aios-v2r2c1-model-api-{oid}.receipt.json'
|
||||
receipt_path.write_text(json.dumps(receipt, ensure_ascii=False, indent=2, sort_keys=True) + '\n', encoding='utf-8')
|
||||
print(json.dumps(receipt, ensure_ascii=False, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -9,16 +9,10 @@ WORKSPACE="${AIOS_GITOPS_WORKSPACE:-/data/aios-gitops/workspace}"
|
||||
TAG_REMOTE="${AIOS_GITOPS_GITEA_REMOTE:-gitea}"
|
||||
BRANCH_REMOTE="${AIOS_GITOPS_BRANCH_REMOTE:-gitea}"
|
||||
|
||||
SCRIPT_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
if ! PYTHONPATH="$SCRIPT_ROOT:${PYTHONPATH:-}" python3 - "$VERSION" <<'PY'
|
||||
import sys
|
||||
from release_version import validate_release_version
|
||||
validate_release_version(sys.argv[1])
|
||||
PY
|
||||
then
|
||||
echo "ERROR: version must match VxRxCx" >&2
|
||||
exit 64
|
||||
fi
|
||||
case "$VERSION" in
|
||||
V[0-9]*R[0-9]*C[0-9]*) ;;
|
||||
*) echo "ERROR: version must match VxRxCx" >&2; exit 64 ;;
|
||||
esac
|
||||
|
||||
for value in "$TARGET_OID" "$EVIDENCE_CLOSURE_OID"; do
|
||||
[[ "$value" =~ ^[0-9a-f]{40}$ ]] || {
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
from __future__ import annotations
|
||||
import hashlib,json,re,tarfile
|
||||
from release_version import RELEASE_VERSION_RE
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
OID_RE=re.compile(r"^[0-9a-f]{40}$"); SHA_RE=re.compile(r"^[0-9a-f]{64}$"); VERSION_RE=RELEASE_VERSION_RE
|
||||
OID_RE=re.compile(r"^[0-9a-f]{40}$"); SHA_RE=re.compile(r"^[0-9a-f]{64}$"); VERSION_RE=re.compile(r"^V2R1C[0-9]+$")
|
||||
REQUIRED_SOURCE={"schema","version","repository","base_ref","base_oid","binding_mode","release_readiness","production_deployed","tag_created","baseline_changed","production_service","production_port","rollback_metadata","controller_schema","required_checks"}
|
||||
REQUEST_KEYS={"schema","version","repository","base_oid","target_oid","artifact_uri","artifact_sha256","artifact_size","evidence_closure_oid","approval_plan_id","execute","production_deployed","production_service","production_port","rollback_metadata","current_tag_oid","source_manifest_sha256"}
|
||||
class ManifestValidationError(ValueError):
|
||||
@@ -63,7 +62,7 @@ def validate_release_request(source_manifest:dict[str,Any],request_path:Path,exp
|
||||
if not isinstance(request["approval_plan_id"],str) or not request["approval_plan_id"].startswith("sha256:"): raise ManifestValidationError("APPROVAL_PLAN","invalid approval plan")
|
||||
if request["execute"] is not False or request["production_deployed"] is not False: raise ManifestValidationError("EXECUTION_NOT_ALLOWED","must be non-executing")
|
||||
if request["production_service"]!=source_manifest["production_service"] or request["production_port"]!=source_manifest["production_port"]: raise ManifestValidationError("SERVICE_IDENTITY","request service mismatch")
|
||||
if not isinstance(request["current_tag_oid"],str) or request["current_tag_oid"] not in {"V2R1C7","82792347937c0df59a8e02d6162775252bcad2e2"}: raise ManifestValidationError("PROTECTED_TAG","previous production tag binding changed")
|
||||
if not isinstance(request["current_tag_oid"],str) or request["current_tag_oid"] not in {"V2R1C6","9e65bd59baea392294c0f253046d3ab116f63145"}: raise ManifestValidationError("PROTECTED_TAG","previous tag binding changed")
|
||||
_sha(request["source_manifest_sha256"],"source_manifest_sha256"); return request
|
||||
def build_approval_request(*,source_manifest_path:Path,target_oid:str,artifact_uri:str,artifact_sha256:str,artifact_size:int,evidence_closure_oid:str,rollback_metadata:str,current_tag_oid:str)->dict[str,Any]:
|
||||
source=_json_object(source_manifest_path); _oid(target_oid,"target_oid"); _sha(artifact_sha256,"artifact_sha256"); _oid(evidence_closure_oid,"evidence_closure_oid"); request={"schema":"aios.release-request.v2","version":source["version"],"repository":source["repository"],"base_oid":source["base_oid"],"target_oid":target_oid,"artifact_uri":artifact_uri,"artifact_sha256":artifact_sha256,"artifact_size":artifact_size,"evidence_closure_oid":evidence_closure_oid,"execute":False,"production_deployed":False,"production_service":source["production_service"],"production_port":source["production_port"],"rollback_metadata":rollback_metadata,"current_tag_oid":current_tag_oid,"source_manifest_sha256":sha256_file(source_manifest_path)}; request["approval_plan_id"]="sha256:"+sha256_bytes(_canonical(request)); return request
|
||||
|
||||
@@ -3,13 +3,13 @@ from __future__ import annotations
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
|
||||
|
||||
def test_version_and_candidate_binding():
|
||||
assert (ROOT / "VERSION").read_text(encoding="utf-8").strip() == "V2R1C7"
|
||||
assert (ROOT / "VERSION").read_text(encoding="utf-8").strip() == "V2R1C6"
|
||||
metadata = json.loads((ROOT / "versions/V2R1C6.json").read_text(encoding="utf-8"))
|
||||
assert metadata["version"] == "V2R1C6"
|
||||
assert metadata["base_oid"] == "a33e2593967a180c89d44454350ccaeaf3f79b25"
|
||||
assert metadata["candidate_branch"] == "agent/v2r1c6-mainline-reconciliation-20260806"
|
||||
assert metadata["production_deployed"] is False
|
||||
|
||||
@@ -7,19 +7,17 @@ import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "active-runtime" / "app"))
|
||||
from deployment_state import RuntimeDeploymentState
|
||||
from v2r1c6_privacy_tools import health_payload, serve # noqa: E402
|
||||
|
||||
|
||||
def test_health_is_engineering_only() -> None:
|
||||
result = health_payload(RuntimeDeploymentState("V2R1C7", "a" * 40, "b" * 64, "STAGED"))
|
||||
assert result["status"] == "ok"
|
||||
assert result["version"] == "V2R1C7"
|
||||
assert result["commit_oid"] == "a" * 40
|
||||
assert result["artifact_sha256"] == "b" * 64
|
||||
assert result["deployment_state"] == "STAGED"
|
||||
assert result["production_deployed"] is False
|
||||
assert result["health_timestamp"]
|
||||
result = health_payload()
|
||||
assert result == {
|
||||
"status": "ok",
|
||||
"version": "V2R1C6",
|
||||
"production_deployed": False,
|
||||
"gitops_writes_enabled": False,
|
||||
}
|
||||
|
||||
|
||||
def test_listener_rejects_non_loopback() -> None:
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
||||
TEST_ROOT = REPOSITORY_ROOT / "tests"
|
||||
SERVICE_PACKAGE_ROOT = REPOSITORY_ROOT / "services" / "aios-autonomous-release-candidate"
|
||||
ACTIVE_RUNTIME_ROOT = REPOSITORY_ROOT / "active-runtime"
|
||||
ACTIVE_RUNTIME_APP = ACTIVE_RUNTIME_ROOT / "app"
|
||||
|
||||
for path in (TEST_ROOT, SERVICE_PACKAGE_ROOT, ACTIVE_RUNTIME_APP):
|
||||
value = str(path)
|
||||
if value not in sys.path:
|
||||
sys.path.insert(0, value)
|
||||
|
||||
|
||||
def load_module(relative: str):
|
||||
path = REPOSITORY_ROOT / relative
|
||||
spec = importlib.util.spec_from_file_location("v2r1c6_privacy_tools", path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError("module_load_failed")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _install_active_runtime_namespace() -> None:
|
||||
package = sys.modules.get("active_runtime")
|
||||
if package is None:
|
||||
package = types.ModuleType("active_runtime")
|
||||
package.__path__ = [str(ACTIVE_RUNTIME_ROOT)]
|
||||
package.__package__ = "active_runtime"
|
||||
sys.modules["active_runtime"] = package
|
||||
|
||||
app = sys.modules.get("active_runtime.app")
|
||||
if app is None:
|
||||
app = types.ModuleType("active_runtime.app")
|
||||
app.__path__ = [str(ACTIVE_RUNTIME_APP)]
|
||||
app.__package__ = "active_runtime"
|
||||
sys.modules["active_runtime.app"] = app
|
||||
package.app = app
|
||||
|
||||
|
||||
def _install_legacy_test_module(name: str, relative: str) -> None:
|
||||
if name in sys.modules:
|
||||
return
|
||||
path = REPOSITORY_ROOT / relative
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError("legacy_test_module_load_failed:" + name)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[name] = module
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
_install_active_runtime_namespace()
|
||||
sys.modules.setdefault("conftest", sys.modules[__name__])
|
||||
_install_legacy_test_module(
|
||||
"test_native_adapter_contracts",
|
||||
"tests/autonomous_release/test_native_adapter_contracts.py",
|
||||
)
|
||||
@@ -1,217 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "runtime/agent-os"))
|
||||
|
||||
from aios_chatgpt_bridge_v2 import ( # noqa: E402
|
||||
OPERATION_REQUIRED_FIELDS,
|
||||
operation_contracts,
|
||||
render_openapi_contract_fragment,
|
||||
)
|
||||
from aios_chatgpt_bridge_v2_server import GovernedRuntime # noqa: E402
|
||||
from aios_gitops_job_controller import JobState # noqa: E402
|
||||
from gitea_tag_publication import validate_gitea_api_url # noqa: E402
|
||||
from silent_release_hardening import ReleaseSagaStore, SilentReleaseActionService # noqa: E402
|
||||
from release_version import validate_release_version # noqa: E402
|
||||
import aios_model_api_staging as model_api # noqa: E402
|
||||
|
||||
|
||||
def test_canonical_release_version_is_shared_and_accepts_v2r2c1():
|
||||
assert validate_release_version("V2R2C1") == "V2R2C1"
|
||||
assert validate_release_version("V2R2C1-repair") == "V2R2C1-repair"
|
||||
with pytest.raises(ValueError):
|
||||
validate_release_version("v2r2c1")
|
||||
|
||||
|
||||
def test_gitea_url_validation_is_startup_safe():
|
||||
assert validate_gitea_api_url("https://g.cnnetmkt.top/git/api/v1") == (
|
||||
"https://g.cnnetmkt.top/git/api/v1"
|
||||
)
|
||||
with pytest.raises(ValueError, match="HTTP"):
|
||||
validate_gitea_api_url("g.cnnetmkt.top/git/api/v1")
|
||||
|
||||
|
||||
def test_public_release_reads_use_the_bridge_canonical_evaluator():
|
||||
query = {
|
||||
"version": ["V2R2C1"],
|
||||
"target_oid": ["998d30304787e31e5ae607c0bd86b5edb2b0e5ad"],
|
||||
"evidence_closure_oid": ["a8b906d1bc24088c19647e98de6a679268f6d0a2"],
|
||||
"approval_plan_id": ["sha256:plan"],
|
||||
}
|
||||
assert model_api.governed_release_query_payload(query) == {
|
||||
"version": "V2R2C1",
|
||||
"target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"evidence_closure_oid": "a8b906d1bc24088c19647e98de6a679268f6d0a2",
|
||||
"approval_plan_id": "sha256:plan",
|
||||
}
|
||||
source = inspect.getsource(model_api.H.do_GET)
|
||||
assert "self.bridge_release(" in source
|
||||
assert "'/getReleaseConsistency'" in source
|
||||
assert "'/runReleaseAcceptance'" in source
|
||||
|
||||
|
||||
def test_governed_read_routes_are_bound_to_authenticated_facade():
|
||||
route_script = (
|
||||
ROOT / "ops/gitops-migration/bind_external_action_surface_final_staging.sh"
|
||||
).read_text()
|
||||
for path in (
|
||||
"/api/governed-write-capabilities",
|
||||
"/api/control-plane-snapshot",
|
||||
"/api/online-agent-task",
|
||||
"/api/online-agent-task-events",
|
||||
):
|
||||
assert f"location = {path}" in route_script
|
||||
assert f"proxy_pass http://127.0.0.1:18890{path};" in route_script
|
||||
assert "location /api/ {" in route_script
|
||||
assert "Authorization $http_authorization" in route_script
|
||||
|
||||
|
||||
def test_published_action_v2_paths_are_bound_to_staging_bridge():
|
||||
route_script = (
|
||||
ROOT / "ops/gitops-migration/bind_external_action_surface_final_staging.sh"
|
||||
).read_text()
|
||||
schema = (ROOT / "docs/gitops/openapi-chatgpt-actions.yaml").read_text()
|
||||
assert "servers:" in schema
|
||||
assert "- url: https://cnnetmkt.top" in schema
|
||||
assert " /v2/commit-files:" in schema
|
||||
assert "location ^~ /v2/" in route_script
|
||||
assert "proxy_pass http://127.0.0.1:18892;" in route_script
|
||||
assert "proxy_pass http://127.0.0.1:18920;" not in route_script
|
||||
assert "Authorization $http_authorization" in route_script
|
||||
|
||||
|
||||
def test_published_action_schema_stays_within_chatgpt_operation_limit():
|
||||
schema = yaml.safe_load(
|
||||
(ROOT / "docs/gitops/openapi-chatgpt-actions.yaml").read_text()
|
||||
)
|
||||
operations = [
|
||||
(path, method, operation)
|
||||
for path, item in schema["paths"].items()
|
||||
for method, operation in item.items()
|
||||
if method.lower() in {"get", "post", "put", "patch", "delete", "head", "options"}
|
||||
]
|
||||
assert len(operations) <= 30
|
||||
assert len(operations) == 28
|
||||
assert "commitFilesGoverned" in {
|
||||
operation["operationId"] for _, _, operation in operations
|
||||
}
|
||||
assert {"readRepositoryFile", "acquireWriterLease"}.issubset(
|
||||
{operation["operationId"] for _, _, operation in operations}
|
||||
)
|
||||
assert "/api/file" not in schema["paths"]
|
||||
assert "/api/commit" not in schema["paths"]
|
||||
operation_ids = {operation["operationId"] for _, _, operation in operations}
|
||||
assert {
|
||||
"submitSignedApproval",
|
||||
"createPatch",
|
||||
"createBranch",
|
||||
"commitFileAtomic",
|
||||
"commitFile",
|
||||
"commitChanges",
|
||||
}.isdisjoint(operation_ids)
|
||||
governed = next(
|
||||
operation for _, _, operation in operations
|
||||
if operation["operationId"] == "commitFilesGoverned"
|
||||
)
|
||||
assert governed["security"] == [{"bearerAuth": []}]
|
||||
assert governed["x-openai-isConsequential"] is True
|
||||
|
||||
|
||||
def test_commit_files_runtime_and_published_schema_have_same_required_fields():
|
||||
runtime = operation_contracts()["commitFilesGoverned"]["required_fields"]
|
||||
assert runtime == list(OPERATION_REQUIRED_FIELDS["commitFilesGoverned"])
|
||||
fragment = render_openapi_contract_fragment()
|
||||
published = (ROOT / "docs/gitops/openapi-chatgpt-actions.yaml").read_text()
|
||||
assert fragment in published
|
||||
for field in runtime:
|
||||
assert f" - {field}" in fragment
|
||||
assert "required: [path, content_base64]" in fragment
|
||||
|
||||
|
||||
class _Store:
|
||||
def __init__(self, row):
|
||||
self.row = row
|
||||
self.receipt_calls = 0
|
||||
|
||||
def read(self, _job_id):
|
||||
return self.row
|
||||
|
||||
def _receipt(self, row, duplicate=False):
|
||||
self.receipt_calls += 1
|
||||
return type("Receipt", (), {"as_dict": lambda _self: {
|
||||
"job_id": row["job_id"],
|
||||
"state": row["state"],
|
||||
"duplicate": duplicate,
|
||||
}})()
|
||||
|
||||
|
||||
class _Controller:
|
||||
def __init__(self, row):
|
||||
self.store = _Store(row)
|
||||
|
||||
|
||||
def _runtime_for(row):
|
||||
runtime = object.__new__(GovernedRuntime)
|
||||
controller = _Controller(row)
|
||||
runtime._controller_for_job = lambda _job_id: controller
|
||||
runtime._executor_from_row = lambda *_args: (_ for _ in ()).throw(
|
||||
AssertionError("terminal reconcile must not reconstruct an executor")
|
||||
)
|
||||
return runtime, controller
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"state",
|
||||
[
|
||||
JobState.COMPLETED.value,
|
||||
JobState.FAILED.value,
|
||||
JobState.CANCELLED.value,
|
||||
JobState.MANUAL_OWNER_REVIEW_REQUIRED.value,
|
||||
],
|
||||
)
|
||||
def test_terminal_reconcile_is_idempotent_without_durable_binding(state):
|
||||
row = {
|
||||
"job_id": "job-terminal",
|
||||
"state": state,
|
||||
"request_json": json.dumps({}),
|
||||
}
|
||||
runtime, controller = _runtime_for(row)
|
||||
result = GovernedRuntime.job(runtime, {"job_id": row["job_id"]}, "reconcile")
|
||||
assert result["duplicate"] is True
|
||||
assert controller.store.receipt_calls == 1
|
||||
|
||||
|
||||
def test_active_reconcile_still_uses_executor():
|
||||
row = {
|
||||
"job_id": "job-active",
|
||||
"state": JobState.RECONCILIATION_REQUIRED.value,
|
||||
"request_json": json.dumps({}),
|
||||
}
|
||||
runtime, controller = _runtime_for(row)
|
||||
class Executor:
|
||||
def reconcile(self, job_id):
|
||||
return {"job_id": job_id, "state": "COMPLETED"}
|
||||
runtime._executor_from_row = lambda *_args: Executor()
|
||||
assert GovernedRuntime.job(runtime, {"job_id": row["job_id"]}, "reconcile") == {
|
||||
"job_id": "job-active",
|
||||
"state": "COMPLETED",
|
||||
}
|
||||
|
||||
|
||||
def test_missing_release_saga_is_a_not_found_empty_state(tmp_path):
|
||||
service = object.__new__(SilentReleaseActionService)
|
||||
service.sagas = ReleaseSagaStore(tmp_path)
|
||||
service.execution_enabled = False
|
||||
result = service.get_release_saga("never-created-action-contract")
|
||||
assert result["status"] == "NOT_FOUND"
|
||||
assert result["state"] == "NOT_FOUND"
|
||||
assert not list(tmp_path.rglob("*"))
|
||||
@@ -1,108 +0,0 @@
|
||||
import base64
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from aios_authority_git_executor import AuthorityGitExecutor
|
||||
from aios_chatgpt_bridge_v2_server import BridgeHandler, RuntimeConfig
|
||||
from aios_continuation_executor import GiteaContinuationRemote, ServerSideCredentialProjection
|
||||
from aios_continuation_lease import WriterLeaseRequestV2
|
||||
|
||||
|
||||
class Probe:
|
||||
def __init__(self, present=False):
|
||||
self.present = present
|
||||
|
||||
def branch_exists(self, _branch):
|
||||
return self.present
|
||||
|
||||
def branch_head(self, _branch):
|
||||
return "a" * 40
|
||||
|
||||
def is_ancestor(self, _older, _newer):
|
||||
return True
|
||||
|
||||
def commit_exists(self, _oid):
|
||||
return True
|
||||
|
||||
|
||||
def test_authority_create_task_branch_is_agent_scoped_and_idempotent(tmp_path):
|
||||
bare = tmp_path / "repo.git"
|
||||
subprocess.run(["git", "init", "--bare", str(bare)], check=True, capture_output=True)
|
||||
source = tmp_path / "source"
|
||||
subprocess.run(["git", "init", str(source)], check=True, capture_output=True)
|
||||
(source / "README.md").write_text("fixture\n", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(source), "add", "README.md"], check=True)
|
||||
subprocess.run(["git", "-C", str(source), "-c", "user.name=test", "-c", "user.email=test@example.invalid", "commit", "-m", "fixture"], check=True, capture_output=True)
|
||||
base = subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip()
|
||||
executor = AuthorityGitExecutor(bare, tmp_path / "worktrees")
|
||||
subprocess.run(["git", "-C", str(source), "push", str(bare), "HEAD:refs/heads/main"], check=True, capture_output=True)
|
||||
assert executor.create_task_branch("refs/heads/agent/contract-test", base) == base
|
||||
assert executor.create_task_branch("refs/heads/agent/contract-test", base) == base
|
||||
assert executor.read_ref("refs/heads/agent/contract-test") == base
|
||||
|
||||
|
||||
def test_create_new_lease_is_exact_base_and_absent():
|
||||
request = WriterLeaseRequestV2(
|
||||
task_id="TASK-P0-BRIDGE-V21-DURABLE-RECONCILIATION-20260809",
|
||||
repository="aios/aios",
|
||||
branch_mode="CREATE_NEW",
|
||||
base_oid="a" * 40,
|
||||
expected_branch_oid="a" * 40,
|
||||
target_branch="agent/p0-bridge-v21-durable-reconciliation-20260809",
|
||||
generation=1,
|
||||
)
|
||||
request.validate(Probe())
|
||||
|
||||
|
||||
def test_create_new_lease_rejects_existing_target():
|
||||
request = WriterLeaseRequestV2(
|
||||
task_id="task",
|
||||
repository="aios/aios",
|
||||
branch_mode="CREATE_NEW",
|
||||
base_oid="a" * 40,
|
||||
expected_branch_oid="a" * 40,
|
||||
target_branch="agent/existing-target",
|
||||
generation=1,
|
||||
)
|
||||
try:
|
||||
request.validate(Probe(True))
|
||||
except Exception as exc:
|
||||
assert str(exc) == "TARGET_BRANCH_ALREADY_EXISTS"
|
||||
else:
|
||||
raise AssertionError("existing CREATE_NEW target must fail")
|
||||
|
||||
|
||||
def test_slash_branch_uses_paginated_collection():
|
||||
credential = ServerSideCredentialProjection(Path("/tmp/key"), Path("/tmp/token"), active=True)
|
||||
calls = []
|
||||
|
||||
class FakeRemote(GiteaContinuationRemote):
|
||||
def _api(self, path):
|
||||
calls.append(path)
|
||||
if "page=1" in path:
|
||||
return [{"name": f"agent/other-{i}", "commit": {"id": "b" * 40}} for i in range(50)]
|
||||
return [{"name": "agent/slash/branch", "commit": {"id": "c" * 40}}]
|
||||
|
||||
remote = FakeRemote(Path("/tmp"), credential)
|
||||
assert remote.read_api_branch("agent/slash/branch") == "c" * 40
|
||||
assert calls[0].endswith("branches?page=1&limit=50")
|
||||
assert calls[1].endswith("branches?page=2&limit=50")
|
||||
|
||||
|
||||
def test_http_route_contract_is_complete():
|
||||
expected = {
|
||||
"/v2/runtime", "/v2/capabilities", "/v2/governed-task",
|
||||
"/v2/writer-lease", "/v2/commit-file", "/v2/commit-files",
|
||||
"/v2/source/file",
|
||||
"/v2/job", "/v2/job/resume", "/v2/job/reconcile",
|
||||
"/v2/tag/approval-request",
|
||||
"/v2/tag/publish",
|
||||
"/v2/tag/status",
|
||||
"/v2/release/artifact",
|
||||
"/v2/release/execute",
|
||||
"/v2/release/consistency",
|
||||
"/v2/release/acceptance",
|
||||
}
|
||||
from aios_chatgpt_bridge_v2_server import ROUTES
|
||||
|
||||
assert set(ROUTES) == expected
|
||||
@@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from aios_chatgpt_bridge_v2 import (
|
||||
BRIDGE_OPERATIONS,
|
||||
BRIDGE_SCHEMA_VERSION,
|
||||
OPERATION_REQUIRED_FIELDS,
|
||||
BridgeV2Adapter,
|
||||
ControlPlaneReleaseManifest,
|
||||
RuntimeDriftError,
|
||||
)
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[1]
|
||||
|
||||
|
||||
def test_immutable_release_identity_accepts_exact_artifact_and_rejects_workspace_drift():
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
approved = Path(directory) / "releases"
|
||||
runtime = approved / "release-1"
|
||||
runtime.mkdir(parents=True)
|
||||
artifact = runtime / "bridge.pyz"
|
||||
artifact.write_bytes(b"bridge-v2")
|
||||
digest = hashlib.sha256(artifact.read_bytes()).hexdigest()
|
||||
manifest = ControlPlaneReleaseManifest(
|
||||
"bridge-v2-test", "a" * 40, digest, runtime, BRIDGE_SCHEMA_VERSION,
|
||||
"aios/aios", Path("/data/aios-gitops/repo.git"), "STAGING",
|
||||
)
|
||||
assert manifest.validate(artifact, observed_oid="a" * 40, approved_root=approved)["drift_status"] == "PASS"
|
||||
with pytest.raises(RuntimeDriftError, match="CONTROL_PLANE_RUNTIME_DRIFT"):
|
||||
manifest.validate(artifact, observed_oid="b" * 40, approved_root=approved)
|
||||
mutable = ControlPlaneReleaseManifest(
|
||||
"bad", "a" * 40, digest, Path("/var/lib/worktrees/dev"), BRIDGE_SCHEMA_VERSION,
|
||||
"aios/aios", Path("/data/aios-gitops/repo.git"), "STAGING",
|
||||
)
|
||||
with pytest.raises(RuntimeDriftError, match="CONTROL_PLANE_RUNTIME_DRIFT"):
|
||||
mutable.validate(artifact, observed_oid="a" * 40, approved_root=approved)
|
||||
|
||||
|
||||
def test_bridge_capabilities_keep_legacy_closed_and_expose_exact_operations():
|
||||
adapter = BridgeV2Adapter(runtime_status={"drift_status": "PASS"})
|
||||
assert adapter.getRuntimeStatus()["bridge_schema_version"] == BRIDGE_SCHEMA_VERSION
|
||||
capabilities = adapter.getGovernedWriteCapabilities()
|
||||
assert capabilities["legacy_writes_enabled"] is False
|
||||
assert capabilities["governed_writes_enabled"] is True
|
||||
assert tuple(capabilities["operations"]) == BRIDGE_OPERATIONS
|
||||
assert adapter.legacy_write_disabled() == {
|
||||
"error": "LEGACY_WRITE_DISABLED",
|
||||
"replacement": "createGovernedTask",
|
||||
"governed_writes_available": True,
|
||||
}
|
||||
|
||||
|
||||
def test_openapi_runtime_and_fragment_required_fields_are_exactly_converged():
|
||||
canonical = yaml.safe_load((ROOT / "docs/gitops/openapi-chatgpt-actions.yaml").read_text(encoding="utf-8"))
|
||||
fragment = yaml.safe_load((ROOT / "docs/gitops/openapi-authorized-task-writer-fragment.yaml").read_text(encoding="utf-8"))
|
||||
operations = {}
|
||||
for path, methods in canonical["paths"].items():
|
||||
for method, value in methods.items():
|
||||
if isinstance(value, dict) and value.get("operationId") in BRIDGE_OPERATIONS:
|
||||
operations[value["operationId"]] = value
|
||||
assert set(operations) == set(BRIDGE_OPERATIONS)
|
||||
for operation, required in OPERATION_REQUIRED_FIELDS.items():
|
||||
if "requestBody" not in operations[operation]:
|
||||
assert required == ()
|
||||
continue
|
||||
schema = operations[operation]["requestBody"]["content"]["application/json"]["schema"]
|
||||
assert tuple(schema["required"]) == required
|
||||
fragment_required = tuple(fragment["components"]["schemas"]["WriterLeaseRequestV2"]["required"])
|
||||
assert fragment_required == OPERATION_REQUIRED_FIELDS["acquireWriterLease"]
|
||||
|
||||
|
||||
def test_release_manifest_round_trip_contains_only_declared_identity_fields():
|
||||
manifest = ControlPlaneReleaseManifest(
|
||||
"v", "a" * 40, "b" * 64, Path("/opt/aios/gitops-control-plane/v"), BRIDGE_SCHEMA_VERSION,
|
||||
"aios/aios", Path("/data/aios-gitops/repo.git"), "STAGING",
|
||||
)
|
||||
value = manifest.as_dict()
|
||||
assert tuple(value) == (
|
||||
"control_plane_release_version", "control_plane_target_oid", "artifact_sha256", "runtime_path",
|
||||
"bridge_schema_version", "repository_identity", "authoritative_git_dir", "deployment_state",
|
||||
)
|
||||
assert "credential" not in json.dumps(value).lower()
|
||||
@@ -0,0 +1,283 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
|
||||
from aios_continuation_executor import (
|
||||
ContinuationCommit,
|
||||
ContinuationExecutionError,
|
||||
ContinuationExecutor,
|
||||
ContinuationPermissions,
|
||||
ContinuationRuntimeBinding,
|
||||
DetachedGitWorkspace,
|
||||
GiteaContinuationRemote,
|
||||
)
|
||||
from aios_continuation_lease import WriterLeaseRequestV2
|
||||
from aios_gitops_job_controller import BindingConflict, GitOpsJobController, JobState, JobStore
|
||||
|
||||
|
||||
TASK = "TASK-P0-CHATGPT-BRIDGE-V2-CONTROL-PLANE-CONVERGENCE-20260809"
|
||||
REPOSITORY = "aios/aios"
|
||||
BRANCH = "agent/p0-chatgpt-bridge-v2-control-plane-convergence-20260809"
|
||||
BASE = "2" * 40
|
||||
HEAD = "8" * 40
|
||||
NEW = "9" * 40
|
||||
NOW = datetime(2026, 8, 9, 12, 0, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
class Authority:
|
||||
def __init__(self, *, head=HEAD, exists=True, descendant=True):
|
||||
self.head = head
|
||||
self.exists = exists
|
||||
self.descendant = descendant
|
||||
self.cas_calls = []
|
||||
|
||||
def branch_exists(self, branch):
|
||||
return self.exists
|
||||
|
||||
def branch_head(self, branch):
|
||||
return self.head
|
||||
|
||||
def is_ancestor(self, older, newer):
|
||||
if (older, newer) == (BASE, HEAD):
|
||||
return True
|
||||
return self.descendant and (older, newer) in {(HEAD, NEW), (BASE, NEW)}
|
||||
|
||||
def compare_and_swap_branch(self, branch, expected, new):
|
||||
self.cas_calls.append((branch, expected, new))
|
||||
if self.head != expected:
|
||||
raise RuntimeError("stale")
|
||||
self.head = new
|
||||
return new
|
||||
|
||||
|
||||
class Workspace:
|
||||
def __init__(self, *, detached=True, head=HEAD):
|
||||
self.detached = detached
|
||||
self.head = head
|
||||
self.commits = 0
|
||||
|
||||
def is_detached(self):
|
||||
return self.detached
|
||||
|
||||
def head_oid(self):
|
||||
return self.head
|
||||
|
||||
def commit_files(self, files, message):
|
||||
self.commits += 1
|
||||
self.head = NEW
|
||||
return NEW
|
||||
|
||||
|
||||
class Remote:
|
||||
def __init__(self, *, git=HEAD, api=HEAD, visible=True, repository=REPOSITORY, fail_after_push=False, omit_after_push=False):
|
||||
self.git = git
|
||||
self.api = api
|
||||
self.visible = visible
|
||||
self.repository = repository
|
||||
self.fail_after_push = fail_after_push
|
||||
self.omit_after_push = omit_after_push
|
||||
self.pushes = 0
|
||||
|
||||
def repository_identity(self):
|
||||
return self.repository
|
||||
|
||||
def push_exact(self, branch, expected, new):
|
||||
self.pushes += 1
|
||||
if self.git is None:
|
||||
raise RuntimeError("remote branch missing")
|
||||
if self.git != expected:
|
||||
raise RuntimeError("remote conflict")
|
||||
if not self.omit_after_push:
|
||||
self.git = self.api = new
|
||||
else:
|
||||
self.git = self.api = None
|
||||
if self.fail_after_push:
|
||||
raise TimeoutError("response lost")
|
||||
|
||||
def read_git_ref(self, branch):
|
||||
return self.git
|
||||
|
||||
def read_api_branch(self, branch):
|
||||
return self.api
|
||||
|
||||
def commit_visible(self, oid):
|
||||
return self.visible and self.api == oid
|
||||
|
||||
|
||||
class Credential:
|
||||
def __init__(self):
|
||||
self.projected = 0
|
||||
self.revoked = 0
|
||||
|
||||
def project(self):
|
||||
self.projected += 1
|
||||
|
||||
def revoke(self):
|
||||
self.revoked += 1
|
||||
|
||||
|
||||
def lease_request(**changes):
|
||||
values = dict(task_id=TASK, repository=REPOSITORY, branch_mode="CONTINUE_EXISTING", base_oid=BASE,
|
||||
expected_branch_oid=HEAD, target_branch=BRANCH, generation=1, lease_seconds=900)
|
||||
values.update(changes)
|
||||
return WriterLeaseRequestV2(**values)
|
||||
|
||||
|
||||
def binding(**changes):
|
||||
values = dict(
|
||||
request=lease_request(),
|
||||
workspace_path=Path("/var/lib/aios-task-writer/continuation-worktrees/exact"),
|
||||
lease_not_before=NOW - timedelta(seconds=1),
|
||||
lease_expires_at=NOW + timedelta(minutes=15),
|
||||
original_receipt_valid=True,
|
||||
original_grant_consumed=True,
|
||||
permissions=ContinuationPermissions(),
|
||||
)
|
||||
values.update(changes)
|
||||
return ContinuationRuntimeBinding(**values)
|
||||
|
||||
|
||||
def commit(**changes):
|
||||
values = dict(idempotency_key="first-continuation", files={"active-runtime/app/new.py": b"ok\n"},
|
||||
message="feat(gitops): add governed continuation executor")
|
||||
values.update(changes)
|
||||
return ContinuationCommit(**values)
|
||||
|
||||
|
||||
def make_executor(authority=None, workspace=None, remote=None, credential=None):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
controller = GitOpsJobController(JobStore(Path(temp.name).resolve()))
|
||||
executor = ContinuationExecutor(
|
||||
controller, authority or Authority(), workspace or Workspace(), remote or Remote(), credential or Credential(),
|
||||
now=lambda: NOW,
|
||||
)
|
||||
executor._test_temp = temp
|
||||
return executor
|
||||
|
||||
|
||||
def test_exact_existing_branch_completes_only_after_all_remote_proofs():
|
||||
authority, remote, credential = Authority(), Remote(), Credential()
|
||||
result = make_executor(authority, remote=remote, credential=credential).execute(binding(), commit())
|
||||
assert result["state"] == JobState.COMPLETED.value
|
||||
assert result["receipt"]["authority_oid"] == result["receipt"]["git_remote_oid"] == NEW
|
||||
assert result["receipt"]["api_branch_oid"] == NEW
|
||||
assert result["receipt"]["commit_visible"] is True
|
||||
assert authority.cas_calls == [(BRANCH, HEAD, NEW)]
|
||||
assert credential.projected == credential.revoked == 1
|
||||
assert "credential" not in repr(result).lower()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"runtime_binding,authority,workspace,error",
|
||||
[
|
||||
(binding(request=lease_request(expected_branch_oid="7" * 40)), Authority(), Workspace(), "EXISTING_BRANCH_OID_CONFLICT"),
|
||||
(binding(), Authority(exists=False), Workspace(), "EXISTING_BRANCH_MISSING"),
|
||||
(binding(), Authority(), Workspace(detached=False), "WORKTREE_NOT_DETACHED"),
|
||||
(binding(), Authority(), Workspace(head="7" * 40), "WORKTREE_HEAD_MISMATCH"),
|
||||
(binding(lease_expires_at=NOW), Authority(), Workspace(), "LEASE_EXPIRED"),
|
||||
(binding(request=lease_request(repository="other/repo")), Authority(), Workspace(), "request_identity_invalid"),
|
||||
(binding(request=lease_request(target_branch="main")), Authority(), Workspace(), "PROTECTED_BRANCH_REJECTED"),
|
||||
(binding(request=lease_request(generation=1)), Authority(), Workspace(), "GENERATION_NOT_MONOTONIC"),
|
||||
],
|
||||
)
|
||||
def test_pre_side_effect_failures_never_create_or_update_a_branch(runtime_binding, authority, workspace, error):
|
||||
executor = make_executor(authority, workspace=workspace)
|
||||
if error == "GENERATION_NOT_MONOTONIC":
|
||||
executor.observe_generation(BRANCH, 1)
|
||||
with pytest.raises(Exception, match=error):
|
||||
executor.execute(runtime_binding, commit())
|
||||
assert authority.cas_calls == []
|
||||
assert workspace.commits == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["create_target_branch", "force_push", "tag_write", "baseline_write", "production_write", "main_write"])
|
||||
def test_forbidden_capabilities_fail_before_credential_projection(field):
|
||||
credential = Credential()
|
||||
permissions = ContinuationPermissions(**{field: True})
|
||||
with pytest.raises(ContinuationExecutionError, match="MUTATION_PERMISSION_DENIED"):
|
||||
make_executor(credential=credential).execute(binding(permissions=permissions), commit())
|
||||
assert credential.projected == 0
|
||||
|
||||
|
||||
def test_non_fast_forward_and_concurrent_movement_are_rejected_cas_only():
|
||||
authority = Authority(descendant=False)
|
||||
with pytest.raises(ContinuationExecutionError, match="NON_FAST_FORWARD_COMMIT"):
|
||||
make_executor(authority).execute(binding(), commit())
|
||||
assert authority.cas_calls == []
|
||||
|
||||
|
||||
def test_authority_success_and_gitea_missing_is_never_completed():
|
||||
remote = Remote(omit_after_push=True)
|
||||
result = make_executor(remote=remote).execute(binding(), commit())
|
||||
assert result["state"] == JobState.RECONCILIATION_REQUIRED.value
|
||||
assert result["side_effect_state"] == "REMOTE_PUSH_PENDING"
|
||||
assert result["state"] not in {JobState.REMOTE_VERIFIED.value, JobState.COMPLETED.value}
|
||||
|
||||
|
||||
def test_response_loss_after_remote_success_reconciles_by_observation_without_second_push():
|
||||
remote = Remote(fail_after_push=True)
|
||||
executor = make_executor(remote=remote)
|
||||
first = executor.execute(binding(), commit())
|
||||
assert first["state"] == JobState.RECONCILIATION_REQUIRED.value
|
||||
assert remote.pushes == 1
|
||||
recovered = executor.reconcile(first["job_id"])
|
||||
assert recovered["state"] == JobState.COMPLETED.value
|
||||
assert remote.pushes == 1
|
||||
|
||||
|
||||
def test_observation_first_reconcile_retries_only_when_remote_is_exact_expected_old_oid():
|
||||
remote = Remote(fail_after_push=True)
|
||||
executor = make_executor(remote=remote)
|
||||
first = executor.execute(binding(), commit())
|
||||
assert first["state"] == JobState.RECONCILIATION_REQUIRED.value
|
||||
remote.git = remote.api = HEAD
|
||||
remote.visible = True
|
||||
remote.fail_after_push = False
|
||||
recovered = executor.reconcile(first["job_id"])
|
||||
assert recovered["state"] == JobState.COMPLETED.value
|
||||
assert remote.pushes == 2
|
||||
|
||||
|
||||
def test_duplicate_idempotency_replay_and_conflicting_payload():
|
||||
executor = make_executor()
|
||||
first = executor.execute(binding(), commit())
|
||||
replay = executor.execute(binding(), commit())
|
||||
assert replay["job_id"] == first["job_id"]
|
||||
with pytest.raises(BindingConflict, match="BINDING_CONFLICT"):
|
||||
executor.execute(binding(), commit(files={"active-runtime/app/new.py": b"changed\n"}))
|
||||
|
||||
|
||||
def test_secret_like_payload_fails_before_projection():
|
||||
credential = Credential()
|
||||
secret_fixture = b"to" + b"ken=" + b"ghp_" + b"abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
with pytest.raises(ContinuationExecutionError, match="SECRET_LIKE_PAYLOAD_REJECTED"):
|
||||
make_executor(credential=credential).execute(binding(), commit(files={"x": secret_fixture}))
|
||||
assert credential.projected == 0
|
||||
|
||||
|
||||
def test_remote_identity_cannot_alias_the_authority_bare_repo():
|
||||
with pytest.raises(ContinuationExecutionError, match="GITEA_REMOTE_IDENTITY_INVALID"):
|
||||
GiteaContinuationRemote.validate_remote_url("/data/aios-gitops/repo.git")
|
||||
GiteaContinuationRemote.validate_remote_url("aiman@g.cnnetmkt.top:aios/aios.git")
|
||||
|
||||
|
||||
def test_detached_workspace_preserves_porcelain_leading_status_column():
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
subprocess.run(["git", "init", "-q", str(root)], check=True)
|
||||
subprocess.run(["git", "-C", str(root), "config", "user.name", "test"], check=True)
|
||||
subprocess.run(["git", "-C", str(root), "config", "user.email", "test@localhost"], check=True)
|
||||
(root / "tracked.py").write_text("one\n", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(root), "add", "tracked.py"], check=True)
|
||||
subprocess.run(["git", "-C", str(root), "commit", "-q", "-m", "base"], check=True)
|
||||
subprocess.run(["git", "-C", str(root), "checkout", "-q", "--detach"], check=True)
|
||||
(root / "tracked.py").write_text("two\n", encoding="utf-8")
|
||||
(root / "new.py").write_text("new\n", encoding="utf-8")
|
||||
workspace = DetachedGitWorkspace(root)
|
||||
assert workspace.is_detached()
|
||||
assert workspace._dirty_paths() == {"tracked.py", "new.py"}
|
||||
@@ -250,7 +250,7 @@ class GovernedLocalWriterTests(unittest.TestCase):
|
||||
}
|
||||
self.assertEqual(service.process_request(secret_request, peer)["status"], "error")
|
||||
|
||||
def test_idempotent_replay_returns_receipt(self) -> None:
|
||||
def test_one_shot_consumption(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
directory = Path(root)
|
||||
auth = self._load_auth(self._make_auth_payload(), directory)
|
||||
@@ -283,8 +283,8 @@ class GovernedLocalWriterTests(unittest.TestCase):
|
||||
|
||||
self.assertEqual(service.process_request(create_request, peer)["status"], "ok")
|
||||
self.assertEqual(service.process_request(append_request, peer)["status"], "ok")
|
||||
self.assertEqual(service.process_request(append_request, peer)["status"], "receipt")
|
||||
self.assertEqual(len(sink.records), 2)
|
||||
self.assertEqual(service.process_request(append_request, peer)["status"], "error")
|
||||
self.assertEqual(len(sink.records), 3)
|
||||
self.assertEqual(len(handler.create_calls), 1)
|
||||
self.assertEqual(len(handler.append_calls), 1)
|
||||
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
MODULE_PATH = (
|
||||
Path(__file__).parents[1]
|
||||
/ "active-runtime"
|
||||
/ "app"
|
||||
/ "governed_production_release.py"
|
||||
)
|
||||
|
||||
|
||||
def _load_module():
|
||||
dependency = types.ModuleType("gitea_tag_publication")
|
||||
for name in (
|
||||
"GiteaTagClient",
|
||||
"GitTagBackend",
|
||||
"PublicationManualOwnerReviewRequired",
|
||||
"PublicationPending",
|
||||
"PublicationReconciliationRequired",
|
||||
"PublicationRequest",
|
||||
"TagPublisher",
|
||||
):
|
||||
setattr(dependency, name, type(name, (), {}))
|
||||
sys.modules["gitea_tag_publication"] = dependency
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"governed_production_release_under_test", MODULE_PATH
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
assert spec.loader is not None
|
||||
sys.modules[spec.name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
release_module = _load_module()
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
status = 200
|
||||
|
||||
def __init__(self, body):
|
||||
self._payload = json.dumps(body).encode("utf-8")
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
return False
|
||||
|
||||
def read(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
def _health_body(binding, artifact_sha256):
|
||||
return {
|
||||
"status": "ok",
|
||||
"version": binding.version,
|
||||
"commit_oid": binding.target_oid,
|
||||
"artifact_sha256": artifact_sha256,
|
||||
"deployment_state": "ACTIVE",
|
||||
"production_deployed": True,
|
||||
}
|
||||
|
||||
|
||||
def _run_acceptance(result):
|
||||
executor = object.__new__(release_module.GovernedProductionReleaseExecutor)
|
||||
records = []
|
||||
executor.state = SimpleNamespace(
|
||||
record=lambda *args: records.append(args),
|
||||
)
|
||||
executor.consistency = lambda request: deepcopy(result)
|
||||
return executor.acceptance({}), records
|
||||
|
||||
|
||||
def test_all_checks_true_preserves_health_status_and_accepts():
|
||||
binding = release_module.ReleaseBinding()
|
||||
artifact_sha256 = "a" * 64
|
||||
|
||||
with patch(
|
||||
"urllib.request.urlopen",
|
||||
return_value=FakeResponse(_health_body(binding, artifact_sha256)),
|
||||
):
|
||||
health = release_module._health(
|
||||
"https://example.test/health",
|
||||
binding,
|
||||
{"artifact_sha256": artifact_sha256},
|
||||
)
|
||||
|
||||
assert health["status"] == "ok"
|
||||
assert health["verification_status"] == "ACTIVE_VERIFIED"
|
||||
assert health["http_status"] == 200
|
||||
|
||||
result, records = _run_acceptance(
|
||||
{"status": "PASS", "production_health": health}
|
||||
)
|
||||
assert result["accepted"] is True
|
||||
assert records[-1][0] == "ACCEPTED"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value", "artifact_sha256"),
|
||||
[
|
||||
("commit_oid", "0" * 40, "a" * 64),
|
||||
("artifact_sha256", "b" * 64, "a" * 64),
|
||||
("deployment_state", "STAGING", "a" * 64),
|
||||
],
|
||||
ids=["commit-mismatch", "artifact-mismatch", "deployment-not-active"],
|
||||
)
|
||||
def test_health_conflicts_keep_external_status_and_reject(field, value, artifact_sha256):
|
||||
binding = release_module.ReleaseBinding()
|
||||
body = _health_body(binding, artifact_sha256)
|
||||
body[field] = value
|
||||
|
||||
with patch("urllib.request.urlopen", return_value=FakeResponse(body)):
|
||||
health = release_module._health(
|
||||
"https://example.test/health",
|
||||
binding,
|
||||
{"artifact_sha256": artifact_sha256},
|
||||
)
|
||||
|
||||
assert health["status"] == "ok"
|
||||
assert health["verification_status"] == "CONFLICT"
|
||||
result, _ = _run_acceptance(
|
||||
{"status": "PASS", "production_health": health}
|
||||
)
|
||||
assert result["accepted"] is False
|
||||
|
||||
|
||||
def test_health_unavailable_has_internal_verdict_and_rejects():
|
||||
binding = release_module.ReleaseBinding()
|
||||
|
||||
with patch("urllib.request.urlopen", side_effect=TimeoutError("boom")):
|
||||
health = release_module._health(
|
||||
"https://example.test/health",
|
||||
binding,
|
||||
{"artifact_sha256": "a" * 64},
|
||||
)
|
||||
|
||||
assert health["status"] == "UNAVAILABLE"
|
||||
assert health["verification_status"] == "UNAVAILABLE"
|
||||
assert health["error"] == "TimeoutError"
|
||||
result, _ = _run_acceptance(
|
||||
{"status": "PASS", "production_health": health}
|
||||
)
|
||||
assert result["accepted"] is False
|
||||
|
||||
|
||||
def test_acceptance_rejects_when_overall_check_is_not_pass():
|
||||
result, records = _run_acceptance(
|
||||
{
|
||||
"status": "CONFLICT",
|
||||
"production_health": {
|
||||
"status": "ok",
|
||||
"verification_status": "ACTIVE_VERIFIED",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert result["accepted"] is False
|
||||
assert records[-1][0] == "RECONCILIATION_REQUIRED"
|
||||
@@ -1,116 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OVERLAY = ROOT / "active-runtime" / "app" / "aios_model_api_staging_list_patches_overlay.py"
|
||||
|
||||
|
||||
class StubHandler:
|
||||
def sendj(self, data, code=200):
|
||||
self.sent = (data, code)
|
||||
return self.sent
|
||||
|
||||
|
||||
def load_overlay() -> ModuleType:
|
||||
base = ModuleType("aios_model_api_staging")
|
||||
base.H = StubHandler
|
||||
base.main = lambda: None
|
||||
previous = sys.modules.get("aios_model_api_staging")
|
||||
sys.modules["aios_model_api_staging"] = base
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location("list_patches_overlay_test", OVERLAY)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
finally:
|
||||
if previous is None:
|
||||
sys.modules.pop("aios_model_api_staging", None)
|
||||
else:
|
||||
sys.modules["aios_model_api_staging"] = previous
|
||||
|
||||
|
||||
def test_overlay_keeps_legacy_keys_but_only_emits_bounded_summaries():
|
||||
overlay = load_overlay()
|
||||
records = [
|
||||
{
|
||||
"id": "oversized",
|
||||
"branch": "agent/oversized",
|
||||
"created_at": "2026-08-26T15:00:00Z",
|
||||
"text": "X" * 2_000_000,
|
||||
"body": "B" * 2_000_000,
|
||||
"diff": "D" * 2_000_000,
|
||||
"evidence": {"raw": "E" * 2_000_000},
|
||||
}
|
||||
] + [
|
||||
{"id": f"patch-{index:03d}", "created_at": f"2026-08-25T{index % 24:02d}:00:00Z", "description": "summary"}
|
||||
for index in range(1, 25)
|
||||
]
|
||||
handler = overlay.ListPatchesOverlayHandler.__new__(overlay.ListPatchesOverlayHandler)
|
||||
handler.path = "/api/patch"
|
||||
result = handler.sendj(
|
||||
{
|
||||
"metadata_patches": records,
|
||||
"patches": records,
|
||||
"authoritative_branches": [{"name": "agent/example", "oid": "a" * 40, "secret": "drop"}],
|
||||
"orphan_metadata": records,
|
||||
"branches_without_metadata": records,
|
||||
"branches": [f"agent/{index}" for index in range(40)],
|
||||
"repository_available": True,
|
||||
"query_error": None,
|
||||
}
|
||||
)
|
||||
payload, code = result
|
||||
assert code == 200
|
||||
assert payload["list_patches_overlay"] == "bounded-summary-v1"
|
||||
assert payload["count"] <= overlay.PATCH_DEFAULT_LIMIT
|
||||
assert payload["has_more"] is True
|
||||
assert payload["next_cursor"]
|
||||
encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
assert len(encoded) <= overlay.PATCH_RESPONSE_BUDGET
|
||||
assert all(set(item) <= {
|
||||
"patch_id", "name", "branch", "ref", "status", "risk", "created_at", "updated_at",
|
||||
"commit_oid", "summary", "summary_truncated",
|
||||
} for item in payload["items"])
|
||||
assert "body" not in json.dumps(payload, ensure_ascii=False)
|
||||
assert len(payload["branches"]) <= overlay.PATCH_COMPAT_LIST_LIMIT
|
||||
|
||||
|
||||
def test_overlay_cursor_pagination_and_invalid_limit_are_deterministic():
|
||||
overlay = load_overlay()
|
||||
records = [
|
||||
{"id": f"p-{index:02d}", "created_at": f"2026-08-26T{index:02d}:00:00Z"}
|
||||
for index in range(1, 26)
|
||||
]
|
||||
first = overlay._page(records, {"limit": ["1"]})
|
||||
second = overlay._page(records, {"limit": ["1"], "cursor": [first["next_cursor"]]})
|
||||
assert first["count"] == second["count"] == 1
|
||||
assert first["items"][0]["patch_id"] != second["items"][0]["patch_id"]
|
||||
assert first["has_more"] and second["has_more"]
|
||||
for value in ("0", "101", "not-an-int"):
|
||||
try:
|
||||
overlay._page(records, {"limit": [value]})
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "invalid_limit"
|
||||
else:
|
||||
raise AssertionError("invalid limit accepted")
|
||||
try:
|
||||
overlay._page(records, {"limit": ["1"], "cursor": ["bad"]})
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "invalid_cursor"
|
||||
else:
|
||||
raise AssertionError("invalid cursor accepted")
|
||||
|
||||
|
||||
def test_overlay_delegates_non_patch_routes_unchanged():
|
||||
overlay = load_overlay()
|
||||
handler = overlay.ListPatchesOverlayHandler.__new__(overlay.ListPatchesOverlayHandler)
|
||||
handler.path = "/api/health"
|
||||
result = handler.sendj({"status": "ok"}, 200)
|
||||
assert result == ({"status": "ok"}, 200)
|
||||
@@ -1,77 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "active-runtime" / "app"))
|
||||
|
||||
from aios_authority_git_executor import AuthorityGitError, AuthorityGitExecutor
|
||||
from aios_chatgpt_bridge_v2 import OPERATION_REQUIRED_FIELDS, operation_contracts
|
||||
from scoped_lease_store import ScopedLeaseStore, ScopedLeaseError
|
||||
|
||||
|
||||
def _fixture_repo(tmp_path: Path) -> tuple[Path, str]:
|
||||
bare = tmp_path / "repo.git"
|
||||
source = tmp_path / "source"
|
||||
subprocess.run(["git", "init", "--bare", str(bare)], check=True, capture_output=True)
|
||||
subprocess.run(["git", "init", str(source)], check=True, capture_output=True)
|
||||
(source / "README.md").write_text("fixture\n", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(source), "add", "README.md"], check=True)
|
||||
subprocess.run(
|
||||
["git", "-C", str(source), "-c", "user.name=test", "-c", "user.email=test@example.invalid", "commit", "-m", "fixture"],
|
||||
check=True, capture_output=True,
|
||||
)
|
||||
oid = subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip()
|
||||
subprocess.run(["git", "-C", str(source), "push", str(bare), "HEAD:refs/heads/main"], check=True, capture_output=True)
|
||||
return bare, oid
|
||||
|
||||
|
||||
def test_read_repository_file_is_bounded_and_ref_scoped(tmp_path):
|
||||
bare, oid = _fixture_repo(tmp_path)
|
||||
executor = AuthorityGitExecutor(bare, tmp_path / "worktrees")
|
||||
result = executor.read_file("main", "README.md", 1024)
|
||||
assert result["resolved_commit_oid"] == oid
|
||||
assert base64.b64decode(result["content_base64"]) == b"fixture\n"
|
||||
assert result["read_only"] is True
|
||||
with pytest.raises(AuthorityGitError, match="SOURCE_PATH_INVALID"):
|
||||
executor.read_file("main", "../README.md", 1024)
|
||||
with pytest.raises(AuthorityGitError, match="SOURCE_FILE_TOO_LARGE"):
|
||||
executor.read_file("main", "README.md", 1)
|
||||
with pytest.raises(AuthorityGitError, match="SOURCE_REF_SCOPE_DENIED"):
|
||||
executor.read_file("refs/remotes/origin/main", "README.md", 1024)
|
||||
|
||||
|
||||
def test_runtime_and_published_contract_keep_read_and_commit_fields_explicit():
|
||||
contracts = operation_contracts()
|
||||
assert set(OPERATION_REQUIRED_FIELDS["readRepositoryFile"]) == {"repository", "ref", "path", "max_bytes"}
|
||||
assert contracts["commitFilesGoverned"]["required_fields"] == list(OPERATION_REQUIRED_FIELDS["commitFilesGoverned"])
|
||||
assert "files" in contracts["commitFilesGoverned"]["required_fields"]
|
||||
|
||||
|
||||
def test_scoped_lease_is_idempotent_and_rejects_cross_binding(tmp_path):
|
||||
store = ScopedLeaseStore(tmp_path / "leases.sqlite3")
|
||||
request = {
|
||||
"schema": "aios.task-writer-lease.v2",
|
||||
"task_id": "task-min-loop",
|
||||
"repository": "aios/aios",
|
||||
"branch_mode": "CONTINUE_EXISTING",
|
||||
"base_oid": "a" * 40,
|
||||
"expected_branch_oid": "a" * 40,
|
||||
"target_branch": "agent/min-loop",
|
||||
"generation": 1,
|
||||
"lease_seconds": 60,
|
||||
}
|
||||
first, created = store.acquire(request)
|
||||
assert created is True and first["state"] == "ACTIVE"
|
||||
replay, created = store.acquire(request)
|
||||
assert created is False and replay["lease_key"] == first["lease_key"]
|
||||
conflict = dict(request, expected_branch_oid="b" * 40)
|
||||
with pytest.raises(ScopedLeaseError, match="LEASE_BINDING_CONFLICT"):
|
||||
store.acquire(conflict)
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def test_model_api_source_is_immutable_and_authority_bound():
|
||||
source = (ROOT / 'active-runtime' / 'app' / 'aios_model_api_staging.py').read_text(encoding='utf-8')
|
||||
assert 'BaselineAuthority' in source
|
||||
assert 'BASELINE_AUTHORITY = BaselineAuthority()' in source
|
||||
assert 'LEGACY_GIT_WRITE_COMMANDS' in source
|
||||
assert 'BaselineAuthorityError' in source
|
||||
assert 'IMMUTABLE_STAGING' in source
|
||||
assert 'LEGACY_GLOBAL_WRITES_DISABLED' in source
|
||||
assert "'production_deployed': False" in source
|
||||
assert "'governed_release_routing': 'bridge-v2'" in source
|
||||
|
||||
|
||||
def test_model_api_staging_unit_is_non_production_and_read_only():
|
||||
unit = (ROOT / 'deploy' / 'systemd' / 'aios-gitops-model-api-v2r2c1-staging.service').read_text(encoding='utf-8')
|
||||
assert 'aios-gitops-model-api-v2r2c1-staging.service' in unit
|
||||
assert 'AIOS_GITOPS_WRITES_ENABLED=false' in unit
|
||||
assert 'AIOS_GITOPS_DURABLE_JOB_EXECUTION_ENABLED=false' in unit
|
||||
assert 'AIOS_GITOPS_PORT=18893' in unit
|
||||
assert 'aios_model_api_staging.py' in unit
|
||||
assert 'production' not in unit.lower().replace('model-api-v2r2c1-staging', '')
|
||||
|
||||
|
||||
def test_model_api_builder_manifest_contract():
|
||||
builder = (ROOT / 'scripts' / 'build_v2r2c1_model_api_staging.py').read_text(encoding='utf-8')
|
||||
assert 'aios.v2r2c1.model-api-staging-manifest.v1' in builder
|
||||
assert "'target_version': 'V2R2C1'" in builder
|
||||
assert "'repository_identity': 'aios/aios'" in builder
|
||||
assert "'deployment_state': 'STAGING'" in builder
|
||||
assert "'legacy_global_writes_enabled': False" in builder
|
||||
assert 'private marker rejected' in builder
|
||||
@@ -0,0 +1,51 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from aios_control_plane_snapshot import build_control_plane_snapshot
|
||||
from aios_credential_broker import CredentialBroker
|
||||
from aios_gitops_reconciliation_core import ReconciliationAction, RemoteObservation, decide_reconciliation
|
||||
from aios_governed_policy import GovernedPolicyInput, evaluate_policy
|
||||
|
||||
|
||||
OID = "a" * 40
|
||||
OLD = "b" * 40
|
||||
|
||||
|
||||
def test_authority_desired_remote_missing_never_completes():
|
||||
decision = decide_reconciliation(RemoteObservation("aios/aios", "agent/example", OID, OID, None, None, False, "now", OLD))
|
||||
assert decision.action == ReconciliationAction.MARK_RECONCILIATION_REQUIRED
|
||||
assert decision.state != "COMPLETED"
|
||||
|
||||
|
||||
def test_response_loss_observes_desired_remote_before_retry():
|
||||
decision = decide_reconciliation(RemoteObservation("aios/aios", "agent/example", OID, OID, OID, OID, True, "now", OLD))
|
||||
assert decision.action == ReconciliationAction.MARK_REMOTE_VERIFIED
|
||||
|
||||
|
||||
def test_conflicting_remote_fails_closed():
|
||||
decision = decide_reconciliation(RemoteObservation("aios/aios", "agent/example", OID, OID, "c" * 40, "c" * 40, True, "now", OLD))
|
||||
assert decision.action == ReconciliationAction.FAIL_CONFLICT
|
||||
|
||||
|
||||
def test_policy_denies_production_and_force_capabilities():
|
||||
request = GovernedPolicyInput("owner", "task", "aios/aios", "commitFilesGoverned", OID, OID, "agent/example", 2, requested_capabilities=("production_write", "force_push"))
|
||||
assert evaluate_policy(request).decision == "DENY"
|
||||
|
||||
|
||||
def test_credential_metadata_does_not_include_secret_and_revoke_is_idempotent():
|
||||
class Provider:
|
||||
def environment(self, lease):
|
||||
return {"CREDENTIAL_FILE": "/run/credential"}
|
||||
broker = CredentialBroker(Provider())
|
||||
metadata = broker.issue(task_id="task", repository="aios/aios", target_branch="agent/example", generation=1)
|
||||
assert "token" not in str(metadata).lower()
|
||||
revoked = broker.revoke(metadata["lease_id"])
|
||||
assert broker.revoke(metadata["lease_id"])["state"] == "REVOKED"
|
||||
assert revoked["state"] == "REVOKED"
|
||||
|
||||
|
||||
def test_snapshot_marks_secret_material_false_and_preserves_partial_observation():
|
||||
snapshot = build_control_plane_snapshot(target_version="V2R2C1", task={"gitea_git_oid": None, "gitea_api_oid": None})
|
||||
assert snapshot["secret_material_exposed"] is False
|
||||
assert snapshot["task"]["gitea_git_oid"] is None
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"approval_plan_id": "sha256:c0df52008ae7f64cec5ee2d28947aa7b892066c670ab8295e4549140b1a7500e",
|
||||
"artifact_sha256": "ab4ae257346c82863f05abf5e309381a1c86612957608c3a4f4ab5cc9233f052",
|
||||
"deployment_state": "ACTIVE",
|
||||
"enabled": true,
|
||||
"evidence_closure_oid": "a8b906d1bc24088c19647e98de6a679268f6d0a2",
|
||||
"peeled_target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"production_deployed": true,
|
||||
"production_port": 18927,
|
||||
"production_service": "aios-v2r1c7-production.service",
|
||||
"registered": true,
|
||||
"repository": "aios/aios",
|
||||
"schema": "aios.production-registry.v2",
|
||||
"status": "PRODUCTION_DEPLOYED",
|
||||
"tag": "V2R2C1",
|
||||
"tag_object": "07fc2746b688f5f243f29b39de39f32edc3dd9d2",
|
||||
"tag_oid": "07fc2746b688f5f243f29b39de39f32edc3dd9d2",
|
||||
"target_oid": "998d30304787e31e5ae607c0bd86b5edb2b0e5ad",
|
||||
"updated_at": "2026-08-09T09:13:13Z",
|
||||
"version": "V2R2C1"
|
||||
}
|
||||
Reference in New Issue
Block a user