backend/ship/ (store, service, routes), /api/ship/* (authz + golden matrix), DEPS.deploy_hosts, the guard's ship-deploy catch (_SHIP / ship()) and the guest prompt's hardcoded ship-deploy line are gone: the managed ship plugin (ai-agent-plugins) decides who deploys where and its skill supplies the instructions. carryover.ship copies /data/deploy-hosts.json into the plugin's shared dir once (then ….migrated). GUARD_SHIP_TIMEOUT_S becomes GUARD_BROKER_TIMEOUT_S — the ai-agent CLI broker still needs it. Kept: sidecar/ship.py (the ship.run bridge's /ship/deploy), deploycmd.py, DeployWidget / DeployGizmo, the ship project level. openapi.json is not re-dumped here (the coordinator does it after Batch 1). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
165 lines
5.9 KiB
Python
165 lines
5.9 KiB
Python
"""The move from path ids to UUIDv7 ids (conversations/ids.py).
|
|
|
|
Runs in ``core.state.build_state`` before any JSON store is loaded, so nothing
|
|
holds the old spelling in memory while the files are rewritten:
|
|
|
|
1. every archived transcript gets its uid (``Registry.register_tree``);
|
|
2. every JSON store under the data dir has each legacy id **it is sure of**
|
|
— a ``<project dir>/<sid>.jsonl`` (a subagent's deeper) that is a known
|
|
transcript — swapped for the uid, a ``.bak-uids`` copy kept beside it. The
|
|
swap works on the raw text, so ids nested inside JSON-encoded strings (the
|
|
synced PWA stores in ui-state.json) are caught too; an absolute transcript
|
|
path (``…/projects/-home-…/x.jsonl``) is left alone: it is a file, not an id;
|
|
3. the short-title cache is re-keyed.
|
|
|
|
Idempotent, and re-run at every start (see :func:`migrate`): what was swapped
|
|
is no longer found. Old links keep working regardless — the resolver still
|
|
accepts a path id — so a store this misses only means that one reference
|
|
still emits the path until it is rewritten.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import fcntl
|
|
import json
|
|
import logging
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import shutil
|
|
import time
|
|
|
|
from conversations import ids
|
|
from core.config import META_PATH
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
VERSION = "1"
|
|
META_KEY = "conv_uids_migrated"
|
|
|
|
_SEG = r"[A-Za-z0-9._-]+"
|
|
# A bare id: a project dir (always "-<encoded abs path>"), then one or more
|
|
# segments, ending ".jsonl". Not preceded by a path character — that would be
|
|
# an absolute file path, which must keep pointing at the file.
|
|
_BARE = re.compile(rf"(?<![A-Za-z0-9._%/-])(-{_SEG}(?:/{_SEG})+?\.jsonl)(?![A-Za-z0-9._-])")
|
|
# …and the same id in a viewer URL, where it follows "/conversation/" (the
|
|
# diff route encodes the slashes: "/diff/conversation/-home…%2Fsid.jsonl").
|
|
_URL = re.compile(rf"(?<=/conversation/)(-{_SEG}(?:(?:/|%2F){_SEG})+?\.jsonl)(?![A-Za-z0-9._-])")
|
|
|
|
# Files that never hold a conversation id (or must not be touched).
|
|
_SKIP = {"auth.json", "security.json", "mcp.json", "form-secrets.json",
|
|
"openrouter-models.json"}
|
|
|
|
|
|
def rewrite_text(text: str, mapping: dict[str, str]) -> tuple[str, int]:
|
|
"""Swap every known legacy id in ``text`` for its uid."""
|
|
n = 0
|
|
|
|
def bare(m: re.Match) -> str:
|
|
nonlocal n
|
|
uid = mapping.get(m.group(1))
|
|
if uid is None:
|
|
return m.group(0)
|
|
n += 1
|
|
return uid
|
|
|
|
def url(m: re.Match) -> str:
|
|
nonlocal n
|
|
uid = mapping.get(m.group(1).replace("%2F", "/"))
|
|
if uid is None:
|
|
return m.group(0)
|
|
n += 1
|
|
return uid
|
|
|
|
text = _URL.sub(url, text)
|
|
text = _BARE.sub(bare, text)
|
|
return text, n
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def _meta_lock(data_dir: pathlib.Path):
|
|
"""The lock the conv-meta skill script takes before writing the sidecar."""
|
|
try:
|
|
fh = open(data_dir / ".conv-meta.lock", "a")
|
|
except OSError:
|
|
yield
|
|
return
|
|
with fh:
|
|
fcntl.flock(fh, fcntl.LOCK_EX)
|
|
yield
|
|
|
|
|
|
def rewrite_file(path: pathlib.Path, mapping: dict[str, str], stamp: str) -> int:
|
|
"""Rewrite one JSON store in place (a ``.bak-uids-<stamp>`` copy first)."""
|
|
try:
|
|
text = path.read_text(encoding="utf-8")
|
|
except (OSError, UnicodeDecodeError):
|
|
return 0
|
|
new, n = rewrite_text(text, mapping)
|
|
if not n:
|
|
return 0
|
|
try:
|
|
json.loads(new)
|
|
except ValueError:
|
|
log.warning("conv-uids: %s would not parse after the rewrite, left alone", path)
|
|
return 0
|
|
bak = path.with_name(f"{path.name}.bak-uids-{stamp}")
|
|
if not bak.exists():
|
|
shutil.copy2(path, bak)
|
|
tmp = path.with_name(f"{path.name}.uids.tmp")
|
|
tmp.write_text(new, encoding="utf-8")
|
|
with contextlib.suppress(OSError):
|
|
st = path.stat()
|
|
os.chown(tmp, st.st_uid, st.st_gid)
|
|
os.chmod(tmp, st.st_mode & 0o7777)
|
|
os.replace(tmp, path)
|
|
return n
|
|
|
|
|
|
def store_files(data_dir: pathlib.Path) -> list[pathlib.Path]:
|
|
"""Every JSON store under the data dir worth sweeping (top level).
|
|
|
|
Skips legacy ``*.json`` files whose sibling ``*.db`` SQLite store already
|
|
exists so already-migrated stores are not re-scanned on every startup."""
|
|
out = []
|
|
for p in sorted(data_dir.glob("*.json")):
|
|
if p.name in _SKIP or ".bak" in p.name or p.name.endswith(".tmp"):
|
|
continue
|
|
if p.with_suffix(".db").exists():
|
|
continue
|
|
out.append(p)
|
|
return out
|
|
|
|
|
|
def migrate(store, root: pathlib.Path | None, data_dir: pathlib.Path) -> dict:
|
|
"""Mint what has no uid yet and sweep the stores — at **every** start.
|
|
|
|
Not once: during a blue-green deploy the old container (old code, path
|
|
ids) keeps writing the same files for a while after the standby's start
|
|
ran this, so the canonical container's start sweeps again. Only what is
|
|
left is swapped (nothing, most starts — a read of ~12 MB of JSON), and
|
|
``meta.conv_uids_migrated`` just records when the first sweep happened."""
|
|
if root is None or not root.is_dir():
|
|
return {"skipped": "no archive"}
|
|
t0 = time.monotonic()
|
|
minted = ids.REGISTRY.register_tree(root)
|
|
mapping = ids.REGISTRY.snapshot()
|
|
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
swapped: dict[str, int] = {}
|
|
meta_name = pathlib.Path(META_PATH).name
|
|
for path in store_files(data_dir):
|
|
lock = _meta_lock(data_dir) if path.name == meta_name else contextlib.nullcontext()
|
|
with lock:
|
|
n = rewrite_file(path, mapping, stamp)
|
|
if n:
|
|
swapped[path.name] = n
|
|
titles = store.rekey_short_titles(mapping)
|
|
if store.get_meta(META_KEY) is None:
|
|
store.set_meta(META_KEY, f"{VERSION} {stamp}")
|
|
out = {"minted": minted, "files": swapped, "shortTitles": titles,
|
|
"seconds": round(time.monotonic() - t0, 2)}
|
|
if minted > 50 or swapped or titles:
|
|
log.warning("conv-uids: %s", out)
|
|
return out
|