dsh-plugin-opc 0.0.0-stage → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +257 -2
  2. package/config/overlay.example.yml +9 -0
  3. package/docs/acceptance-matrix.md +30 -0
  4. package/docs/images/01-plugins.png +0 -0
  5. package/docs/images/02-install-menu.png +0 -0
  6. package/docs/images/03-install-address.png +0 -0
  7. package/docs/images/04-installed.png +0 -0
  8. package/docs/images/05-open-sidebar.png +0 -0
  9. package/docs/images/06-opc-entries.png +0 -0
  10. package/docs/images/07-space-and-knowledge.png +0 -0
  11. package/docs/images/08-search-results.png +0 -0
  12. package/docs/images/09-document.png +0 -0
  13. package/docs/images/10-mention-menu.png +0 -0
  14. package/docs/images/11-mention-question.png +0 -0
  15. package/docs/images/12-answer-sources.png +0 -0
  16. package/docs/images/13-skills-install.png +0 -0
  17. package/docs/images/14-skill-enabled.png +0 -0
  18. package/docs/images/15-skill-slash.png +0 -0
  19. package/docs/images/16-mcp-list.png +0 -0
  20. package/docs/images/17-mcp-tool.png +0 -0
  21. package/docs/images/chat-mention.png +0 -0
  22. package/docs/images/git-source.png +0 -0
  23. package/docs/images/mcp-services.png +0 -0
  24. package/docs/implementation-status.md +40 -0
  25. package/lib/client.js +31892 -0
  26. package/lib/index.js +3477 -0
  27. package/package.json +90 -4
  28. package/runtime/app_delivery/LICENSE +18 -0
  29. package/runtime/app_delivery/PROVENANCE.md +1 -0
  30. package/runtime/app_delivery/SKILL.md +38 -0
  31. package/runtime/app_delivery/__init__.py +1 -0
  32. package/runtime/app_delivery/assets/invoke_api.py.txt +269 -0
  33. package/runtime/app_delivery/references/contract.md +90 -0
  34. package/runtime/app_delivery/references/framework-checks.md +59 -0
  35. package/runtime/app_delivery/references/integration.md +23 -0
  36. package/runtime/app_delivery/references/preparation-checks.md +26 -0
  37. package/runtime/app_delivery/scripts/__init__.py +1 -0
  38. package/runtime/app_delivery/scripts/delivery.py +650 -0
  39. package/runtime/app_delivery/scripts/invoke_api.py +269 -0
  40. package/runtime/app_delivery/scripts/sqlite_snapshot.py +139 -0
  41. package/runtime/app_delivery_auth.py +113 -0
  42. package/runtime/app_delivery_config.py +108 -0
  43. package/runtime/app_delivery_migration.py +2452 -0
  44. package/runtime/app_delivery_repair.py +48 -0
  45. package/runtime/app_delivery_sources.py +39 -0
  46. package/runtime/vendor/tomli/LICENSE +21 -0
  47. package/runtime/vendor/tomli/__init__.py +8 -0
  48. package/runtime/vendor/tomli/_parser.py +793 -0
  49. package/runtime/vendor/tomli/_re.py +119 -0
  50. package/runtime/vendor/tomli/_types.py +10 -0
  51. package/runtime/vendor/yaml/LICENSE +20 -0
  52. package/runtime/vendor/yaml/__init__.py +389 -0
  53. package/runtime/vendor/yaml/composer.py +138 -0
  54. package/runtime/vendor/yaml/constructor.py +748 -0
  55. package/runtime/vendor/yaml/cyaml.py +100 -0
  56. package/runtime/vendor/yaml/dumper.py +61 -0
  57. package/runtime/vendor/yaml/emitter.py +1137 -0
  58. package/runtime/vendor/yaml/error.py +74 -0
  59. package/runtime/vendor/yaml/events.py +85 -0
  60. package/runtime/vendor/yaml/loader.py +63 -0
  61. package/runtime/vendor/yaml/nodes.py +48 -0
  62. package/runtime/vendor/yaml/parser.py +588 -0
  63. package/runtime/vendor/yaml/reader.py +185 -0
  64. package/runtime/vendor/yaml/representer.py +388 -0
  65. package/runtime/vendor/yaml/resolver.py +226 -0
  66. package/runtime/vendor/yaml/scanner.py +1435 -0
  67. package/runtime/vendor/yaml/serializer.py +110 -0
  68. package/runtime/vendor/yaml/tokens.py +103 -0
  69. package/runtime/worker.py +574 -0
@@ -0,0 +1,574 @@
1
+ """Plugin-owned deterministic worker. Never imports or executes application code."""
2
+ from __future__ import annotations
3
+ import argparse
4
+ import base64
5
+ import contextlib
6
+ import difflib
7
+ import hashlib
8
+ import io
9
+ import json
10
+ from pathlib import Path
11
+ import re
12
+ import shutil
13
+ import sys
14
+ import tarfile
15
+ import tempfile
16
+ import time
17
+ import zipfile
18
+ import uuid
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
21
+ if sys.version_info < (3, 9):
22
+ sys.exit("Requires Python 3.9 or newer")
23
+
24
+ from app_delivery.scripts import delivery as d
25
+ from app_delivery.scripts.invoke_api import execute
26
+ from app_delivery_auth import resolve_authentication, validate_auth_evidence, validate_auth_probe_coverage, validate_auth_questions
27
+ from app_delivery_config import loopback_connection, original_fields, original_value
28
+ from app_delivery_migration import (
29
+ enrich_contract_and_discovery_report,
30
+ inspect_local_sqlite_files,
31
+ scan_app_routes_and_pages,
32
+ select_and_filter_platform_resources,
33
+ )
34
+ from app_delivery_repair import check_archive_syntax, read_archive_file
35
+ from app_delivery_sources import dependency_path
36
+
37
+
38
+ def _fingerprint(value) -> str:
39
+ return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()
40
+
41
+
42
+ def redact(text: str, name: str = "") -> str:
43
+ hidden = set(d.secret_lines(text, name))
44
+ config = Path(name).suffix.lower() in {".yaml", ".yml", ".ini", ".toml", ".properties"} or Path(name).name.startswith(".env")
45
+ lines = []
46
+ for i, line in enumerate(text.splitlines(), 1):
47
+ if i not in hidden:
48
+ lines.append(line)
49
+ continue
50
+ key = re.match(r"^(\s*(?:#\s*)?(?:export\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*[:=])", line) if config else None
51
+ lines.append(key.group(1) + ' "[REDACTED]"' if key else "[REDACTED credential line]")
52
+ return "\n".join(lines)
53
+
54
+
55
+ def load_json_if_exists(path: Path, default):
56
+ if path.is_file():
57
+ try:
58
+ return json.loads(path.read_text(encoding="utf-8"))
59
+ except Exception:
60
+ return default
61
+ return default
62
+
63
+
64
+ def validate_file_change(source: Path, change: dict):
65
+ d.require(isinstance(change, dict), "修改项必须是对象")
66
+ d.require(isinstance(change.get("group", ""), str) and len(change.get("group", "")) <= 160, "修改分组必须是简短文字")
67
+ path = change.get("path")
68
+ target = d.relative(source, path)
69
+ if target.exists() and not target.is_file():
70
+ raise ValueError("修改路径必须是普通文件")
71
+ if any(p in d.EXCLUDED or p == ".coworker" for p in Path(path).parts):
72
+ raise ValueError("禁止修改版本库或 Agent 配置")
73
+ if not isinstance(change.get("path"), str) or not change["path"] or not isinstance(change.get("reason", "适配修改"), str) or not isinstance(change.get("content"), str):
74
+ raise ValueError("修改项必须有路径、原因和完整文件内容")
75
+ if target.is_file() and target.suffix in {".mjs", ".cjs", ".js", ".py", ".go", ".ts"}:
76
+ old = d.text_of(target)
77
+ if old and len(old.splitlines()) > 100 and len(change["content"].splitlines()) < 10:
78
+ raise ValueError("疑似用代码片段覆盖完整业务文件;请保留原业务并提交完整文件内容")
79
+ if len(change["content"].encode("utf-8")) > 2_000_000 or "[REDACTED" in change["content"]:
80
+ raise ValueError("提案文件超限或包含脱敏占位符,需重新分析")
81
+
82
+
83
+ def compute_change_diffs(source: Path, changes: list[dict]) -> dict[str, str]:
84
+ diffs: dict[str, str] = {}
85
+ for ch in changes:
86
+ cpath = ch.get("path", "")
87
+ if not cpath or not isinstance(ch.get("content"), str):
88
+ continue
89
+ p = d.relative(source, cpath)
90
+ old = redact(p.read_text(encoding="utf-8", errors="replace"), cpath) if p.is_file() else ""
91
+ new = redact(ch["content"], cpath)
92
+ diffs[cpath] = "\n".join(
93
+ difflib.unified_diff(
94
+ old.splitlines(),
95
+ new.splitlines(),
96
+ fromfile=cpath + " (原始)",
97
+ tofile=cpath + " (建议)",
98
+ )
99
+ )
100
+ return diffs
101
+
102
+
103
+ def resolve_and_enrich_proposal(
104
+ root: Path,
105
+ proposal: dict,
106
+ *,
107
+ repair: bool = False,
108
+ failed_revision: str = "",
109
+ failure_feedback: str = "",
110
+ revision_count: int = 1,
111
+ feedback_text: str = "",
112
+ expected_port: int | None = None,
113
+ ) -> tuple[dict, dict | None, dict | None]:
114
+ source = root / "review/source"
115
+ draft_files = load_json_if_exists(root / "draft_files.json", {})
116
+ resolved_changes = []
117
+ for idx, change in enumerate(proposal.get("changes", [])):
118
+ if isinstance(change, dict) and "content" not in change:
119
+ cid = change.get("id") or change.get("path")
120
+ if cid and cid in draft_files:
121
+ staged = draft_files[cid]
122
+ if change.get("path") and staged.get("path") and change["path"] != staged["path"]:
123
+ raise ValueError("汇总提案的文件路径与分项提案不一致")
124
+ change = {**staged, **change}
125
+ elif change.get("path"):
126
+ by_path = next((v for v in draft_files.values() if isinstance(v, dict) and v.get("path") == change["path"]), None)
127
+ if by_path:
128
+ change = {**by_path, **change}
129
+ if isinstance(change, dict) and not change.get("id"):
130
+ change = {**change, "id": change.get("path") or f"change-{idx + 1}"}
131
+ if isinstance(change, dict) and not change.get("reason"):
132
+ change = {**change, "reason": "容器化与部署适配"}
133
+ validate_file_change(source, change)
134
+ resolved_changes.append(change)
135
+ proposal["changes"] = resolved_changes
136
+
137
+ discovery_report = None
138
+ transformation_report = None
139
+ contract = proposal.get("contract")
140
+ if expected_port is not None and not proposal.get("unresolved") and (contract or {}).get("runtime", {}).get("port") != expected_port:
141
+ raise ValueError("模型不能静默改变用户选择的容器端口")
142
+ if isinstance(contract, dict) and source.is_dir():
143
+ job_meta = {
144
+ "slug": contract.get("slug", ""),
145
+ "name": contract.get("name", contract.get("slug", "")),
146
+ "description": contract.get("description", ""),
147
+ "app_url": contract.get("base_url", ""),
148
+ "port": (contract.get("runtime") or {}).get("port", 8080) if isinstance(contract.get("runtime"), dict) else 8080,
149
+ "revision": revision_count,
150
+ "analysis_mode": "repair" if repair else "analysis",
151
+ "feedback": feedback_text,
152
+ }
153
+ try:
154
+ enrich_contract_and_discovery_report(source, job_meta, proposal)
155
+ discovery_report = proposal.pop("discovery_report", None)
156
+ transformation_report = proposal.pop("transformation_report", None)
157
+ except Exception:
158
+ proposal.pop("discovery_report", None)
159
+ proposal.pop("transformation_report", None)
160
+
161
+ if repair and failed_revision and failed_revision.isalnum():
162
+ failed_archive = root / failed_revision / "bundle/app.tar"
163
+ if failed_archive.is_file():
164
+ failed_read = set(load_json_if_exists(root / "failed_files_read.json", []))
165
+ if not failed_read:
166
+ raise ValueError("修复模式必须先调用 read_failed 读取实际失败制品,不能仅复用旧提案")
167
+ if re.search(r"SyntaxError|ReferenceError|TypeError|ModuleNotFound|Cannot find module", failure_feedback or ""):
168
+ changed = False
169
+ for change in proposal.get("changes", []):
170
+ try:
171
+ old = read_archive_file(failed_archive, change["path"])
172
+ except ValueError:
173
+ changed = True
174
+ continue
175
+ changed = changed or old != change["content"]
176
+ if not changed:
177
+ raise ValueError("本轮未修改失败制品中的文件,不能将相同程序错误标记为已修复;请读取出错文件并修正")
178
+
179
+ if isinstance(contract, dict):
180
+ for config in contract.get("configs", []):
181
+ if not isinstance(config, dict):
182
+ raise ValueError("配置项必须是对象")
183
+ if config.get("source") is not None:
184
+ original_value(source, config["source"])
185
+
186
+ unresolved_all = list(proposal.get("unresolved") or []) + list(contract.get("unresolved") or [])
187
+ decisions = proposal.get("decisions", [])
188
+ if decisions is not None:
189
+ if not isinstance(decisions, list):
190
+ raise ValueError("decisions 必须是列表")
191
+ decision_ids = set()
192
+ for decision in decisions:
193
+ if (
194
+ not isinstance(decision, dict)
195
+ or not isinstance(decision.get("id"), str)
196
+ or not decision["id"]
197
+ or decision["id"] in decision_ids
198
+ or decision.get("question") not in unresolved_all
199
+ or not isinstance(decision.get("impact", ""), str)
200
+ or not isinstance(decision.get("options"), list)
201
+ or len(decision["options"]) > 4
202
+ or any(not isinstance(opt, str) or not opt.strip() for opt in decision["options"])
203
+ ):
204
+ raise ValueError("每项决定须关联未解决问题、使用唯一 ID 并给出至多四个可选回答")
205
+ decision_ids.add(decision["id"])
206
+
207
+ if not unresolved_all:
208
+ bindings = {_fingerprint(c["source"]) for c in contract.get("configs", []) if isinstance(c, dict) and c.get("source")}
209
+ for change in proposal.get("changes", []):
210
+ for field in original_fields(source, change["path"]):
211
+ ref = field["source"]
212
+ if field["has_value"] and re.search(d.SECRET_KEY, "_".join(map(str, ref["keys"])), re.I) and _fingerprint(ref) not in bindings:
213
+ raise ValueError(
214
+ "原有敏感配置必须保留并通过 source 引用注入,不能清空:"
215
+ + ref["path"]
216
+ + " / "
217
+ + ".".join(map(str, ref["keys"]))
218
+ )
219
+
220
+ validate_auth_questions(proposal)
221
+ resolve_authentication(contract)
222
+ validate_auth_evidence(source, proposal)
223
+ d.validate_credential_references(contract)
224
+ if not proposal.get("unresolved") and not contract.get("unresolved"):
225
+ validate_auth_probe_coverage(contract)
226
+
227
+ return proposal, discovery_report, transformation_report
228
+
229
+
230
+ def apply_plan(root, proposal, target, *, repair=False, failed_revision="", failure_feedback="", expected_port=None, revision_count=1, feedback_text=""):
231
+ original = root / "review"
232
+ d.require(d.inspect_source(original / "source")[0] == d.load(original / "inventory.json")["files"], "Source changed; import again")
233
+ d.require(isinstance(proposal.get("summary"), str) and proposal["summary"].strip(), "summary required")
234
+ d.require(not proposal.get("unresolved"), "Resolve outstanding questions before preparation")
235
+ proposal, discovery_report, transformation_report = resolve_and_enrich_proposal(
236
+ root,
237
+ proposal,
238
+ repair=repair,
239
+ failed_revision=failed_revision,
240
+ failure_feedback=failure_feedback,
241
+ expected_port=expected_port,
242
+ revision_count=revision_count,
243
+ feedback_text=feedback_text,
244
+ )
245
+ shutil.copytree(original, target)
246
+ seen = set()
247
+ for change in proposal.get("changes", []):
248
+ name = change["path"]
249
+ d.require(name not in seen, "Duplicate file change")
250
+ seen.add(name)
251
+ p = d.relative(target / "source", name)
252
+ executable = (p.exists() and p.stat().st_mode & 0o111) or change.get("executable") is True
253
+ d.require(isinstance(change.get("content"), str) and len(change["content"]) <= 2_000_000, "Invalid complete file content")
254
+ p.parent.mkdir(parents=True, exist_ok=True)
255
+ p.write_text(change["content"], encoding="utf-8")
256
+ p.chmod(0o700 if executable else 0o600)
257
+ contract = proposal["contract"]
258
+ d.require(contract["health"]["path"] == "/healthz" and contract["health"]["json_contains"].get("service") == contract["slug"], "Platform requires /healthz with service=slug")
259
+ d.save(target / "app-contract.json", contract)
260
+ d.save(target / "review.json", {"kind": "ai-technical", "scope": "deployment-adaptation", "source": "DSH isolated preparation; deployment requires separate user confirmation", "approved_issue_ids": [c["id"] for c in proposal.get("changes", [])] or ["NO_SOURCE_CHANGES"], "unresolved": []})
261
+ (target / "analysis.md").write_text(proposal["summary"], encoding="utf-8")
262
+ d.check_work(target)
263
+ return proposal, discovery_report, transformation_report
264
+
265
+
266
+ def extract_original_config_values(source: Path, configs: list[dict]) -> tuple[dict[str, str], list[str]]:
267
+ values: dict[str, str] = {}
268
+ has_original_keys: list[str] = []
269
+ for cfg in configs:
270
+ if isinstance(cfg, dict) and cfg.get("source"):
271
+ try:
272
+ val = original_value(source, cfg["source"])
273
+ if val:
274
+ values[cfg["key"]] = val
275
+ has_original_keys.append(cfg["key"])
276
+ except Exception:
277
+ pass
278
+ return values, has_original_keys
279
+
280
+
281
+ def main(body):
282
+ root = Path(body["root"]).resolve()
283
+ action = body["action"]
284
+ if action == "redact_feedback":
285
+ return redact(str(body.get("text", "")))
286
+ if action == "handoff":
287
+ job = body["job"]
288
+ revision = job.get("revision")
289
+ d.require(not revision or (isinstance(revision, str) and revision.isalnum()), "Invalid revision")
290
+ source = root / revision / "approved/source" if revision else root / "review/source"
291
+ inventory, _ = d.inspect_source(source)
292
+ snapshot = root / "handoff" / uuid.uuid4().hex
293
+ snapshot.mkdir(parents=True, mode=0o700)
294
+ for entry in inventory:
295
+ name = entry["path"]
296
+ src, dest = d.relative(source, name), d.relative(snapshot, name)
297
+ dest.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
298
+ shutil.copy2(src, dest)
299
+ plan = job["proposal"]
300
+ prompt = (
301
+ f"请改造应用 {job['name']},保持标识 {job['slug']}、地址 {job['url']} 和端口 {job.get('port', 8080)}。\n"
302
+ f"独立源码副本:{snapshot}。先复制到新目录再修改。\n"
303
+ "保留原业务、认证、数据库和数据卷。依据实际登录与权限代码规划凭据引用,"
304
+ "秘密值只在受保护输入中提供。补齐 Dockerfile 和 /healthz,明确区分构建、健康、"
305
+ "只读业务及页面验证。提供可重新导入的源码,不直接发布。\n"
306
+ f"此前改造摘要(待核实):\n{redact(plan.get('summary', ''))}\n"
307
+ f"待确认事项:{redact(json.dumps(plan.get('unresolved', []), ensure_ascii=False))}"
308
+ )
309
+ return {"prompt": prompt, "source_path": str(snapshot)}
310
+ if action == "validate_credential_references":
311
+ d.validate_credential_references(body["contract"])
312
+ return {"valid": True}
313
+ if action == "validate_verification_contract":
314
+ d.validate_credential_references(body["contract"])
315
+ validate_auth_probe_coverage(body["contract"])
316
+ return {"valid": True}
317
+ if action == "prepare":
318
+ with contextlib.redirect_stdout(io.StringIO()):
319
+ d.prepare(argparse.Namespace(archive=body["source"], work_dir=str(root / "review"), slug=body["slug"], url=body["url"]))
320
+ return {"imported": True}
321
+ if action == "inventory":
322
+ files = d.load(root / "review/inventory.json")["files"]
323
+ start = max(0, int(body.get("start", 1)) - 1)
324
+ return {"files": [{"path": f["path"], "bytes": f["bytes"]} for f in files[start:start+500]], "total": len(files)}
325
+ if action == "read":
326
+ source_dir = root / "review/source"
327
+ p = d.relative(source_dir, body["path"])
328
+ content = d.text_of(p)
329
+ if content is None:
330
+ return {"text": "Binary file"}
331
+ start = max(0, int(body.get("start", 1)) - 1)
332
+ lines = redact(content, body["path"]).splitlines()
333
+ excerpt = "\n".join(f"{i + start + 1}: {s[:400]}" for i, s in enumerate(lines[start:start+200]))
334
+ returned = len(lines[start:start+200])
335
+ range_info = f"返回第 {start + 1}–{start + returned} 行" if returned else "所请求范围无内容"
336
+ excerpt = f"{body['path']} 共 {len(lines)} 行,{range_info}。\n{excerpt}"
337
+ fields = original_fields(source_dir, body["path"])
338
+ if fields:
339
+ excerpt += "\nOriginal configuration references (metadata only; values stay local):\n" + json.dumps(fields, ensure_ascii=False)
340
+ return {"text": excerpt, "total_lines": len(lines)}
341
+ if action == "read_failed":
342
+ revision = body.get("revision", "")
343
+ d.require(isinstance(revision, str) and revision.isalnum(), "Invalid revision")
344
+ name = body["path"]
345
+ d.relative(root, name)
346
+ archive = root / revision / "bundle/app.tar"
347
+ with tarfile.open(archive) as tar:
348
+ matches = [item for item in tar if item.name == name]
349
+ d.require(len(matches) == 1 and matches[0].isfile() and matches[0].size <= 2_000_000, "Failed artifact file missing or unsafe")
350
+ content = tar.extractfile(matches[0]).read().decode("utf-8")
351
+ failed_read_path = root / "failed_files_read.json"
352
+ failed_read = set(load_json_if_exists(failed_read_path, []))
353
+ failed_read.add(name)
354
+ d.save(failed_read_path, sorted(failed_read))
355
+ start = max(0, int(body.get("start", 1)) - 1)
356
+ lines = redact(content, name).splitlines()
357
+ return {"text": "\n".join(f"{i + start + 1}: {line[:400]}" for i, line in enumerate(lines[start:start+200])), "total_lines": len(lines)}
358
+ if action == "reference":
359
+ d.require(body["name"] in {"contract.md", "framework-checks.md", "preparation-checks.md", "integration.md"}, "Unknown reference")
360
+ return {"text": (Path(__file__).parent / "app_delivery/references" / body["name"]).read_text(encoding="utf-8")}
361
+ if action == "scan_routes_and_pages":
362
+ res = scan_app_routes_and_pages(root / "review/source")
363
+ d.save(root / "routes_scanned.json", {"scanned": True})
364
+ res["_auto_contract_enrichment"] = (
365
+ "系统已在后端自动缓存全部扫描到的 API 接口与页面视图。你在调用 opc_delivery_submit 时,"
366
+ "后端会自动将全部扫描到的接口与页面 100% 合并注入 contract.apis 与 contract.pages 中。"
367
+ "你无需重复手写几十个接口对象(传空数组 [] 或仅传需定制覆盖的接口即可),"
368
+ "也严禁把接口数量多或扫描问题写入 unresolved!"
369
+ )
370
+ return res
371
+ if action == "inspect_local_storage":
372
+ return inspect_local_sqlite_files(root / "review/source", str(body.get("path", "")))
373
+ if action == "read_go_dependency":
374
+ target = dependency_path(root / "review/source", str(body.get("module", "")), str(body.get("path", "")))
375
+ if not isinstance(target, Path):
376
+ return {"entries": target}
377
+ content = d.text_of(target)
378
+ if content is None:
379
+ return {"text": "Binary dependency file; provide source or interface documentation"}
380
+ start = max(0, int(body.get("start", 1)) - 1)
381
+ rows = redact(content, str(body.get("path", ""))).splitlines()
382
+ return {"text": "\n".join(f"{i + start + 1}: {line[:400]}" for i, line in enumerate(rows[start:start+200])), "total_lines": len(rows)}
383
+ if action == "filter_resources":
384
+ resources = body.get("resources") or []
385
+ slug = str(body.get("slug") or "")
386
+ default_only = bool(body.get("default_only", False))
387
+ return {"resources": select_and_filter_platform_resources(resources, slug, default_only=default_only)}
388
+ if action == "propose_file":
389
+ change = {
390
+ "id": str(body.get("id") or body.get("path") or ""),
391
+ "path": str(body.get("path") or ""),
392
+ "reason": str(body.get("reason") or "容器化与部署适配"),
393
+ "content": body.get("content"),
394
+ "executable": bool(body.get("executable", False)),
395
+ "group": str(body.get("group") or ""),
396
+ }
397
+ validate_file_change(root / "review/source", change)
398
+ draft_path = root / "draft_files.json"
399
+ drafts = load_json_if_exists(draft_path, {})
400
+ cid = change["id"]
401
+ if cid in drafts and drafts[cid].get("path") != change["path"]:
402
+ raise ValueError("同一修改 ID 不能对应不同文件")
403
+ drafts[cid] = change
404
+ d.save(draft_path, drafts)
405
+ return {"staged": cid, "path": change["path"], "message": f"File proposal recorded: {cid}. Source is unchanged."}
406
+ if action == "validate":
407
+ proposal = body["proposal"]
408
+ repair_flag = bool(body.get("repair"))
409
+ failed_rev = str(body.get("failed_revision") or "")
410
+ failure_fb = str(body.get("failure_feedback") or "")
411
+ rev_count = int(body.get("revision_count") or 1)
412
+ fb_text = str(body.get("feedback") or "")
413
+ source_dir = root / "review/source"
414
+ if proposal.get("unresolved") and body.get("allow_unresolved"):
415
+ proposal, discovery_report, transformation_report = resolve_and_enrich_proposal(
416
+ root,
417
+ proposal,
418
+ repair=repair_flag,
419
+ failed_revision=failed_rev,
420
+ failure_feedback=failure_fb,
421
+ revision_count=rev_count,
422
+ feedback_text=fb_text,
423
+ expected_port=body.get("expected_port"),
424
+ )
425
+ diffs = compute_change_diffs(source_dir, proposal.get("changes", []))
426
+ _, has_orig = extract_original_config_values(source_dir, (proposal.get("contract") or {}).get("configs", []))
427
+ return {
428
+ "valid": True,
429
+ "proposal": proposal,
430
+ "discovery_report": discovery_report,
431
+ "transformation_report": transformation_report,
432
+ "diffs": diffs,
433
+ "has_original_keys": has_orig,
434
+ }
435
+ with tempfile.TemporaryDirectory(dir=root, prefix="check-") as temp:
436
+ temp_path = Path(temp)
437
+ proposal, discovery_report, transformation_report = apply_plan(
438
+ root,
439
+ proposal,
440
+ temp_path / "approved",
441
+ repair=repair_flag,
442
+ failed_revision=failed_rev,
443
+ failure_feedback=failure_fb,
444
+ expected_port=body.get("expected_port"),
445
+ revision_count=rev_count,
446
+ feedback_text=fb_text,
447
+ )
448
+ d.bundle_work(temp_path / "approved", temp_path / "bundle")
449
+ syntax_check = check_archive_syntax(temp_path / "bundle/app.tar")
450
+ # Persist staged files for future rounds
451
+ draft_path = root / "draft_files.json"
452
+ drafts = load_json_if_exists(draft_path, {})
453
+ for ch in proposal.get("changes", []):
454
+ if isinstance(ch, dict) and ch.get("id") and ch.get("path") and isinstance(ch.get("content"), str):
455
+ drafts[ch["id"]] = dict(ch)
456
+ d.save(draft_path, drafts)
457
+ diffs = compute_change_diffs(source_dir, proposal.get("changes", []))
458
+ _, has_orig = extract_original_config_values(source_dir, (proposal.get("contract") or {}).get("configs", []))
459
+ return {
460
+ "valid": True,
461
+ "proposal": proposal,
462
+ "syntax_check": syntax_check,
463
+ "discovery_report": discovery_report,
464
+ "transformation_report": transformation_report,
465
+ "diffs": diffs,
466
+ "has_original_keys": has_orig,
467
+ }
468
+ if action == "bundle":
469
+ # Each revision has a fresh immutable destination. Failed revisions are never published.
470
+ dest = root / body["revision"]
471
+ d.require(body["revision"].isalnum(), "Invalid revision")
472
+ dest.mkdir(mode=0o700)
473
+ proposal = body["proposal"]
474
+ proposal, discovery_report, transformation_report = apply_plan(
475
+ root,
476
+ proposal,
477
+ dest / "approved",
478
+ repair=bool(body.get("repair")),
479
+ failed_revision=str(body.get("failed_revision") or ""),
480
+ failure_feedback=str(body.get("failure_feedback") or ""),
481
+ expected_port=body.get("expected_port"),
482
+ revision_count=int(body.get("revision_count") or 1),
483
+ feedback_text=str(body.get("feedback") or ""),
484
+ )
485
+ result = d.bundle_work(dest / "approved", dest / "bundle")
486
+ syntax_check = check_archive_syntax(dest / "bundle/app.tar")
487
+ skill_markdown = ""
488
+ try:
489
+ with zipfile.ZipFile(dest / "bundle/skill.zip") as zf:
490
+ skill_markdown = zf.read("SKILL.md").decode("utf-8")
491
+ except Exception:
492
+ pass
493
+ dockerfile_path = dest / "approved/source/Dockerfile"
494
+ dockerfile_content = dockerfile_path.read_text(encoding="utf-8", errors="replace") if dockerfile_path.is_file() else ""
495
+ source_dir = root / "review/source"
496
+ orig_values, has_orig = extract_original_config_values(source_dir, (proposal.get("contract") or {}).get("configs", []))
497
+ diffs = compute_change_diffs(source_dir, proposal.get("changes", []))
498
+ preparation_checks = [
499
+ syntax_check,
500
+ {"label": "原源码完整性", "status": "passed", "detail": "已核对分析时的源码摘要,改造在独立副本完成"},
501
+ {"label": "交付文件与业务技能契约", "status": "passed", "detail": "已通过打包器的构建输入、配置和业务契约校验;不是编译或运行测试"},
502
+ {"label": "服务器构建、启动与业务访问", "status": "pending", "detail": "确认部署后在目标服务器验证"},
503
+ ]
504
+ return {
505
+ "summary": result,
506
+ "proposal": proposal,
507
+ "syntax_check": syntax_check,
508
+ "preparation_checks": preparation_checks,
509
+ "discovery_report": discovery_report,
510
+ "transformation_report": transformation_report,
511
+ "skill_markdown": skill_markdown,
512
+ "dockerfile_content": dockerfile_content,
513
+ "original_config_values": orig_values,
514
+ "has_original_keys": has_orig,
515
+ "diffs": diffs,
516
+ }
517
+ if action == "extract_skill_contract":
518
+ zip_bytes = base64.b64decode(body["skill_zip_b64"], validate=True)
519
+ actual_sha = d.sha(zip_bytes)
520
+ expected_sha = str(body.get("expected_sha256") or "").strip().lower()
521
+ if expected_sha and actual_sha != expected_sha:
522
+ raise ValueError("回滚技能包摘要不一致,拒绝启用")
523
+ skill_markdown = ""
524
+ with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
525
+ ops_name = next(
526
+ (n for n in zf.namelist() if n == "references/operations.json" or n.endswith("/references/operations.json")),
527
+ None,
528
+ )
529
+ if not ops_name:
530
+ raise ValueError("回退技能包缺少有效的 references/operations.json")
531
+ ops_raw = zf.read(ops_name).decode("utf-8")
532
+ contract = json.loads(ops_raw)
533
+ d.validate_credential_references(contract)
534
+ md_name = next((n for n in zf.namelist() if n == "SKILL.md" or n.endswith("/SKILL.md")), None)
535
+ if md_name:
536
+ skill_markdown = zf.read(md_name).decode("utf-8", errors="replace")
537
+ expected_slug = str(body.get("slug") or "").strip()
538
+ if expected_slug and contract.get("slug") != expected_slug:
539
+ raise ValueError("回退技能包的标识与当前应用不一致")
540
+ expected_url = str(body.get("app_url") or "").strip()
541
+ if expected_url and str(contract.get("base_url", "")).rstrip("/") != expected_url.rstrip("/"):
542
+ raise ValueError("回退技能包的访问地址与当前应用不一致")
543
+ return {"contract": contract, "sha256": actual_sha, "skill_markdown": skill_markdown}
544
+ if action == "probe":
545
+ contract = body["contract"]
546
+ credentials = body.get("credentials", {})
547
+ approve_write = bool(body.get("approved"))
548
+ operation_id = body["operation"]
549
+ api_def = next((a for a in (contract.get("apis") or []) if isinstance(a, dict) and a.get("id") == operation_id), {})
550
+ is_readonly = not approve_write and api_def.get("effect", "read") == "read"
551
+ max_attempts = 3 if is_readonly else 1
552
+ result = None
553
+ for attempt in range(max_attempts):
554
+ try:
555
+ # No ambient host credentials or proxy configuration enters an application call.
556
+ result = execute(contract, operation_id, body.get("params", {}), body=body.get("body"), approve_write=approve_write, credential_env=credentials)
557
+ except OSError as exc:
558
+ if attempt == max_attempts - 1:
559
+ raise ValueError(f"{operation_id} 验证请求失败({type(exc).__name__})") from exc
560
+ else:
561
+ if result[0] not in {502, 503, 504} or attempt == max_attempts - 1:
562
+ break
563
+ time.sleep(0.5 * (attempt + 1))
564
+ d.require(result is not None and len(result[2]) <= 2_000_000, "Response exceeds 2 MB")
565
+ return {"status": result[0], "content_type": result[1], "content": result[2].decode("utf-8", errors="replace")}
566
+ raise ValueError("Unknown worker action")
567
+
568
+
569
+ if __name__ == "__main__":
570
+ try:
571
+ print(json.dumps({"ok": True, "value": main(json.load(sys.stdin))}, ensure_ascii=False))
572
+ except Exception as exc:
573
+ print(json.dumps({"ok": False, "error": redact(str(exc))[:2000]}, ensure_ascii=False))
574
+ sys.exit(1)