dsh-plugin-opc 0.1.29 → 0.1.30

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.
package/runtime/worker.py CHANGED
@@ -116,14 +116,16 @@ def compute_change_diffs(source: Path, changes: list[dict]) -> dict[str, str]:
116
116
 
117
117
  def save_draft_files(path: Path, drafts: dict) -> None:
118
118
  # A cancelled worker must leave the previous complete checkpoint readable.
119
- with tempfile.NamedTemporaryFile(dir=path.parent, prefix="draft-files-", mode="w", encoding="utf-8", delete=False) as tmp:
120
- tmp_path = Path(tmp.name)
121
- try:
119
+ path.parent.mkdir(parents=True, exist_ok=True)
120
+ tmp_path: Path | None = None
121
+ try:
122
+ with tempfile.NamedTemporaryFile(dir=path.parent, prefix="draft-files-", suffix=".tmp", mode="w", encoding="utf-8", delete=False) as tmp:
123
+ tmp_path = Path(tmp.name)
122
124
  json.dump(drafts, tmp, ensure_ascii=False, indent=2)
123
125
  tmp.write("\n")
124
- tmp.close()
125
- tmp_path.replace(path)
126
- finally:
126
+ d.atomic_replace(tmp_path, path)
127
+ finally:
128
+ if tmp_path is not None:
127
129
  tmp_path.unlink(missing_ok=True)
128
130
 
129
131
 
@@ -159,26 +161,32 @@ def resolve_and_enrich_proposal(
159
161
  source = root / "review/source"
160
162
  draft_files = load_json_if_exists(root / "draft_files.json", {})
161
163
  resolved_changes = []
164
+ change_errors: list[str] = []
162
165
  for idx, change in enumerate(proposal.get("changes", [])):
163
- if isinstance(change, dict) and "content" not in change:
164
- cid = change.get("id") or change.get("path")
165
- if cid and cid in draft_files:
166
- staged = draft_files[cid]
167
- if change.get("path") and staged.get("path") and change["path"] != staged["path"]:
168
- raise ValueError(f"汇总提案的文件路径与分项提案不一致:{cid} 已对应 {staged['path']},本次提交 {change['path']}。请核对路径")
169
- change = {**staged, **change}
170
- elif not change.get("id") and change.get("path"):
171
- by_path = next((v for v in draft_files.values() if isinstance(v, dict) and v.get("path") == change["path"]), None)
172
- if by_path:
173
- change = {**by_path, **change}
174
- if "content" not in change:
175
- raise ValueError(f"changes[{idx}] 没有文件内容。请使用已暂存的修改 ID,或先单独暂存该文件")
176
- if isinstance(change, dict) and not change.get("id"):
177
- change = {**change, "id": change.get("path") or f"change-{idx + 1}"}
178
- if isinstance(change, dict) and not change.get("reason"):
179
- change = {**change, "reason": "容器化与部署适配"}
180
- validate_file_change(source, change)
181
- resolved_changes.append(change)
166
+ try:
167
+ if isinstance(change, dict) and "content" not in change:
168
+ cid = change.get("id") or change.get("path")
169
+ if cid and cid in draft_files:
170
+ staged = draft_files[cid]
171
+ if change.get("path") and staged.get("path") and change["path"] != staged["path"]:
172
+ raise ValueError(f"汇总提案的文件路径与分项提案不一致:{cid} 已对应 {staged['path']},本次提交 {change['path']}。请核对路径")
173
+ change = {**staged, **change}
174
+ elif not change.get("id") and change.get("path"):
175
+ by_path = next((v for v in draft_files.values() if isinstance(v, dict) and v.get("path") == change["path"]), None)
176
+ if by_path:
177
+ change = {**by_path, **change}
178
+ if "content" not in change:
179
+ raise ValueError(f"changes[{idx}] 没有文件内容。请使用已暂存的修改 ID,或先单独暂存该文件")
180
+ if isinstance(change, dict) and not change.get("id"):
181
+ change = {**change, "id": change.get("path") or f"change-{idx + 1}"}
182
+ if isinstance(change, dict) and not change.get("reason"):
183
+ change = {**change, "reason": "容器化与部署适配"}
184
+ validate_file_change(source, change)
185
+ resolved_changes.append(change)
186
+ except ValueError as exc:
187
+ change_errors.append(str(exc))
188
+ if change_errors:
189
+ raise ValueError("\n".join(dict.fromkeys(change_errors)))
182
190
  proposal["changes"] = resolved_changes
183
191
  for key in ("id", "path"):
184
192
  d.require(len({change[key] for change in resolved_changes}) == len(resolved_changes), "修改项 ID 和路径必须唯一")
@@ -222,48 +230,84 @@ def resolve_and_enrich_proposal(
222
230
  raise ValueError("本轮未修改失败制品中的文件,不能将相同程序错误标记为已修复;请读取出错文件并修正")
223
231
 
224
232
  if isinstance(contract, dict):
225
- for config in contract.get("configs", []):
226
- if not isinstance(config, dict):
227
- raise ValueError("配置项必须是对象")
228
- if not isinstance(config.get("key"), str) or not d.ENV_NAME.fullmatch(config["key"]):
229
- raise ValueError("配置键名无效")
230
- if type(config.get("secret")) is not bool or type(config.get("required")) is not bool or not isinstance(config.get("default", ""), str):
231
- raise ValueError("配置必须声明 secret、required 和字符串默认值")
232
- if config["secret"] and config.get("default"):
233
- raise ValueError(f"秘密配置 {config['key']} 不能包含默认值。原值仅通过 source 引用。")
234
- if config.get("source") is not None:
235
- original_value(source, config["source"])
236
-
237
- validate_config_origins(root, contract)
233
+ errors: list[str] = []
234
+ configs = contract.get("configs", [])
235
+ valid_config_dicts = isinstance(configs, list)
236
+ if not valid_config_dicts:
237
+ errors.append("配置列表必须是数组")
238
+ else:
239
+ for config in configs:
240
+ if not isinstance(config, dict):
241
+ errors.append("配置项必须是对象")
242
+ valid_config_dicts = False
243
+ continue
244
+ if not isinstance(config.get("key"), str) or not d.ENV_NAME.fullmatch(config["key"]):
245
+ errors.append("配置键名无效")
246
+ valid_config_dicts = False
247
+ continue
248
+ if type(config.get("secret")) is not bool or type(config.get("required")) is not bool or not isinstance(config.get("default", ""), str):
249
+ errors.append("配置必须声明 secret、required 和字符串默认值")
250
+ elif config["secret"] and config.get("default"):
251
+ errors.append(f"秘密配置 {config['key']} 不能包含默认值。原值仅通过 source 引用。")
252
+ if config.get("source") is not None:
253
+ try:
254
+ original_value(source, config["source"])
255
+ except ValueError as exc:
256
+ errors.append(str(exc))
257
+
258
+ if valid_config_dicts:
259
+ try:
260
+ validate_config_origins(root, contract)
261
+ except ValueError as exc:
262
+ errors.extend(line for line in str(exc).splitlines() if line)
238
263
 
239
264
  unresolved_all = list(proposal.get("unresolved") or []) + list(contract.get("unresolved") or [])
240
265
  decisions = proposal.get("decisions", [])
241
266
  if decisions is not None:
242
267
  if not isinstance(decisions, list):
243
- raise ValueError("decisions 必须是列表")
244
- decision_ids = set()
245
- for decision in decisions:
246
- if (
247
- not isinstance(decision, dict)
248
- or not isinstance(decision.get("id"), str)
249
- or not decision["id"]
250
- or decision["id"] in decision_ids
251
- or decision.get("question") not in unresolved_all
252
- or not isinstance(decision.get("impact", ""), str)
253
- or not isinstance(decision.get("options"), list)
254
- or len(decision["options"]) > 4
255
- or any(not isinstance(opt, str) or not opt.strip() for opt in decision["options"])
256
- ):
257
- raise ValueError("每项决定须关联未解决问题、使用唯一 ID 并给出至多四个可选回答")
258
- decision_ids.add(decision["id"])
259
-
260
- validate_auth_questions(proposal)
261
- resolve_authentication(contract)
262
- validate_auth_evidence(source, proposal)
263
- d.validate_credential_references(contract)
264
- validate_account_plan(source, contract)
268
+ errors.append("decisions 必须是列表")
269
+ else:
270
+ decision_ids = set()
271
+ for decision in decisions:
272
+ if (
273
+ not isinstance(decision, dict)
274
+ or not isinstance(decision.get("id"), str)
275
+ or not decision["id"]
276
+ or decision["id"] in decision_ids
277
+ or decision.get("question") not in unresolved_all
278
+ or not isinstance(decision.get("impact", ""), str)
279
+ or not isinstance(decision.get("options"), list)
280
+ or len(decision["options"]) > 4
281
+ or any(not isinstance(opt, str) or not opt.strip() for opt in decision["options"])
282
+ ):
283
+ errors.append("每项决定须关联未解决问题、使用唯一 ID 并给出至多四个可选回答")
284
+ break
285
+ decision_ids.add(decision["id"])
286
+
287
+ checks = [
288
+ lambda: validate_auth_questions(proposal),
289
+ lambda: resolve_authentication(contract),
290
+ lambda: validate_auth_evidence(source, proposal),
291
+ lambda: d.validate_credential_references(contract),
292
+ lambda: validate_account_plan(source, contract),
293
+ ]
265
294
  if not proposal.get("unresolved") and not contract.get("unresolved"):
266
- validate_auth_probe_coverage(contract)
295
+ checks.append(lambda: validate_auth_probe_coverage(contract))
296
+ for check in checks:
297
+ try:
298
+ check()
299
+ except ValueError as exc:
300
+ errors.extend(line for line in str(exc).splitlines() if line)
301
+
302
+ errors = list(dict.fromkeys(errors))
303
+ if errors:
304
+ if len(errors) == 1:
305
+ raise ValueError(errors[0])
306
+ shown = errors[:12]
307
+ formatted = "\n".join(f"{i}. {msg}" for i, msg in enumerate(shown, 1))
308
+ if len(errors) > 12:
309
+ formatted += f"\n...另有 {len(errors) - 12} 项未列出,请先修正以上问题。"
310
+ raise ValueError(f"发现 {len(errors)} 项提案校验问题,请一次性修正后重新提交:\n{formatted}")
267
311
 
268
312
  return proposal, discovery_report, transformation_report
269
313
 
@@ -461,15 +505,24 @@ def validate_config_origins(root: Path, contract: dict):
461
505
  origins = historical_config_origins(root, source)
462
506
  generated_keys, _ = origins
463
507
  references = set(source_configuration(root, origins)["references"])
508
+ errors = []
464
509
  for config in configs:
465
510
  key = config["key"]
466
- d.require(not config.get("default"), "原应用配置只能引用已有值,AI 不可提交默认值:" + key)
511
+ if config.get("default"):
512
+ errors.append("原应用配置只能引用已有值,AI 不可提交默认值:" + key)
467
513
  ref = config.get("source")
514
+ original_key = False
468
515
  if ref is not None:
469
- original_value(source, ref)
470
- original_key = ref is not None and ref["keys"][-1] == key
471
- d.require(key not in generated_keys and (original_key or key in references),
472
- "原应用没有可核实的配置键:" + key)
516
+ try:
517
+ original_value(source, ref)
518
+ original_key = ref["keys"][-1] == key
519
+ except ValueError as exc:
520
+ errors.append(str(exc))
521
+ continue
522
+ if key in generated_keys or not (original_key or key in references):
523
+ errors.append("原应用没有可核实的配置键:" + key)
524
+ if errors:
525
+ raise ValueError("\n".join(dict.fromkeys(errors)))
473
526
 
474
527
 
475
528
 
@@ -538,7 +591,20 @@ def main(body):
538
591
  if action == "inventory":
539
592
  files = d.load(root / "review/inventory.json")["files"]
540
593
  start = max(0, int(body.get("start", 1)) - 1)
541
- return {"files": [{"path": f["path"], "bytes": f["bytes"]} for f in files[start:start+500]], "total": len(files)}
594
+ result: dict = {"files": [{"path": f["path"], "bytes": f["bytes"]} for f in files[start:start+500]], "total": len(files)}
595
+ if start == 0 and (root / "review/source").is_dir():
596
+ try:
597
+ cfg = source_configuration(root)
598
+ result["source_configuration"] = {
599
+ "config_files": [
600
+ {"path": f["path"], "keys": [field["key"] for field in f.get("fields", [])]}
601
+ for f in cfg.get("files", [])
602
+ ],
603
+ "env_references": cfg.get("references", []),
604
+ }
605
+ except Exception:
606
+ pass
607
+ return result
542
608
  if action == "read":
543
609
  source_dir = root / "review/source"
544
610
  path = body["path"]
@@ -797,6 +863,12 @@ def main(body):
797
863
 
798
864
 
799
865
  if __name__ == "__main__":
866
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
867
+ if hasattr(stream, "reconfigure"):
868
+ try:
869
+ stream.reconfigure(encoding="utf-8")
870
+ except Exception:
871
+ pass
800
872
  try:
801
873
  print(json.dumps({"ok": True, "value": main(json.load(sys.stdin))}, ensure_ascii=False))
802
874
  except Exception as exc: