File size: 17,943 Bytes
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ca3c16
caf8059
 
 
 
 
 
5ca3c16
 
caf8059
 
 
 
 
 
5ca3c16
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ca3c16
 
caf8059
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
"""Skill use cases, transaction boundaries and version/approval invariants."""
import re
import uuid
from typing import Callable
from pydantic import ValidationError
from src.modules.skill.atomic_registry.catalog import builtin_operations, check_handler
from src.modules.skill.domain.models import Actor, Draft, Framework, Issue, Operation, SkillError, digest
from src.modules.skill.graph.compiler import compile_graph
from src.modules.skill.ports.repository import SkillRepository


class SkillService:
    def __init__(self, repository: SkillRepository, knowledge_resolver: Callable, project_access: Callable | None = None):
        self.repository = repository
        self.knowledge_resolver = knowledge_resolver
        self.project_access = project_access or self._no_project_adapter

    @staticmethod
    def _no_project_adapter(actor, project_id):
        raise SkillError("PROJECT_ADAPTER_REQUIRED", "项目权限适配器未接入。", 503)

    @staticmethod
    def require(actor, roles):
        if not set(actor.roles).intersection(roles):
            raise SkillError("ROLE_REQUIRED", "当前角色无此管理权限。", 403)

    @staticmethod
    def need(tx, actor, kind, key):
        doc = tx.get(actor.tenant_id, kind, key)
        if doc is None:
            raise SkillError("NOT_FOUND", "对象不存在或不可见。", 404)
        return doc

    def scope(self, actor, body):
        project_id = body.get("project_id")
        if project_id:
            self.project_access(actor, project_id)

    def bootstrap(self, actor: Actor):
        """Install only platform-owned contracts; does not approve Skill/framework/corpus."""
        self.require(actor, {"admin"})
        with self.repository.transaction(write=True) as tx:
            for operation in builtin_operations():
                key = operation.operation_id + "@" + operation.version
                if tx.get(actor.tenant_id, "operation", key) is None:
                    tx.create(actor.tenant_id, "operation", key, operation.model_dump(mode="json"))
            tx.audit(actor.tenant_id, actor.user_id, "catalog.bootstrap", "atomic-operations", digest([o.model_dump(mode="json") for o in builtin_operations()]))

    def catalog(self, actor, kind):
        if kind not in {"operation", "framework"}:
            raise SkillError("INVALID_CATALOG", "未知目录。")
        with self.repository.transaction() as tx:
            return tx.listing(actor.tenant_id, kind)

    def add_operation(self, actor, operation: Operation):
        self.require(actor, {"admin", "skill_manager"})
        check_handler(operation)
        key = operation.operation_id + "@" + operation.version
        with self.repository.transaction(write=True) as tx:
            result = tx.create(actor.tenant_id, "operation", key, operation.model_dump(mode="json"))
            tx.audit(actor.tenant_id, actor.user_id, "operation.version.create", key, result["digest"])
            return result

    def add_framework(self, actor, framework: Framework):
        self.require(actor, {"admin", "skill_manager"})
        if framework.state == "approved" and not framework.evidence_refs:
            raise SkillError("FRAMEWORK_EVIDENCE_REQUIRED", "批准框架需要工具链/契约证据引用。")
        if any(not re.fullmatch(r"[0-9][A-Za-z0-9._-]*", v) or "snapshot" in v.lower() for v in framework.dependencies.values()):
            raise SkillError("UNPINNED_DEPENDENCY", "依赖必须锁定具体版本。")
        key = framework.profile_id + "@" + framework.version
        with self.repository.transaction(write=True) as tx:
            result = tx.create(actor.tenant_id, "framework", key, framework.model_dump(mode="json"))
            tx.audit(actor.tenant_id, actor.user_id, "framework.version.create", key, result["digest"])
            return result

    def save_draft(self, actor, draft: Draft, expected_revision=None):
        self.require(actor, {"admin", "skill_manager"})
        self.scope(actor, draft.model_dump())
        with self.repository.transaction(write=True) as tx:
            old = tx.get(actor.tenant_id, "draft", draft.skill_id)
            body = draft.model_dump(mode="json")
            body["owner_id"] = old["body"]["owner_id"] if old else actor.user_id
            body["last_editor_id"] = actor.user_id
            if old:
                if expected_revision is None:
                    raise SkillError("REVISION_REQUIRED", "保存已有草稿必须带expected_revision。", 409)
                # Check the previous project too; a caller cannot move an inaccessible draft out of it.
                self.scope(actor, old["body"])
                result = tx.update(actor.tenant_id, "draft", draft.skill_id, body, expected_revision)
            else:
                if expected_revision is not None:
                    raise SkillError("REVISION_CONFLICT", "草稿尚不存在。", 409)
                result = tx.create(actor.tenant_id, "draft", draft.skill_id, body)
            tx.audit(actor.tenant_id, actor.user_id, "skill.draft.save", draft.skill_id, result["digest"])
            return result

    def read_draft(self, actor, skill_id):
        self.require(actor, {"admin", "skill_manager", "reviewer"})
        with self.repository.transaction() as tx:
            result = self.need(tx, actor, "draft", skill_id)
            self.scope(actor, result["body"])
            return result

    def drafts(self, actor):
        self.require(actor, {"admin", "skill_manager", "reviewer"})
        with self.repository.transaction() as tx:
            result = []
            for item in tx.listing(actor.tenant_id, "draft"):
                try:
                    self.scope(actor, item["body"])
                except SkillError as exc:
                    if exc.status in {403, 404}:
                        continue
                    raise
                result.append(item)
            return result

    def _validate(self, tx, actor, doc):
        self.scope(actor, doc["body"])
        data = {k: v for k, v in doc["body"].items() if k not in {"owner_id", "last_editor_id"}}
        draft = Draft.model_validate(data)
        operations = {item["key"]: Operation.model_validate(item["body"]) for item in tx.listing(actor.tenant_id, "operation") if not tx.get(actor.tenant_id, "retirement", "operation:" + item["key"])}
        framework_doc = tx.get(actor.tenant_id, "framework", draft.framework_ref)
        framework = Framework.model_validate(framework_doc["body"]) if framework_doc and not tx.get(actor.tenant_id, "retirement", "framework:" + draft.framework_ref) else None
        report = compile_graph(draft, operations, framework)
        knowledge = []
        for binding in draft.knowledge_bindings:
            try:
                knowledge.append(self.knowledge_resolver(actor, binding))
            except SkillError as exc:
                # Never reveal names/body of an invisible source in the report.
                report.issues.append(Issue(code=exc.code, location="knowledge_bindings." + binding.name, message="知识引用不可用、版本不符或权限不足。"))
        report.valid = not report.issues
        report.digest = digest({"compiled": report.digest, "knowledge": knowledge})
        return draft, report, knowledge, operations, framework

    def validate(self, actor, skill_id):
        self.require(actor, {"admin", "skill_manager", "reviewer"})
        with self.repository.transaction() as tx:
            return self._validate(tx, actor, self.need(tx, actor, "draft", skill_id))[1]

    def approve(self, actor, skill_id, expected_revision, expected_digest, evidence_refs):
        self.require(actor, {"admin", "reviewer"})
        if not evidence_refs or any(not x.strip() or len(x) > 300 for x in evidence_refs):
            raise SkillError("REVIEW_EVIDENCE_REQUIRED", "评审必须引用具体评审/测试证据。")
        with self.repository.transaction(write=True) as tx:
            doc = self.need(tx, actor, "draft", skill_id)
            if doc["body"]["last_editor_id"] == actor.user_id:
                raise SkillError("INDEPENDENT_REVIEW_REQUIRED", "草稿作者不能自行批准发布。", 403)
            _, report, _, _, _ = self._validate(tx, actor, doc)
            if not report.valid:
                raise SkillError("GRAPH_INVALID", "静态校验未通过。", details={"issues": [x.model_dump() for x in report.issues]})
            if doc["revision"] != expected_revision or report.digest != expected_digest:
                raise SkillError("APPROVAL_TARGET_CHANGED", "评审目标或依赖已经变化。", 409)
            body = {"skill_id": skill_id, "draft_revision": doc["revision"], "compiled_digest": report.digest, "reviewer_id": actor.user_id, "evidence_refs": evidence_refs}
            key = "approval-" + uuid.uuid4().hex
            result = tx.create(actor.tenant_id, "approval", key, body)
            tx.audit(actor.tenant_id, actor.user_id, "skill.review.approve", skill_id, report.digest)
            return result

    def publish(self, actor, skill_id, version, expected_revision, approval_id):
        self.require(actor, {"admin", "skill_manager"})
        if not re.fullmatch(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", version):
            raise SkillError("INVALID_VERSION", "发布版本必须为精确语义版本。")
        with self.repository.transaction(write=True) as tx:
            doc = self.need(tx, actor, "draft", skill_id)
            draft, report, knowledge, operations, framework = self._validate(tx, actor, doc)
            if not report.valid:
                raise SkillError("GRAPH_INVALID", "静态校验未通过。", details={"issues": [x.model_dump() for x in report.issues]})
            approval = self.need(tx, actor, "approval", approval_id)["body"]
            if doc["revision"] != expected_revision or approval["skill_id"] != skill_id or approval["draft_revision"] != doc["revision"] or approval["compiled_digest"] != report.digest:
                raise SkillError("APPROVAL_TARGET_CHANGED", "变更后必须重新评审,旧批准不能重用。", 409)
            body = {"skill_id": skill_id, "version": version, "project_id": draft.project_id,
                    "draft": draft.model_dump(mode="json"), "compiled_digest": report.digest,
                    "execution_order": report.execution_order, "operations_lock": report.operation_locks,
                    "operations": {ref: operations[ref].model_dump(mode="json") for ref in report.operation_locks},
                    "framework": framework.model_dump(mode="json"), "knowledge": knowledge,
                    "approval_id": approval_id, "review_evidence": approval["evidence_refs"],
                    "publication_scope": "capability-definition", "runtime_verification": "not_executed_by_skill_registry"}
            key = skill_id + "@" + version
            result = tx.create(actor.tenant_id, "release", key, body)
            tx.audit(actor.tenant_id, actor.user_id, "skill.release.publish", key, result["digest"])
            return result

    def retire(self, actor, kind, key, reason):
        self.require(actor, {"admin", "skill_manager"})
        if kind not in {"operation", "framework", "release"}:
            raise SkillError("INVALID_KIND", "不支持该版本类型。")
        with self.repository.transaction(write=True) as tx:
            obj = self.need(tx, actor, kind, key)
            self.scope(actor, obj["body"])
            result = tx.create(actor.tenant_id, "retirement", kind + ":" + key, {"reason": reason, "actor": actor.user_id})
            tx.audit(actor.tenant_id, actor.user_id, kind + ".retire", key, obj["digest"])
            return result

    def stage_local_validation(self, actor, skill_id, authorization_ref, *, validation_owner=None, expected_revision=None):
        """Server-only experimental snapshot; not a published capability release."""
        self.require(actor, {'admin'})
        if not authorization_ref or len(authorization_ref) > 300:
            raise SkillError('AUTHORIZATION_REFERENCE_REQUIRED', '本地验证需要明确授权引用。')
        with self.repository.transaction(write=True) as tx:
            doc = self.need(tx, actor, 'draft', skill_id)
            if expected_revision is not None and doc['revision'] != expected_revision:
                raise SkillError('REVISION_CONFLICT','工作流已被修改,请刷新后重试。',409)
            draft, report, knowledge, operations, framework = self._validate(tx, actor, doc)
            if not report.valid:
                raise SkillError('GRAPH_INVALID', '本地验证图校验失败。', details={'issues': [x.model_dump() for x in report.issues]})
            if not draft.project_id:
                raise SkillError('VALIDATION_PROJECT_REQUIRED', '本地验证版本必须绑定一个明确项目。')
            body = {'skill_id': skill_id, 'version': 'local-validation', 'project_id': draft.project_id,
                    'draft_revision':doc['revision'],'draft_digest':doc['digest'],
                    'draft': draft.model_dump(mode='json'), 'compiled_digest': report.digest,
                    'execution_order': report.execution_order, 'operations_lock': report.operation_locks,
                    'operations': {ref: operations[ref].model_dump(mode='json') for ref in report.operation_locks},
                    'framework': framework.model_dump(mode='json'), 'knowledge': knowledge,
                    'approval_id': None, 'review_evidence': [], 'authorization_ref': authorization_ref,
                    'publication_scope': 'local-validation-only', 'human_review': False, 'validation_owner': validation_owner or actor.user_id}
            key = skill_id + '@local-' + digest(body)[:16]
            existing = tx.get(actor.tenant_id, 'release', key)
            if existing:
                return existing
            result = tx.create(actor.tenant_id, 'release', key, body)
            tx.audit(actor.tenant_id, actor.user_id, 'skill.local-validation.stage', key, result['digest'])
            return result

    def releases(self, actor, project_id=None):
        if project_id:
            self.project_access(actor, project_id)
        with self.repository.transaction() as tx:
            return [item for item in tx.listing(actor.tenant_id, "release") if item['body'].get('publication_scope') != 'local-validation-only' and not tx.get(actor.tenant_id, "retirement", "release:" + item["key"]) and item["body"].get("project_id") in {None, project_id}]

    def prepare(self, actor, release_ref, project_id, source_digest, idempotency_key, *, inspect_only=False):
        if not re.fullmatch(r"[a-f0-9]{64}", source_digest) or not 8 <= len(idempotency_key) <= 128:
            raise SkillError("INVALID_SNAPSHOT_INPUT", "源码摘要或幂等键格式不符。")
        self.project_access(actor, project_id)
        with self.repository.transaction(write=True) as tx:
            release = self.need(tx, actor, "release", release_ref)
            body = release["body"]
            if (body.get('publication_scope') == 'local-validation-only' and body.get('validation_owner') != actor.user_id
                    and not (inspect_only and set(actor.roles).intersection({'admin', 'reviewer'}))):
                raise SkillError('NOT_FOUND', '本地验证版本不对其他用户发布。', 404)
            self.scope(actor, body)
            if body.get("project_id") not in {None, project_id}:
                raise SkillError("NOT_FOUND", "版本不在当前项目范围。", 404)
            checks = [("release", release_ref), ("framework", body["draft"]["framework_ref"])] + [("operation", ref) for ref in body["operations_lock"]]
            if any(tx.get(actor.tenant_id, "retirement", kind + ":" + key) for kind, key in checks):
                raise SkillError("DEPENDENCY_RETIRED", "版本或依赖停用,不能开始新任务。", 409)
            knowledge = [self.knowledge_resolver(actor, binding) for binding in Draft.model_validate(body["draft"]).knowledge_bindings]
            if knowledge != body["knowledge"]:
                raise SkillError("KNOWLEDGE_CHANGED", "知识版本或权限发生变化,需重新检查。", 409)
            request_digest = digest({"release": release_ref, "project": project_id, "source": source_digest})
            request_key = digest({"user": actor.user_id, "idempotency_key": idempotency_key})
            previous = tx.get(actor.tenant_id, "prepared-request", request_key)
            if previous:
                if previous["body"]["request_digest"] != request_digest:
                    raise SkillError("IDEMPOTENCY_CONFLICT", "同一幂等键不能用于不同源码或版本。", 409)
                return previous["body"]["snapshot"]
            snapshot = {"snapshot_id": "snapshot-" + uuid.uuid4().hex, "tenant_id": actor.tenant_id, "user_id": actor.user_id, "project_id": project_id,
                        "release_ref": release_ref, "release_digest": release["digest"], "source_digest": source_digest,
                        "knowledge": knowledge, "framework": body["framework"], "operations_lock": body["operations_lock"],
                        "execution_order": body["execution_order"], "budget": body["draft"]["budget"], "execution_status": "not_started"}
            if body['draft'].get('instructions'):
                snapshot['skill_instructions'] = body['draft']['instructions']
            snapshot = dict(snapshot, snapshot_digest=digest(snapshot))
            tx.create(actor.tenant_id, "snapshot", snapshot["snapshot_id"], snapshot)
            tx.create(actor.tenant_id, "prepared-request", request_key, {"request_digest": request_digest, "snapshot": snapshot})
            tx.audit(actor.tenant_id, actor.user_id, "skill.snapshot.prepare", release_ref, snapshot["snapshot_digest"])
            return snapshot