feat(mcp): harden remote assets and job execution
Gate source-file downloads and verify registry paths and content hashes. Stream multipart uploads with bounded limits, supervise OpenCode jobs with explicit result markers and timeouts, and preserve managed endpoint security settings. Document the trusted-client boundary and add focused regression coverage. Validation: PYTHONPATH=<staged-tree> python -m unittest discover -s tests (182 tests)
This commit is contained in:
+292
-82
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -20,21 +21,27 @@ from threading import RLock
|
||||
from typing import Any
|
||||
|
||||
from obsidian_wiki.file_assets import clean_config_value, db_path_for_vault, registry_path_for_vault
|
||||
from obsidian_wiki.mcp_jobs import ProcessOutcome, ProcessSupervisor, extract_final_answer, parse_marked_result
|
||||
|
||||
DEFAULT_INGEST_MAX_FILE_BYTES = 100 * 1024 * 1024
|
||||
DEFAULT_INGEST_MAX_CHUNK_BYTES = 4 * 1024 * 1024
|
||||
DEFAULT_INGEST_MAX_FILES_PER_JOB = 10
|
||||
DEFAULT_INGEST_MAX_REQUEST_BYTES = 0
|
||||
DEFAULT_UPLOAD_TICKET_SECONDS = 30 * 60
|
||||
MAX_UPLOAD_TICKET_SECONDS = 24 * 60 * 60
|
||||
DEFAULT_OPENCODE_PATH = "opencode"
|
||||
DEFAULT_INGEST_OPENCODE_MODEL = "openai/gpt-5.5"
|
||||
DEFAULT_INGEST_OPENCODE_VARIANT = "high"
|
||||
DEFAULT_OPENCODE_SMOKE_TIMEOUT_SECONDS = 120
|
||||
DEFAULT_INGEST_JOB_TIMEOUT_SECONDS = 30 * 60
|
||||
STREAM_COPY_CHUNK_BYTES = 1024 * 1024
|
||||
|
||||
SHA256_RE = re.compile(r"^(?:sha256:)?([0-9a-fA-F]{64})$")
|
||||
OPENCODE_REQUIRED_RUN_FLAGS = ("--format", "--auto", "--dir", "--title")
|
||||
OPENCODE_SMOKE_SUCCESS = "WIKI_INGEST_SKILL_LOADED"
|
||||
OPENCODE_SMOKE_FAILURE = "SKILL_LOAD_FAILED"
|
||||
INGEST_SUCCESS_MARKER = "MCP_INGEST_OK"
|
||||
INGEST_FAILURE_MARKER = "MCP_INGEST_FAILED"
|
||||
TERMINAL_JOB_STATES = {"succeeded", "failed", "cancelled"}
|
||||
|
||||
|
||||
@@ -73,6 +80,8 @@ class IngestManager:
|
||||
max_file_bytes: int = DEFAULT_INGEST_MAX_FILE_BYTES,
|
||||
max_chunk_bytes: int = DEFAULT_INGEST_MAX_CHUNK_BYTES,
|
||||
max_files_per_job: int = DEFAULT_INGEST_MAX_FILES_PER_JOB,
|
||||
max_request_bytes: int = DEFAULT_INGEST_MAX_REQUEST_BYTES,
|
||||
job_timeout_seconds: int = DEFAULT_INGEST_JOB_TIMEOUT_SECONDS,
|
||||
) -> None:
|
||||
self.vault = Path(clean_config_value(str(vault_path))).expanduser().resolve()
|
||||
self.project_root = Path(clean_config_value(str(project_root))).expanduser().resolve()
|
||||
@@ -88,14 +97,20 @@ class IngestManager:
|
||||
self.max_file_bytes = max_file_bytes
|
||||
self.max_chunk_bytes = max_chunk_bytes
|
||||
self.max_files_per_job = max_files_per_job
|
||||
self.max_request_bytes = max(0, int(max_request_bytes))
|
||||
self.job_timeout_seconds = max(1, int(job_timeout_seconds))
|
||||
self.upload_root = self.runtime_root / "uploads"
|
||||
self.jobs_root = self.runtime_root / "jobs"
|
||||
self.upload_ticket_root = self.runtime_root / "upload-tickets"
|
||||
self._lock = RLock()
|
||||
self._processes: dict[str, subprocess.Popen[Any]] = {}
|
||||
self._closing = False
|
||||
self.upload_root.mkdir(parents=True, exist_ok=True)
|
||||
self.jobs_root.mkdir(parents=True, exist_ok=True)
|
||||
self.upload_ticket_root.mkdir(parents=True, exist_ok=True)
|
||||
self._supervisor = ProcessSupervisor(
|
||||
self.runtime_root,
|
||||
popen_factory=lambda *args, **kwargs: subprocess.Popen(*args, **kwargs),
|
||||
)
|
||||
self._mark_interrupted_jobs()
|
||||
|
||||
def create_upload(
|
||||
@@ -143,23 +158,80 @@ class IngestManager:
|
||||
doc_type_hint: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
data = bytes(payload)
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
return self.create_completed_upload_from_stream(
|
||||
file_name=file_name,
|
||||
stream=io.BytesIO(data),
|
||||
size_bytes=len(data),
|
||||
project=project,
|
||||
doc_type_hint=doc_type_hint,
|
||||
)
|
||||
|
||||
def create_completed_upload_from_stream(
|
||||
self,
|
||||
file_name: str,
|
||||
stream: Any,
|
||||
*,
|
||||
size_bytes: int | None = None,
|
||||
project: str | None = None,
|
||||
doc_type_hint: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
name = self._validate_file_name(file_name)
|
||||
declared_size = None if size_bytes is None else int(size_bytes)
|
||||
if declared_size is not None and declared_size < 0:
|
||||
raise IngestError("size_bytes must be non-negative")
|
||||
if declared_size is not None and self.max_file_bytes > 0 and declared_size > self.max_file_bytes:
|
||||
raise IngestError(f"file exceeds max upload size: {declared_size} > {self.max_file_bytes}")
|
||||
|
||||
with self._lock:
|
||||
upload = self.create_upload(
|
||||
file_name=file_name,
|
||||
size_bytes=len(data),
|
||||
sha256=digest,
|
||||
project=project,
|
||||
doc_type_hint=doc_type_hint,
|
||||
)
|
||||
meta = self._load_upload(upload["upload_id"])
|
||||
path = Path(meta["path"])
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
meta["received_bytes"] = len(data)
|
||||
meta["updated_at"] = utc_now()
|
||||
self._write_json(self._upload_meta_path(path.parent), meta)
|
||||
return self.complete_upload(upload["upload_id"])
|
||||
upload_id = uuid.uuid4().hex
|
||||
month = datetime.now(timezone.utc).strftime("%Y-%m")
|
||||
upload_dir = self.upload_root / month / upload_id
|
||||
upload_dir.mkdir(parents=True, exist_ok=False)
|
||||
path = upload_dir / name
|
||||
received = 0
|
||||
hasher = hashlib.sha256()
|
||||
try:
|
||||
with path.open("xb") as destination:
|
||||
while True:
|
||||
chunk = stream.read(STREAM_COPY_CHUNK_BYTES)
|
||||
if not chunk:
|
||||
break
|
||||
if not isinstance(chunk, (bytes, bytearray, memoryview)):
|
||||
raise IngestError("upload stream must return bytes")
|
||||
data = bytes(chunk)
|
||||
received += len(data)
|
||||
if self.max_file_bytes > 0 and received > self.max_file_bytes:
|
||||
raise IngestError(
|
||||
f"file exceeds max upload size: {received} > {self.max_file_bytes}"
|
||||
)
|
||||
if declared_size is not None and received > declared_size:
|
||||
raise IngestError(
|
||||
f"upload size mismatch: received more than declared {declared_size} bytes"
|
||||
)
|
||||
destination.write(data)
|
||||
hasher.update(data)
|
||||
if declared_size is not None and received != declared_size:
|
||||
raise IngestError(f"upload size mismatch: {received} != {declared_size}")
|
||||
now = utc_now()
|
||||
meta = {
|
||||
"upload_id": upload_id,
|
||||
"state": "complete",
|
||||
"file_name": name,
|
||||
"size_bytes": received,
|
||||
"received_bytes": received,
|
||||
"sha256": hasher.hexdigest(),
|
||||
"project": self._safe_optional_text(project),
|
||||
"doc_type_hint": self._safe_optional_text(doc_type_hint),
|
||||
"path": str(path),
|
||||
"created_at": now,
|
||||
"completed_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
self._write_json(self._upload_meta_path(upload_dir), meta)
|
||||
return self._public_upload(meta)
|
||||
except Exception:
|
||||
shutil.rmtree(upload_dir, ignore_errors=True)
|
||||
raise
|
||||
|
||||
def create_upload_ticket(
|
||||
self,
|
||||
@@ -312,16 +384,53 @@ class IngestManager:
|
||||
self._write_json(self._upload_meta_path(path.parent), meta)
|
||||
return self._public_upload(meta)
|
||||
|
||||
def discard_upload(self, upload_id: str) -> bool:
|
||||
with self._lock:
|
||||
if any(upload_id in job.get("upload_ids", []) for job in self._iter_jobs()):
|
||||
return False
|
||||
meta = self._load_upload(upload_id)
|
||||
upload_dir = Path(meta["path"]).parent.resolve()
|
||||
if not path_is_relative_to(upload_dir, self.upload_root.resolve()):
|
||||
raise IngestError(f"upload path escapes runtime root: {upload_id}")
|
||||
shutil.rmtree(upload_dir)
|
||||
return True
|
||||
|
||||
def start_ingest_job(self, upload_ids: list[str], note: str | None = None) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
if self._closing:
|
||||
raise IngestError("ingest manager is closed")
|
||||
if not upload_ids:
|
||||
raise IngestError("upload_ids must not be empty")
|
||||
if len(set(upload_ids)) != len(upload_ids):
|
||||
raise IngestError("upload_ids must be unique")
|
||||
if len(upload_ids) > self.max_files_per_job:
|
||||
raise IngestError(f"too many files for one ingest job: {len(upload_ids)} > {self.max_files_per_job}")
|
||||
uploads = [self._load_upload(upload_id) for upload_id in upload_ids]
|
||||
for upload in uploads:
|
||||
if upload["state"] != "complete":
|
||||
raise IngestError(f"upload is not complete: {upload['upload_id']}")
|
||||
requested_upload_ids = tuple(upload_ids)
|
||||
claimed_jobs = [
|
||||
job
|
||||
for job in self._iter_jobs()
|
||||
if job.get("state") in {"queued", "running", "succeeded"}
|
||||
and set(upload_ids).intersection(job.get("upload_ids", []))
|
||||
]
|
||||
for claimed in claimed_jobs:
|
||||
if tuple(claimed.get("upload_ids", [])) == requested_upload_ids:
|
||||
return self._public_job(claimed)
|
||||
if claimed_jobs:
|
||||
claimed_ids = sorted(
|
||||
{
|
||||
upload_id
|
||||
for job in claimed_jobs
|
||||
for upload_id in job.get("upload_ids", [])
|
||||
if upload_id in upload_ids
|
||||
}
|
||||
)
|
||||
raise IngestError(
|
||||
"uploads are already assigned to another ingest job: " + ", ".join(claimed_ids)
|
||||
)
|
||||
job_id = uuid.uuid4().hex
|
||||
job_dir = self.jobs_root / job_id
|
||||
job_dir.mkdir(parents=True, exist_ok=False)
|
||||
@@ -331,6 +440,7 @@ class IngestManager:
|
||||
"upload_ids": upload_ids,
|
||||
"files": [self._public_upload(upload, expose_path=True) for upload in uploads],
|
||||
"note": self._safe_optional_text(note),
|
||||
"queue_sequence": time.time_ns(),
|
||||
"created_at": utc_now(),
|
||||
"updated_at": utc_now(),
|
||||
"started_at": None,
|
||||
@@ -343,7 +453,7 @@ class IngestManager:
|
||||
}
|
||||
self._write_job(job)
|
||||
self._start_next_job_locked()
|
||||
return self.get_job_status(job_id)
|
||||
return self.get_job_status(job_id)
|
||||
|
||||
def check_opencode_readiness(self, *, run_smoke_test: bool = False) -> dict[str, Any]:
|
||||
result: dict[str, Any] = {
|
||||
@@ -367,8 +477,8 @@ class IngestManager:
|
||||
return result
|
||||
|
||||
def get_job_status(self, job_id: str) -> dict[str, Any]:
|
||||
self.refresh_jobs()
|
||||
with self._lock:
|
||||
self.refresh_jobs()
|
||||
job = self._load_job(job_id)
|
||||
return self._public_job(job)
|
||||
|
||||
@@ -376,17 +486,16 @@ class IngestManager:
|
||||
return self.get_job_status(job_id)
|
||||
|
||||
def get_ingest_job_result(self, job_id: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
status = self.get_job_status(job_id)
|
||||
return {
|
||||
"job_id": status["job_id"],
|
||||
"state": status["state"],
|
||||
"summary": self._summary_for_status(status),
|
||||
"files": status["files"],
|
||||
"exit_code": status.get("exit_code"),
|
||||
"opencode_output_tail": status.get("log_tail", ""),
|
||||
"error": status.get("error", ""),
|
||||
}
|
||||
status = self.get_job_status(job_id)
|
||||
return {
|
||||
"job_id": status["job_id"],
|
||||
"state": status["state"],
|
||||
"summary": self._summary_for_status(status),
|
||||
"files": status["files"],
|
||||
"exit_code": status.get("exit_code"),
|
||||
"opencode_output_tail": status.get("log_tail", ""),
|
||||
"error": status.get("error", ""),
|
||||
}
|
||||
|
||||
def cancel_ingest_job(self, job_id: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
@@ -398,33 +507,32 @@ class IngestManager:
|
||||
self._write_job(job)
|
||||
return self._public_job(job)
|
||||
if job["state"] == "running":
|
||||
process = self._processes.get(job_id)
|
||||
if process is not None:
|
||||
process.terminate()
|
||||
job["state"] = "cancelled"
|
||||
job["finished_at"] = utc_now()
|
||||
job["updated_at"] = utc_now()
|
||||
job["exit_code"] = -15
|
||||
self._write_job(job)
|
||||
self._processes.pop(job_id, None)
|
||||
self._start_next_job_locked()
|
||||
return self._public_job(job)
|
||||
self._supervisor.cancel(job_id)
|
||||
return self._public_job(self._load_job(job_id))
|
||||
return self._public_job(job)
|
||||
|
||||
def refresh_jobs(self) -> None:
|
||||
self._supervisor.refresh()
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
for job_id, process in list(self._processes.items()):
|
||||
code = process.poll()
|
||||
if code is None:
|
||||
continue
|
||||
job = self._load_job(job_id)
|
||||
job["state"] = "succeeded" if code == 0 else "failed"
|
||||
job["exit_code"] = code
|
||||
job["finished_at"] = utc_now()
|
||||
job["updated_at"] = utc_now()
|
||||
self._write_job(job)
|
||||
self._processes.pop(job_id, None)
|
||||
self._start_next_job_locked()
|
||||
if self._closing:
|
||||
cancel_queued = False
|
||||
else:
|
||||
self._closing = True
|
||||
cancel_queued = True
|
||||
try:
|
||||
if cancel_queued:
|
||||
with self._lock:
|
||||
for job in self._iter_jobs():
|
||||
if job.get("state") == "queued":
|
||||
job["state"] = "cancelled"
|
||||
job["error"] = "ingest manager is shutting down"
|
||||
job["finished_at"] = utc_now()
|
||||
job["updated_at"] = utc_now()
|
||||
self._write_job(job)
|
||||
finally:
|
||||
self._supervisor.close()
|
||||
|
||||
def cleanup_runtime(self, *, max_age_days: int = 30) -> dict[str, Any]:
|
||||
if max_age_days <= 0:
|
||||
@@ -437,6 +545,7 @@ class IngestManager:
|
||||
"old_uploads_deleted": 0,
|
||||
"old_jobs_deleted": 0,
|
||||
}
|
||||
self.refresh_jobs()
|
||||
with self._lock:
|
||||
active_upload_ids = {
|
||||
str(upload_id)
|
||||
@@ -486,16 +595,26 @@ class IngestManager:
|
||||
return result
|
||||
|
||||
def _start_next_job_locked(self) -> None:
|
||||
if any(job.get("state") == "running" for job in self._iter_jobs()):
|
||||
if self._closing:
|
||||
return
|
||||
queued = [job for job in self._iter_jobs() if job.get("state") == "queued"]
|
||||
if not queued:
|
||||
return
|
||||
queued.sort(key=lambda job: job["created_at"])
|
||||
job = queued[0]
|
||||
self._launch_job_locked(job)
|
||||
while True:
|
||||
jobs = self._iter_jobs()
|
||||
if any(job.get("state") == "running" for job in jobs):
|
||||
return
|
||||
queued = [job for job in jobs if job.get("state") == "queued"]
|
||||
if not queued:
|
||||
return
|
||||
queued.sort(
|
||||
key=lambda job: (
|
||||
job.get("created_at", ""),
|
||||
int(job.get("queue_sequence") or 0),
|
||||
job.get("job_id", ""),
|
||||
)
|
||||
)
|
||||
if self._launch_job_locked(queued[0]):
|
||||
return
|
||||
|
||||
def _launch_job_locked(self, job: dict[str, Any]) -> None:
|
||||
def _launch_job_locked(self, job: dict[str, Any]) -> bool:
|
||||
readiness = self.check_opencode_readiness()
|
||||
job["preflight"] = readiness
|
||||
if not readiness["ok"]:
|
||||
@@ -504,7 +623,7 @@ class IngestManager:
|
||||
job["finished_at"] = utc_now()
|
||||
job["updated_at"] = utc_now()
|
||||
self._write_job(job)
|
||||
return
|
||||
return False
|
||||
prompt = self._build_prompt(job)
|
||||
args = [
|
||||
self.opencode_path,
|
||||
@@ -519,31 +638,83 @@ class IngestManager:
|
||||
f"MCP ingest {job['job_id']}",
|
||||
prompt,
|
||||
]
|
||||
log_path = Path(job["log_path"])
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
log_file = log_path.open("ab")
|
||||
job["state"] = "running"
|
||||
job["started_at"] = utc_now()
|
||||
job["updated_at"] = utc_now()
|
||||
self._write_job(job)
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
process = self._supervisor.start(
|
||||
job["job_id"],
|
||||
args,
|
||||
cwd=str(self.project_root),
|
||||
stdout=log_file,
|
||||
stderr=subprocess.STDOUT,
|
||||
log_path=job["log_path"],
|
||||
timeout_seconds=self.job_timeout_seconds,
|
||||
on_complete=self._handle_process_outcome,
|
||||
on_callback_error=self._handle_process_callback_error,
|
||||
)
|
||||
except OSError as exc:
|
||||
log_file.close()
|
||||
except (OSError, RuntimeError, ValueError) as exc:
|
||||
job["state"] = "failed"
|
||||
job["error"] = str(exc)
|
||||
job["finished_at"] = utc_now()
|
||||
job["updated_at"] = utc_now()
|
||||
self._write_job(job)
|
||||
return
|
||||
job["state"] = "running"
|
||||
job["started_at"] = utc_now()
|
||||
job["updated_at"] = utc_now()
|
||||
job["pid"] = process.pid
|
||||
self._processes[job["job_id"]] = process
|
||||
self._write_job(job)
|
||||
log_file.close()
|
||||
return False
|
||||
current = self._load_job(job["job_id"])
|
||||
if current.get("state") == "running":
|
||||
current["pid"] = process.pid
|
||||
self._write_job(current)
|
||||
return True
|
||||
|
||||
def _handle_process_callback_error(self, outcome: ProcessOutcome, error: Exception) -> None:
|
||||
with self._lock:
|
||||
try:
|
||||
job = self._load_job(outcome.job_id)
|
||||
except IngestError:
|
||||
return
|
||||
if job.get("state") == "running":
|
||||
job["state"] = "failed"
|
||||
job["exit_code"] = outcome.returncode
|
||||
job["error"] = f"ingest completion handling failed: {type(error).__name__}: {error}"
|
||||
job["finished_at"] = utc_now()
|
||||
job["updated_at"] = utc_now()
|
||||
self._write_job(job)
|
||||
self._start_next_job_locked()
|
||||
|
||||
def _handle_process_outcome(self, outcome: ProcessOutcome) -> None:
|
||||
with self._lock:
|
||||
try:
|
||||
job = self._load_job(outcome.job_id)
|
||||
except IngestError:
|
||||
return
|
||||
if job.get("state") != "running":
|
||||
return
|
||||
final_text = extract_final_answer(job["log_path"])
|
||||
protocol_ok, result_text, protocol_error = parse_marked_result(
|
||||
final_text,
|
||||
success_marker=INGEST_SUCCESS_MARKER,
|
||||
failure_marker=INGEST_FAILURE_MARKER,
|
||||
)
|
||||
job["exit_code"] = outcome.returncode
|
||||
job["finished_at"] = utc_now()
|
||||
job["updated_at"] = utc_now()
|
||||
job["result_text"] = result_text
|
||||
if outcome.cancelled:
|
||||
job["state"] = "cancelled"
|
||||
job["error"] = outcome.error
|
||||
elif outcome.timed_out:
|
||||
job["state"] = "failed"
|
||||
job["error"] = f"OpenCode ingest exceeded {self.job_timeout_seconds} seconds"
|
||||
elif outcome.returncode != 0:
|
||||
job["state"] = "failed"
|
||||
job["error"] = outcome.error or protocol_error or f"OpenCode exited with code {outcome.returncode}"
|
||||
elif not protocol_ok:
|
||||
job["state"] = "failed"
|
||||
job["error"] = protocol_error
|
||||
else:
|
||||
job["state"] = "succeeded"
|
||||
job["error"] = ""
|
||||
self._write_job(job)
|
||||
self._start_next_job_locked()
|
||||
|
||||
def _build_prompt(self, job: dict[str, Any]) -> str:
|
||||
file_lines = []
|
||||
@@ -582,6 +753,8 @@ class IngestManager:
|
||||
"",
|
||||
"After ingesting, archive sources into the vault source archive, update source registry/catalog/wiki metadata as normal, and run `obsidian-wiki file-index rebuild`.",
|
||||
"Return a concise success or failure summary, including whether the file asset index was refreshed.",
|
||||
f"If ingest succeeds, the final response must start with {INGEST_SUCCESS_MARKER} on its own line, followed by the summary.",
|
||||
f"If ingest fails, the final response must start with {INGEST_FAILURE_MARKER} on its own line, followed by the reason.",
|
||||
]
|
||||
)
|
||||
|
||||
@@ -752,6 +925,15 @@ class IngestManager:
|
||||
return duplicates
|
||||
|
||||
def _public_job(self, job: dict[str, Any]) -> dict[str, Any]:
|
||||
output = str(job.get("result_text") or extract_final_answer(job["log_path"]))
|
||||
if output.startswith((INGEST_SUCCESS_MARKER, INGEST_FAILURE_MARKER)):
|
||||
_ok, public_text, error = parse_marked_result(
|
||||
output,
|
||||
success_marker=INGEST_SUCCESS_MARKER,
|
||||
failure_marker=INGEST_FAILURE_MARKER,
|
||||
)
|
||||
output = public_text or error
|
||||
output = self._redact_paths(output)
|
||||
return {
|
||||
"job_id": job["job_id"],
|
||||
"state": job["state"],
|
||||
@@ -760,12 +942,40 @@ class IngestManager:
|
||||
"started_at": job.get("started_at"),
|
||||
"finished_at": job.get("finished_at"),
|
||||
"exit_code": job.get("exit_code"),
|
||||
"pid": job.get("pid"),
|
||||
"error": job.get("error", ""),
|
||||
"preflight": job.get("preflight"),
|
||||
"log_tail": self._read_tail(Path(job["log_path"])),
|
||||
"error": self._redact_paths(str(job.get("error", ""))),
|
||||
"preflight": self._public_preflight(job.get("preflight")),
|
||||
"log_tail": output,
|
||||
}
|
||||
|
||||
def _public_preflight(self, preflight: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if preflight is None:
|
||||
return None
|
||||
return {
|
||||
key: self._redact_public_value(value)
|
||||
for key, value in preflight.items()
|
||||
if key != "checked_paths"
|
||||
}
|
||||
|
||||
def _redact_public_value(self, value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return {key: self._redact_public_value(item) for key, item in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [self._redact_public_value(item) for item in value]
|
||||
if isinstance(value, str):
|
||||
return self._redact_paths(value)
|
||||
return value
|
||||
|
||||
def _redact_paths(self, value: str) -> str:
|
||||
text = value
|
||||
for path, label in (
|
||||
(self.runtime_root, "<runtime>"),
|
||||
(self.vault, "<vault>"),
|
||||
(self.project_root, "<project>"),
|
||||
(Path.home(), "<home>"),
|
||||
):
|
||||
text = text.replace(str(path), label)
|
||||
return text
|
||||
|
||||
def _tree_mtime(self, path: Path) -> float:
|
||||
if not path.exists():
|
||||
return time.time()
|
||||
|
||||
Reference in New Issue
Block a user