@0perator/operator 0.1.351 → 0.1.353
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/dist/acp/agent.js +2 -2
- package/dist/acp/tool-map.js +5 -4
- package/dist/autonomy/delegate.js +54 -1
- package/dist/autonomy/headless.js +2 -0
- package/dist/autonomy/session-factory.js +1 -0
- package/dist/background/index.js +86 -10
- package/dist/background/notices.js +16 -4
- package/dist/cli.js +1073 -177
- package/dist/config/home.js +6 -0
- package/dist/config/memory-sections.js +92 -0
- package/dist/config/persona.js +144 -26
- package/dist/config/settings.js +15 -4
- package/dist/consolidation/scheduler.js +9 -2
- package/dist/consolidation/sleep.js +39 -278
- package/dist/engine/agent.js +444 -76
- package/dist/engine/anthropic-chat.js +13 -2
- package/dist/engine/aurora.js +66 -19
- package/dist/engine/batch-scheduler.js +27 -3
- package/dist/engine/compaction.js +12 -5
- package/dist/engine/continuation.js +14 -12
- package/dist/engine/contract.js +1 -1
- package/dist/engine/decision-points.js +7 -1
- package/dist/engine/front-door.js +59 -0
- package/dist/engine/grandmaster.js +13 -1
- package/dist/engine/loop-guard.js +694 -0
- package/dist/engine/owner-act.js +52 -0
- package/dist/engine/verify-gate.js +52 -0
- package/dist/flywheel/processor.js +3 -1
- package/dist/flywheel/srft.js +8 -4
- package/dist/hooks/index.js +12 -8
- package/dist/mcp/index.js +9 -4
- package/dist/permissions/index.js +32 -11
- package/dist/permissions/modes.js +42 -0
- package/dist/permissions/plan-review.js +100 -0
- package/dist/permissions/policy.js +16 -5
- package/dist/permissions/signature.js +8 -3
- package/dist/remote/safe-commands.js +1 -1
- package/dist/router/read-rates.js +152 -0
- package/dist/selfimprove/backfill.js +174 -0
- package/dist/selfimprove/index.js +146 -57
- package/dist/selfimprove/lessons.js +429 -0
- package/dist/selfimprove/sync.js +58 -0
- package/dist/session.js +362 -33
- package/dist/skills/finder.js +219 -0
- package/dist/toolchain/toolchain.py +528 -112
- package/dist/tools/deferred.js +28 -18
- package/dist/tools/executor.js +7 -3
- package/dist/tools/registry.js +68 -7
- package/dist/tools/result-cap.js +1 -1
- package/dist/ui/ActivitySpinner.js +21 -12
- package/dist/ui/App.js +107 -30
- package/dist/ui/ApprovalPrompt.js +5 -3
- package/dist/ui/ArtifactPicker.js +3 -3
- package/dist/ui/BgPanel.js +105 -5
- package/dist/ui/Composer.js +85 -9
- package/dist/ui/PlanPane.js +72 -8
- package/dist/ui/QuestionPrompt.js +6 -4
- package/dist/ui/SecretPrompt.js +8 -3
- package/dist/ui/SessionPicker.js +2 -2
- package/dist/ui/SkillFinder.js +153 -0
- package/dist/ui/StatusRule.js +5 -2
- package/dist/ui/SummaryCard.js +3 -1
- package/dist/ui/ThinkingSpinner.js +11 -2
- package/dist/ui/ToolBatch.js +11 -2
- package/dist/ui/ToolStep.js +36 -13
- package/dist/ui/Transcript.js +13 -2
- package/dist/ui/actNow.js +61 -0
- package/dist/ui/batchLine.js +165 -0
- package/dist/ui/conversations.js +154 -0
- package/dist/ui/decodeHealth.js +77 -0
- package/dist/ui/expand.js +17 -0
- package/dist/ui/fit.js +40 -0
- package/dist/ui/fitTail.js +14 -0
- package/dist/ui/fold.js +149 -0
- package/dist/ui/format.js +46 -2
- package/dist/ui/liveTools.js +163 -13
- package/dist/ui/modelPicker.js +78 -6
- package/dist/ui/nextStep.js +103 -0
- package/dist/ui/pending.js +57 -0
- package/dist/ui/phase.js +105 -0
- package/dist/ui/planExit.js +0 -5
- package/dist/ui/progressbar.js +4 -26
- package/dist/ui/readForecast.js +44 -0
- package/dist/ui/readProgress.js +119 -0
- package/dist/ui/reportLine.js +62 -0
- package/dist/ui/slashCommands.js +1 -1
- package/dist/ui/theme.js +1 -0
- package/dist/ui/turnFlow.js +72 -0
- package/dist/ui/turnLedger.js +121 -0
- package/dist/ui/turnScope.js +11 -0
- package/dist/util/slash.js +18 -0
- package/package.json +1 -1
|
@@ -8,8 +8,7 @@
|
|
|
8
8
|
toolchain verify [--deep] [--probe] [--quiet]
|
|
9
9
|
toolchain status
|
|
10
10
|
toolchain gc [--keep 3] [--apply]
|
|
11
|
-
toolchain migrate
|
|
12
|
-
toolchain migrate --replace-tools-dir [--undo] (JL1: ~/.operator/tools is an unused real directory)
|
|
11
|
+
toolchain migrate [--dry-run | --undo] [--reason TEXT] (~/.operator/tools onto consumers/aurora, KODE_HOME off ~/.hermes)
|
|
13
12
|
toolchain smoke --bin PATH [--gguf PATH] [--metal] [--via-launchd LABEL] [--ready-timeout SECONDS]
|
|
14
13
|
toolchain gate (--url URL --suite quick|aurora | --input FILE) (--baseline OUT | --compare FILE)
|
|
15
14
|
toolchain manifest check [FILE]
|
|
@@ -22,7 +21,8 @@ The root is --root, else $OPERATOR_TOOLCHAIN_HOME, else $OPERATOR_HOME/toolchain
|
|
|
22
21
|
generations/<N>/ immutable symlink farms with Hermes-schema facts.json and generation.json
|
|
23
22
|
consumers/<c> -> ../generations/<N>, the only mutable pointers (aurora, portal, arena)
|
|
24
23
|
history.jsonl, state.json, baselines/, .trash/
|
|
25
|
-
Exit codes: 0 ok, 1 error, 2 drift (verify), 78 unresolved or refused (EX_CONFIG, which supervise-gateway.sh parks on)
|
|
24
|
+
Exit codes: 0 ok, 1 error, 2 drift (verify), 78 unresolved or refused (EX_CONFIG, which supervise-gateway.sh parks on),
|
|
25
|
+
128+N after signal N (130 Ctrl-C, 143 SIGTERM, 129 SIGHUP) once a mutation's cleanup has run.
|
|
26
26
|
One stdlib file for /usr/bin/python3 -I (3.9.6 on both boxes): -I drops the script dir from sys.path.
|
|
27
27
|
"""
|
|
28
28
|
from __future__ import annotations
|
|
@@ -45,6 +45,7 @@ ROLES = ("payload", "checksums", "signature", "certificate")
|
|
|
45
45
|
CODESIGN_KINDS = ("adhoc", "developer-id", "unsigned-bundle", "none")
|
|
46
46
|
FLIP_ACTIONS = ("activate", "rollback", "migrate")
|
|
47
47
|
MIGRATE_PACKAGE = "llamacpp-metal"
|
|
48
|
+
TOOLS_KINDS = ("adopt-link", "replace-tools-dir", "from-hermes") # the migrate kinds that move ~/.operator/tools
|
|
48
49
|
TARGET_ARCH = {"darwin-arm64": "arm64", "darwin-x64": "x86_64"}
|
|
49
50
|
# Flags operator-runtime/gateway/server.cjs passes besides the preset keys (temp becomes --temperature).
|
|
50
51
|
GATEWAY_FLAGS = ("--host", "--port", "--model", "--alias", "--jinja", "--metrics", "--slots", "--no-webui")
|
|
@@ -70,6 +71,15 @@ class Mismatch(Refused):
|
|
|
70
71
|
"""Bytes that do not match their pin: never retried, never kept."""
|
|
71
72
|
|
|
72
73
|
|
|
74
|
+
class Terminated(BaseException):
|
|
75
|
+
"""SIGTERM or SIGHUP, raised where the run is (main installs the handler), so a mutation cleans up as it does for
|
|
76
|
+
Ctrl-C's KeyboardInterrupt. A BaseException, so no `except Exception` swallows it."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, signum: int):
|
|
79
|
+
super().__init__(signum)
|
|
80
|
+
self.signum = signum
|
|
81
|
+
|
|
82
|
+
|
|
73
83
|
def now() -> str:
|
|
74
84
|
return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
|
|
75
85
|
|
|
@@ -273,9 +283,14 @@ def seal(top) -> None:
|
|
|
273
283
|
|
|
274
284
|
|
|
275
285
|
def fault(point: str) -> None:
|
|
286
|
+
"""Test mode: TOOLCHAIN_FAULT_AT=<point> ends the run there with exit 137, as SIGKILL would. With TOOLCHAIN_FAULT_HOLD=1
|
|
287
|
+
the run says so on stderr and waits there instead, for the test to signal it."""
|
|
276
288
|
if test_mode() and os.environ.get("TOOLCHAIN_FAULT_AT") == point:
|
|
277
289
|
sys.stdout.flush()
|
|
278
290
|
sys.stderr.flush()
|
|
291
|
+
if os.environ.get("TOOLCHAIN_FAULT_HOLD") == "1":
|
|
292
|
+
say(f"toolchain: holding at {point}")
|
|
293
|
+
time.sleep(120)
|
|
279
294
|
os._exit(137)
|
|
280
295
|
|
|
281
296
|
|
|
@@ -290,14 +305,50 @@ def lock_is_current(fd: int, lock: pathlib.Path) -> bool:
|
|
|
290
305
|
|
|
291
306
|
|
|
292
307
|
def ever_activated(root: pathlib.Path) -> bool:
|
|
293
|
-
|
|
308
|
+
"""A consumer exists or history records a flip (a migrate's intent record is not one yet). A migrate --undo that removed
|
|
309
|
+
.lock (its migrate had created it) left the box unmanaged on purpose, so only the flips recorded after it count."""
|
|
310
|
+
hist = [r for r in read_history(root) if r.get("result") != "started"]
|
|
311
|
+
cut = next((i for i in range(len(hist) - 1, -1, -1) if hist[i].get("lock_removed")), None)
|
|
312
|
+
if cut is not None:
|
|
313
|
+
return any(r.get("action") in FLIP_ACTIONS for r in hist[cut + 1:])
|
|
314
|
+
return bool(consumer_names(root)) or any(r.get("action") in FLIP_ACTIONS for r in hist)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def orphan_lock(root: pathlib.Path) -> bool:
|
|
318
|
+
"""A .lock no command stands behind: no consumer is activated and history records no migrate, activate or rollback
|
|
319
|
+
(after the last --undo that removed .lock), so readers exit 78 with nothing to resolve. A first mutation killed before
|
|
320
|
+
its first record leaves one (SIGKILL, or a signal in the instant before mutation() can clean up), and so does an
|
|
321
|
+
install that activated nothing on a box that had no .lock. The caller rules out a live run: mutation() holds the flock
|
|
322
|
+
itself, and inspect asks lock_held."""
|
|
323
|
+
if not (root / ".lock").exists() or consumer_names(root):
|
|
324
|
+
return False
|
|
325
|
+
hist = read_history(root)
|
|
326
|
+
cut = next((i for i in range(len(hist) - 1, -1, -1) if hist[i].get("lock_removed")), -1)
|
|
327
|
+
return not any(r.get("action") in FLIP_ACTIONS for r in hist[cut + 1:])
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def lock_held(root: pathlib.Path) -> bool:
|
|
331
|
+
"""Whether a live run holds .lock's flock: a killed run's went with its process."""
|
|
332
|
+
try:
|
|
333
|
+
fd = os.open(root / ".lock", os.O_RDONLY)
|
|
334
|
+
except OSError:
|
|
335
|
+
return False
|
|
336
|
+
try:
|
|
337
|
+
fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
|
338
|
+
return False
|
|
339
|
+
except BlockingIOError:
|
|
340
|
+
return True
|
|
341
|
+
finally:
|
|
342
|
+
os.close(fd)
|
|
294
343
|
|
|
295
344
|
|
|
296
345
|
@contextlib.contextmanager
|
|
297
|
-
def mutation(root: pathlib.Path):
|
|
346
|
+
def mutation(root: pathlib.Path, orphan: bool = False):
|
|
298
347
|
"""The .lock file is also the managed marker: gateways and accessors that find it fail closed (78) instead of using
|
|
299
348
|
their legacy chain. So a mutation that fails right after creating it, before any consumer was ever activated, takes it
|
|
300
|
-
away again, under the flock; a waiter that locked the removed file sees that and locks the new one.
|
|
349
|
+
away again, under the flock; a waiter that locked the removed file sees that and locks the new one. Ctrl-C, SIGTERM and
|
|
350
|
+
SIGHUP run that cleanup too. Yields whether this mutation created .lock; with orphan (migrate), an orphan .lock counts
|
|
351
|
+
as created, so the record says the box had none and a failure takes it away."""
|
|
301
352
|
lock = root / ".lock"
|
|
302
353
|
guard_write(lock)
|
|
303
354
|
root.mkdir(parents=True, exist_ok=True)
|
|
@@ -319,9 +370,13 @@ def mutation(root: pathlib.Path):
|
|
|
319
370
|
break
|
|
320
371
|
os.close(fd)
|
|
321
372
|
try:
|
|
373
|
+
if orphan and not created and orphan_lock(root):
|
|
374
|
+
created = True
|
|
375
|
+
say(f"{lock} is an orphan (no consumer, and history records no migrate, activate or rollback): this migrate counts "
|
|
376
|
+
f"it as its own, so its --undo leaves the box unmanaged")
|
|
322
377
|
durable_write(root / ".lock.owner", canonical({"pid": os.getpid(), "argv": sys.argv[1:], "ts": now()}))
|
|
323
378
|
sweep(root)
|
|
324
|
-
yield
|
|
379
|
+
yield created
|
|
325
380
|
except BaseException:
|
|
326
381
|
if created and not ever_activated(root):
|
|
327
382
|
with contextlib.suppress(OSError):
|
|
@@ -1068,9 +1123,9 @@ def realize(ctx: Ctx, name: str, which: str, row: dict, witness: bool = False) -
|
|
|
1068
1123
|
if tree != row["tree"]:
|
|
1069
1124
|
raise Refused(f"{label}: realized tree {tree} does not match the manifest's {row['tree']}")
|
|
1070
1125
|
if row.get("expect_pm_digest") and digest != row["expect_pm_digest"]:
|
|
1071
|
-
|
|
1126
|
+
served = served_entry(ctx.root, row["entry"])
|
|
1072
1127
|
raise Refused(f"{label}: pm digest {digest} does not match the manifest's expect_pm_digest {row['expect_pm_digest']}"
|
|
1073
|
-
f"; paths that differ from
|
|
1128
|
+
+ (f"; paths that differ from the served {served}: {digest_diff(top, served)[:40]}" if served else ""))
|
|
1074
1129
|
if missing:
|
|
1075
1130
|
raise Refused(f"{label}: provides missing from the archive: {missing}")
|
|
1076
1131
|
probs = macho_problems(top, ctx.target, bool(row.get("relocatable"))) + codesign_problems(bins, row.get("codesign"))
|
|
@@ -1414,43 +1469,87 @@ def self_install(ctx: Ctx) -> None:
|
|
|
1414
1469
|
durable_write(dest, data, mode)
|
|
1415
1470
|
|
|
1416
1471
|
|
|
1417
|
-
def
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1472
|
+
def under_hermes(path) -> bool:
|
|
1473
|
+
p = os.fspath(path)
|
|
1474
|
+
return bool(p) and any(within(os.path.realpath(p), h) or within(os.path.abspath(p), h) for h in hermes_dirs())
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
def foreign_row(row) -> bool:
|
|
1478
|
+
return isinstance(row, dict) and under_hermes(str(row.get("path") or ""))
|
|
1479
|
+
|
|
1480
|
+
|
|
1481
|
+
class KodeFacts:
|
|
1482
|
+
"""KODE_HOME's tools/facts.json as read under .facts.lock: `facts` is {} for a missing file, and an unparsable one is
|
|
1483
|
+
kept as facts.json.corrupt, not reset. `text` is a parsed file's exact text (None when absent, unparsable or not
|
|
1484
|
+
UTF-8), which migrate records so --undo can write it back byte for byte."""
|
|
1485
|
+
|
|
1486
|
+
def __init__(self, path: pathlib.Path):
|
|
1487
|
+
self.path, self.existed, self.facts, self.text = path, path.exists(), {}, None
|
|
1488
|
+
if self.existed:
|
|
1429
1489
|
raw = path.read_bytes()
|
|
1430
1490
|
try:
|
|
1431
1491
|
facts = json.loads(raw)
|
|
1432
1492
|
if not isinstance(facts, dict):
|
|
1433
1493
|
raise ValueError("not an object")
|
|
1494
|
+
self.facts = facts
|
|
1434
1495
|
except ValueError:
|
|
1435
1496
|
durable_write(path.with_name("facts.json.corrupt"), raw)
|
|
1436
1497
|
say(f"warning: {path} was unparsable; kept it as facts.json.corrupt")
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1498
|
+
else:
|
|
1499
|
+
with contextlib.suppress(UnicodeDecodeError):
|
|
1500
|
+
self.text = raw.decode()
|
|
1501
|
+
|
|
1502
|
+
def tools(self) -> dict:
|
|
1503
|
+
return dict(self.facts["tools"]) if isinstance(self.facts.get("tools"), dict) else {}
|
|
1504
|
+
|
|
1505
|
+
def save(self, facts) -> None:
|
|
1506
|
+
"""Replaces the file atomically: a dict as JSON, a str (the text the file held) as it is. None removes it."""
|
|
1507
|
+
if facts is None:
|
|
1508
|
+
guard_write(self.path)
|
|
1509
|
+
with contextlib.suppress(FileNotFoundError):
|
|
1510
|
+
self.path.unlink()
|
|
1511
|
+
else:
|
|
1512
|
+
durable_write(self.path, (facts if isinstance(facts, str) else json.dumps(facts, indent=1) + "\n").encode())
|
|
1513
|
+
|
|
1514
|
+
|
|
1515
|
+
@contextlib.contextmanager
|
|
1516
|
+
def kode_facts():
|
|
1517
|
+
"""Holds tools/.facts.lock from the read to the replace. toolkit-verify.sh owns `toolkit` and takes the same lock, so
|
|
1518
|
+
neither writer drops the other's section."""
|
|
1519
|
+
tools_dir = kode_home() / "tools"
|
|
1520
|
+
path = tools_dir / "facts.json"
|
|
1521
|
+
guard_write(path)
|
|
1522
|
+
tools_dir.mkdir(parents=True, exist_ok=True)
|
|
1523
|
+
fd = os.open(tools_dir / ".facts.lock", os.O_CREAT | os.O_RDWR, 0o644)
|
|
1524
|
+
try:
|
|
1525
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
1526
|
+
yield KodeFacts(path)
|
|
1442
1527
|
finally:
|
|
1443
1528
|
os.close(fd)
|
|
1444
1529
|
|
|
1445
1530
|
|
|
1531
|
+
def write_kode_facts(rows: dict) -> None:
|
|
1532
|
+
"""tools.<pkg> rows in KODE_HOME's facts.json, plus generated and source. Every other row stays: only migrate drops the
|
|
1533
|
+
rows that resolve under ~/.hermes, and it records them; verify notes any that are left."""
|
|
1534
|
+
with kode_facts() as kf:
|
|
1535
|
+
kf.save({**kf.facts, "tools": {**kf.tools(), **rows}, "generated": now(), "source": "operator-toolchain"})
|
|
1536
|
+
|
|
1537
|
+
|
|
1538
|
+
def kode_rows(root: pathlib.Path, n) -> dict:
|
|
1539
|
+
"""The tools.<pkg> rows for generation n: each names ~/.operator/tools/<entry>, which consumers/aurora serves."""
|
|
1540
|
+
compat, g = operator_home() / "tools", (load_generation(root, n) if n is not None else None) or {}
|
|
1541
|
+
return {name: {"path": str(compat / p["entry"]), "version": p["version"]} for name, p in sorted(g.get("packages", {}).items())}
|
|
1542
|
+
|
|
1543
|
+
|
|
1446
1544
|
def sync_kode_facts(root: pathlib.Path) -> None:
|
|
1447
|
-
"""Rows describe ~/.operator/tools/<entry>, so
|
|
1545
|
+
"""Rows describe ~/.operator/tools/<entry>, so install, activate and rollback write them only once that path is ours
|
|
1546
|
+
(after migrate)."""
|
|
1448
1547
|
compat = operator_home() / "tools"
|
|
1449
1548
|
if not compat.is_symlink() or os.path.realpath(compat) != os.path.realpath(root / "consumers" / "aurora"):
|
|
1450
1549
|
return
|
|
1451
|
-
|
|
1452
|
-
if
|
|
1453
|
-
write_kode_facts(
|
|
1550
|
+
rows = kode_rows(root, current_generation(root, "aurora"))
|
|
1551
|
+
if rows:
|
|
1552
|
+
write_kode_facts(rows)
|
|
1454
1553
|
|
|
1455
1554
|
|
|
1456
1555
|
# ── live servers ────────────────────────────────────────────────────────────
|
|
@@ -1684,17 +1783,23 @@ def inspect(ctx: Ctx, deep: bool = False, probe: bool = False) -> dict:
|
|
|
1684
1783
|
problems.append(f"{c}: store/{p['store_entry']} pm digest drifted from {p['digest']}")
|
|
1685
1784
|
if row is not None:
|
|
1686
1785
|
problems += [f"{c}: {x}" for x in codesign_problems([entry / rel for rel in p["provides"].values()], row.get("codesign"))]
|
|
1687
|
-
compat = operator_home() / "tools"
|
|
1688
|
-
if
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1786
|
+
compat, legacy, runs = operator_home() / "tools", legacy_tools(root), migrate_runs(root)
|
|
1787
|
+
if runs and runs[-1].get("result") == "started":
|
|
1788
|
+
problems.append(f"the migrate ({runs[-1].get('kind')}) started at {runs[-1].get('ts')} did not finish: toolchain migrate --undo")
|
|
1789
|
+
if orphan_lock(root) and not lock_held(root):
|
|
1790
|
+
problems.append(f"{root / '.lock'} is an orphan (no consumer, and history records no migrate, activate or rollback): the "
|
|
1791
|
+
f"gateway and `which` exit 78 with nothing to resolve; toolchain migrate --undo removes it")
|
|
1792
|
+
if compat.is_symlink() and os.path.realpath(compat) == os.path.realpath(root / "consumers" / "aurora"):
|
|
1793
|
+
notes.append(f"{compat} -> consumers/aurora")
|
|
1794
|
+
elif legacy and any(r.get("kind") in TOOLS_KINDS and r.get("result") == "ok" for r in runs):
|
|
1795
|
+
problems.append(f"{compat} resolves outside Operator's store ({legacy}) again, after migrate moved it onto consumers/aurora")
|
|
1796
|
+
elif legacy:
|
|
1797
|
+
notes.append(f"{compat} resolves outside Operator's store ({legacy}): not migrated")
|
|
1798
|
+
for name, target in hermes_links().items():
|
|
1799
|
+
notes.append(f"{kode_home() / 'tools' / name} still resolves into Hermes: -> {target}")
|
|
1694
1800
|
kfacts = read_json(kode_home() / "tools" / "facts.json") or {}
|
|
1695
1801
|
for k, v in sorted((kfacts.get("tools") or {}).items() if isinstance(kfacts, dict) else []):
|
|
1696
|
-
if
|
|
1697
|
-
for h in hermes_dirs()):
|
|
1802
|
+
if foreign_row(v):
|
|
1698
1803
|
notes.append(f"{kode_home() / 'tools/facts.json'} tools.{k} still points into Hermes: {v.get('path')}")
|
|
1699
1804
|
try:
|
|
1700
1805
|
live = classify(root, ctx.manifest, live_servers())
|
|
@@ -1911,41 +2016,185 @@ def link_into(link: pathlib.Path, target: str) -> None:
|
|
|
1911
2016
|
fsync_path(link.parent)
|
|
1912
2017
|
|
|
1913
2018
|
|
|
1914
|
-
def
|
|
2019
|
+
def legacy_tools(root: pathlib.Path) -> str | None:
|
|
2020
|
+
"""Where $OPERATOR_HOME/tools resolves while it is not ours: a link out of the toolchain root, or a real directory."""
|
|
2021
|
+
compat = operator_home() / "tools"
|
|
2022
|
+
real = os.path.realpath(compat)
|
|
2023
|
+
return real if os.path.isdir(compat) and not within(real, os.path.realpath(root)) else None
|
|
2024
|
+
|
|
2025
|
+
|
|
2026
|
+
def served_entry(root: pathlib.Path, entry: str) -> str | None:
|
|
2027
|
+
"""<legacy tools>/<entry>: the entry the legacy layout serves, if it has one."""
|
|
2028
|
+
legacy = legacy_tools(root)
|
|
2029
|
+
path = os.path.join(legacy, entry) if legacy else None
|
|
2030
|
+
return path if path and os.path.isdir(path) else None
|
|
2031
|
+
|
|
2032
|
+
|
|
2033
|
+
def last_migrate(root: pathlib.Path) -> dict | None:
|
|
2034
|
+
return next((r for r in reversed(read_history(root)) if r.get("action") == "migrate"), None)
|
|
2035
|
+
|
|
2036
|
+
|
|
2037
|
+
def migrate_runs(root: pathlib.Path) -> list:
|
|
2038
|
+
"""The migrates no --undo has taken back, oldest first, each as its newest record: "started" (the intent, written before
|
|
2039
|
+
the first flip or move) until the run's closing "ok". 0.1.350's from-hermes record is an "ok" alone. Each -undo record
|
|
2040
|
+
takes back the newest run, so the migrate under a later KODE-only separation stays undoable."""
|
|
2041
|
+
runs = []
|
|
2042
|
+
for r in read_history(root):
|
|
2043
|
+
if r.get("action") != "migrate":
|
|
2044
|
+
continue
|
|
2045
|
+
if str(r.get("kind")).endswith("-undo"):
|
|
2046
|
+
if runs:
|
|
2047
|
+
runs.pop()
|
|
2048
|
+
elif runs and r.get("run") is not None and runs[-1].get("run") == r.get("run"):
|
|
2049
|
+
runs[-1] = r
|
|
2050
|
+
else:
|
|
2051
|
+
runs.append(r)
|
|
2052
|
+
return runs
|
|
2053
|
+
|
|
2054
|
+
|
|
2055
|
+
def tools_layout(root: pathlib.Path) -> str:
|
|
2056
|
+
"""'migrated' (the link to an activated consumers/aurora), 'adopt-link' (a link that resolves outside the toolchain
|
|
2057
|
+
root) or 'replace-tools-dir' (a real directory). Anything else is refused."""
|
|
2058
|
+
compat = operator_home() / "tools"
|
|
2059
|
+
if compat.is_symlink() and os.path.realpath(compat) == os.path.realpath(root / "consumers" / "aurora") \
|
|
2060
|
+
and current_generation(root, "aurora") is not None:
|
|
2061
|
+
return "migrated"
|
|
2062
|
+
if legacy_tools(root):
|
|
2063
|
+
return "adopt-link" if compat.is_symlink() else "replace-tools-dir"
|
|
2064
|
+
if not os.path.lexists(compat):
|
|
2065
|
+
raise Refused(f"{compat} does not exist, so there is nothing to migrate: toolchain install --activate aurora,portal,arena")
|
|
2066
|
+
raise Refused(f"{compat} ({'-> ' + os.readlink(compat) if compat.is_symlink() else 'not a link'}) is neither a directory outside "
|
|
2067
|
+
f"{root} nor the link to an activated consumers/aurora")
|
|
2068
|
+
|
|
2069
|
+
|
|
2070
|
+
def free_bytes(path) -> int:
|
|
2071
|
+
"""In test mode OPERATOR_TOOLCHAIN_FREE_BYTES stands in for the disk, so the low-space refusal can be tested."""
|
|
2072
|
+
if test_mode() and os.environ.get("OPERATOR_TOOLCHAIN_FREE_BYTES"):
|
|
2073
|
+
return int(os.environ["OPERATOR_TOOLCHAIN_FREE_BYTES"])
|
|
2074
|
+
return shutil.disk_usage(path).free
|
|
2075
|
+
|
|
2076
|
+
|
|
2077
|
+
def hermes_links() -> dict:
|
|
2078
|
+
"""KODE_HOME's tools/ links that resolve under ~/.hermes. Nothing in the repo reads them (checked 11/03), so migrate moves
|
|
2079
|
+
them to tools.pre-separation-<date>/ rather than re-pointing them, and never deletes one."""
|
|
2080
|
+
tools = kode_home() / "tools"
|
|
2081
|
+
with contextlib.suppress(OSError):
|
|
2082
|
+
return {p.name: os.readlink(p) for p in sorted(tools.iterdir()) if p.is_symlink() and under_hermes(p)}
|
|
2083
|
+
return {}
|
|
2084
|
+
|
|
2085
|
+
|
|
2086
|
+
def kode_aside() -> str:
|
|
2087
|
+
return str(kode_home() / f"tools.pre-separation-{utc_today().strftime('%Y%m%d')}")
|
|
2088
|
+
|
|
2089
|
+
|
|
2090
|
+
def kode_separation() -> dict:
|
|
2091
|
+
"""What migrate would separate in KODE_HOME, read without the facts lock: the plan and the dry run show it."""
|
|
2092
|
+
facts = read_json(kode_home() / "tools" / "facts.json") or {}
|
|
2093
|
+
rows = facts.get("tools") if isinstance(facts, dict) and isinstance(facts.get("tools"), dict) else {}
|
|
2094
|
+
return {"aside": kode_aside(), "links": hermes_links(), "rows": {k: v for k, v in sorted(rows.items()) if foreign_row(v)}}
|
|
2095
|
+
|
|
2096
|
+
|
|
2097
|
+
def refuse_aside_clash(aside: str, links: dict) -> None:
|
|
2098
|
+
clash = [n for n in links if os.path.lexists(pathlib.Path(aside) / n)]
|
|
2099
|
+
if clash:
|
|
2100
|
+
raise Refused(f"{aside} already holds {', '.join(clash)}")
|
|
2101
|
+
|
|
2102
|
+
|
|
2103
|
+
def move_links(names, src: pathlib.Path, dst: pathlib.Path) -> list:
|
|
2104
|
+
"""rename(2) of each named link from src into dst: the link moves, never what it points at, and nothing is replaced."""
|
|
2105
|
+
moved = []
|
|
2106
|
+
for name in names:
|
|
2107
|
+
a, b = src / name, dst / name
|
|
2108
|
+
if os.sep in name or not a.is_symlink() or os.path.lexists(b):
|
|
2109
|
+
continue
|
|
2110
|
+
guard_write(a)
|
|
2111
|
+
guard_write(b)
|
|
2112
|
+
dst.mkdir(exist_ok=True)
|
|
2113
|
+
os.rename(a, b)
|
|
2114
|
+
moved.append(name)
|
|
2115
|
+
for d in (src, dst) if moved else ():
|
|
2116
|
+
fsync_path(d)
|
|
2117
|
+
return moved
|
|
2118
|
+
|
|
2119
|
+
|
|
2120
|
+
def begin(ctx: Ctx, kind: str, created: bool, kf: KodeFacts, rows: dict, **fields) -> dict:
|
|
2121
|
+
"""The intent record, written before the first flip or move: everything --undo needs to put the box back. The caller
|
|
2122
|
+
holds .facts.lock from here until separate() has written, so kode_rows is exactly what the drop removes."""
|
|
2123
|
+
aside, links = kode_aside(), hermes_links()
|
|
2124
|
+
refuse_aside_clash(aside, links)
|
|
2125
|
+
tools = kf.tools()
|
|
2126
|
+
dropped = {k: v for k, v in sorted(tools.items()) if foreign_row(v)}
|
|
2127
|
+
kept = {k: v for k, v in tools.items() if k not in dropped}
|
|
2128
|
+
rec = {"kind": kind, "run": f"{time.strftime('%Y%m%dT%H%M%S')}-{os.getpid()}", "manifest_serial": ctx.serial,
|
|
2129
|
+
"reason": ctx.args.reason, "lock_existed": not created, **fields, "kode_aside": aside, "kode_links": links,
|
|
2130
|
+
"kode_rows": dropped, "kode_added": sorted(k for k in rows if k not in kept),
|
|
2131
|
+
"kode_replaced": {k: kept[k] for k in sorted(rows) if k in kept and kept[k] != rows[k]},
|
|
2132
|
+
"kode_facts_before": {k: kf.facts[k] for k in ("generated", "source") if k in kf.facts} if kf.existed else None,
|
|
2133
|
+
"kode_facts_text": kf.text}
|
|
2134
|
+
history(ctx.root, "migrate", result="started", **rec)
|
|
2135
|
+
fault("post-intent")
|
|
2136
|
+
return rec
|
|
2137
|
+
|
|
2138
|
+
|
|
2139
|
+
def separate(rec: dict, kf: KodeFacts, rows: dict) -> dict:
|
|
2140
|
+
"""The moves: KODE_HOME's recorded links go aside (renamed, never deleted), and facts.json loses exactly the recorded
|
|
2141
|
+
rows and gains `rows`."""
|
|
2142
|
+
moved = move_links(sorted(rec["kode_links"]), kode_home() / "tools", pathlib.Path(rec["kode_aside"]))
|
|
2143
|
+
tools = {k: v for k, v in kf.tools().items() if k not in rec["kode_rows"]}
|
|
2144
|
+
kf.save({**kf.facts, "tools": {**tools, **rows}, "generated": now(), "source": "operator-toolchain"})
|
|
2145
|
+
return {"aside": rec["kode_aside"] if moved else None, "moved_aside": moved, "dropped_rows": sorted(rec["kode_rows"])}
|
|
2146
|
+
|
|
2147
|
+
|
|
2148
|
+
def migrate(ctx: Ctx, args) -> dict:
|
|
2149
|
+
compat, runs = operator_home() / "tools", migrate_runs(ctx.root)
|
|
2150
|
+
if runs and runs[-1].get("result") == "started":
|
|
2151
|
+
# Refused, not finished: the interrupted run proved the served build, counted the open files and checked the
|
|
2152
|
+
# consumers in a process that died, and finishing would flip the live Aurora path on that evidence. A refusal writes
|
|
2153
|
+
# nothing; --undo takes back exactly what the intent record lists, and the next migrate proves everything again.
|
|
2154
|
+
raise Refused(f"the migrate ({runs[-1].get('kind')}) started at {runs[-1].get('ts')} did not finish: "
|
|
2155
|
+
f"toolchain migrate --undo takes back what it began, then run migrate again")
|
|
2156
|
+
kind = tools_layout(ctx.root)
|
|
2157
|
+
kode = kode_separation()
|
|
2158
|
+
if kind == "migrated":
|
|
2159
|
+
if not kode["links"] and not kode["rows"]:
|
|
2160
|
+
return {"kind": kind, "already_migrated": True, "tools": f"{compat} -> {os.readlink(compat)}"}
|
|
2161
|
+
kind = "kode-only"
|
|
2162
|
+
refuse_aside_clash(kode["aside"], kode["links"])
|
|
2163
|
+
link = f"{os.readlink(compat)} (unchanged)" if kind == "kode-only" else os.path.relpath(ctx.root / "consumers" / "aurora", compat.parent)
|
|
2164
|
+
plan = {"kind": kind, "link": f"{compat} -> {link}",
|
|
2165
|
+
"kode_home": {"aside": kode["aside"], "move_aside": kode["links"], "drop_rows": sorted(kode["rows"])}}
|
|
2166
|
+
return {"adopt-link": migrate_link, "replace-tools-dir": migrate_dir, "kode-only": migrate_kode}[kind](ctx, args, plan)
|
|
2167
|
+
|
|
2168
|
+
|
|
2169
|
+
def migrate_link(ctx: Ctx, args, plan: dict) -> dict:
|
|
2170
|
+
"""The link's target serves the previous row's build (b10964 on JL2). It is realized from upstream into the store and must
|
|
2171
|
+
equal the served <target>/<entry> by pm digest, the one the store records; then the link moves in one rename."""
|
|
1915
2172
|
root, compat = ctx.root, operator_home() / "tools"
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
if
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
was = os.readlink(compat)
|
|
1926
|
-
link_into(compat, last["from"])
|
|
1927
|
-
history(root, "migrate", kind="from-hermes-undo", **{"from": was, "to": last["from"]}, reason=args.reason)
|
|
1928
|
-
return {"undone": True, "tools": str(compat), "now": last["from"]}
|
|
1929
|
-
real_hermes = os.path.realpath(hermes_tools)
|
|
1930
|
-
if not compat.is_symlink() or os.path.realpath(compat) != real_hermes:
|
|
1931
|
-
raise Refused(f"{compat} is not a link to {hermes_tools} (it is {os.readlink(compat) if compat.is_symlink() else 'not a link'})")
|
|
1932
|
-
pre = {"hermes_facts_sha256": sha256_file(hfacts) if hfacts.is_file() else None, "aurora": aurora_identity(),
|
|
1933
|
-
"free_bytes": shutil.disk_usage(operator_home()).free, "tools": os.readlink(compat)}
|
|
2173
|
+
name, which, row = row_for(ctx.manifest, f"{MIGRATE_PACKAGE}@previous")
|
|
2174
|
+
served = os.path.join(os.path.realpath(compat), row["entry"])
|
|
2175
|
+
runs = next((os.path.realpath(p) for p in (compat / "llama-server", compat / "llamacpp" / "llama-server") if p.exists()), None)
|
|
2176
|
+
if not os.path.isdir(served):
|
|
2177
|
+
raise Refused(f"{compat} -> {os.readlink(compat)} has no {row['entry']} to prove {name}@previous against")
|
|
2178
|
+
if not runs or not within(runs, served):
|
|
2179
|
+
raise Refused(f"{compat}/llama-server is {runs or 'missing'}, not a file of the served {served}")
|
|
2180
|
+
pre = {"aurora": aurora_identity(), "free_bytes": free_bytes(operator_home()), "tools": os.readlink(compat),
|
|
2181
|
+
"served": served, "served_digest": pm_digest(served)}
|
|
1934
2182
|
if pre["free_bytes"] < 2 << 30:
|
|
1935
2183
|
raise Refused(f"less than 2 GB free under {operator_home()}")
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
2184
|
+
expect = row.get("expect_pm_digest")
|
|
2185
|
+
# a served entry that misses a set expect_pm_digest dooms the real run: realize refuses a pristine build that misses the
|
|
2186
|
+
# pin, and one that meets it differs from the served entry
|
|
2187
|
+
plan = {**plan, "preflight": pre, "realize": f"{name}@previous", "expect_pm_digest": expect,
|
|
2188
|
+
"served_matches_manifest": pre["served_digest"] == expect if expect else None, "consumers": ["aurora", "arena"]}
|
|
1939
2189
|
if args.dry_run:
|
|
1940
2190
|
return {"dry_run": True, **plan}
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
name, which, row = row_for(ctx.manifest, f"{MIGRATE_PACKAGE}@previous")
|
|
1944
|
-
with mutation(root):
|
|
2191
|
+
target = os.path.relpath(root / "consumers" / "aurora", compat.parent)
|
|
2192
|
+
with mutation(root, orphan=True) as created:
|
|
1945
2193
|
meta = realize(ctx, name, which, row)
|
|
1946
|
-
if meta["digest"] !=
|
|
1947
|
-
diff = digest_diff(root / "store" / meta["store_entry"],
|
|
1948
|
-
raise Refused(f"{name}@previous pm digest {meta['digest']} !=
|
|
2194
|
+
if meta["digest"] != pre["served_digest"]:
|
|
2195
|
+
diff = digest_diff(root / "store" / meta["store_entry"], served)
|
|
2196
|
+
raise Refused(f"{name}@previous pm digest {meta['digest']} != {pre['served_digest']}, the served {served}'s; "
|
|
2197
|
+
f"differing paths: {diff[:40]}")
|
|
1949
2198
|
packages = {name: gen_package(meta, row)}
|
|
1950
2199
|
n = find_generation(root, packages)
|
|
1951
2200
|
if n is None:
|
|
@@ -1957,53 +2206,43 @@ def migrate_from_hermes(ctx: Ctx, args) -> dict:
|
|
|
1957
2206
|
if prev not in (None, n):
|
|
1958
2207
|
raise Refused(f"consumers/{c} is on generation {prev}, not the migrated {n}, so the new link would not run what Aurora runs: "
|
|
1959
2208
|
f"toolchain activate {n} --consumer {c} --reason TEXT first")
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
2209
|
+
with kode_facts() as kf:
|
|
2210
|
+
rows = kode_rows(root, n)
|
|
2211
|
+
rec = begin(ctx, "adopt-link", created, kf, rows, **{"from": pre["tools"], "to": target}, served=served,
|
|
2212
|
+
served_digest=pre["served_digest"])
|
|
2213
|
+
self_install(ctx)
|
|
2214
|
+
fault("pre-consumer-flip")
|
|
2215
|
+
for c, prev in moves:
|
|
2216
|
+
flip(root, c, n)
|
|
2217
|
+
history(root, "activate", consumer=c, **{"from": prev, "to": n}, manifest_serial=ctx.serial, reason="migrate")
|
|
2218
|
+
done = separate(rec, kf, rows)
|
|
2219
|
+
fault("pre-tools-flip")
|
|
1965
2220
|
link_into(compat, target)
|
|
1966
|
-
history(root, "migrate",
|
|
1967
|
-
|
|
1968
|
-
sync_kode_facts(root)
|
|
1969
|
-
return {**plan, "generation": n, "postflight": postflight(ctx, pre, hfacts, row)}
|
|
2221
|
+
history(root, "migrate", result="ok", **rec)
|
|
2222
|
+
return {**plan, "generation": n, "kode_home": done, "postflight": postflight(ctx, pre, row)}
|
|
1970
2223
|
|
|
1971
2224
|
|
|
1972
|
-
def postflight(ctx: Ctx, pre: dict,
|
|
2225
|
+
def postflight(ctx: Ctx, pre: dict, row: dict) -> dict:
|
|
2226
|
+
"""old_target_unchanged: the served entry hashes as it did before, so migrate wrote nothing into the old tree."""
|
|
1973
2227
|
compat = operator_home() / "tools"
|
|
1974
2228
|
out = {"aurora_unchanged": aurora_alive(pre["aurora"]),
|
|
1975
2229
|
"tools_link": os.readlink(compat) if compat.is_symlink() else None,
|
|
1976
2230
|
"llama_server": os.path.realpath(compat / "llama-server"),
|
|
1977
2231
|
"in_store": within(os.path.realpath(compat / "llama-server"), os.path.realpath(ctx.root / "store")),
|
|
1978
|
-
"
|
|
2232
|
+
"old_target_unchanged": os.path.isdir(pre["served"]) and pm_digest(pre["served"]) == pre["served_digest"]}
|
|
1979
2233
|
try:
|
|
1980
2234
|
out["probe"] = first_line(run_probe(compat, {**row, "provides": {row["probe"]["bin"]: "llama-server"}})) if row.get("probe") else ""
|
|
1981
2235
|
out["probe_ok"] = True
|
|
1982
2236
|
except Refused as e:
|
|
1983
2237
|
out["probe"], out["probe_ok"] = str(e), False
|
|
1984
2238
|
out["verify_deep"] = inspect(ctx, deep=True)["result"]
|
|
1985
|
-
out["ok"] = all([out["aurora_unchanged"], out["in_store"], out["
|
|
2239
|
+
out["ok"] = all([out["aurora_unchanged"], out["in_store"], out["old_target_unchanged"], out["probe_ok"], out["verify_deep"] == "ok"])
|
|
1986
2240
|
return out
|
|
1987
2241
|
|
|
1988
2242
|
|
|
1989
|
-
def
|
|
2243
|
+
def migrate_dir(ctx: Ctx, args, plan: dict) -> dict:
|
|
1990
2244
|
root, compat = ctx.root, operator_home() / "tools"
|
|
1991
2245
|
aside = compat.with_name(f"tools.pre-toolchain-{utc_today().strftime('%Y%m%d')}")
|
|
1992
|
-
if args.undo:
|
|
1993
|
-
last = next((r for r in reversed(read_history(root)) if r.get("action") == "migrate" and r.get("kind") == "replace-tools-dir"), None)
|
|
1994
|
-
if not last or not os.path.isdir(last["from"]):
|
|
1995
|
-
raise Refused("history records no migrate --replace-tools-dir whose directory is still there to restore")
|
|
1996
|
-
with mutation(root):
|
|
1997
|
-
if not compat.is_symlink():
|
|
1998
|
-
raise Refused(f"{compat} is not a link; nothing to undo")
|
|
1999
|
-
guard_write(compat)
|
|
2000
|
-
compat.unlink()
|
|
2001
|
-
os.rename(last["from"], compat)
|
|
2002
|
-
fsync_path(compat.parent)
|
|
2003
|
-
history(root, "migrate", kind="replace-tools-dir-undo", **{"from": last["to"], "to": str(compat)}, reason=args.reason)
|
|
2004
|
-
return {"undone": True, "restored": str(compat)}
|
|
2005
|
-
if compat.is_symlink() or not compat.is_dir():
|
|
2006
|
-
raise Refused(f"{compat} is not a real directory")
|
|
2007
2246
|
if current_generation(root, "aurora") is None:
|
|
2008
2247
|
raise Refused("consumers/aurora is not activated: run toolchain install --activate aurora,portal,arena first (the link must never dangle)")
|
|
2009
2248
|
readers = run(["/usr/sbin/lsof", "-nP", "-Fp", "+D", os.path.realpath(compat)], timeout=60).stdout.split()
|
|
@@ -2011,27 +2250,189 @@ def migrate_replace_dir(ctx: Ctx, args) -> dict:
|
|
|
2011
2250
|
raise Refused(f"processes have files open under {compat}: {' '.join(readers)}")
|
|
2012
2251
|
if os.path.lexists(aside):
|
|
2013
2252
|
raise Refused(f"{aside} already exists")
|
|
2253
|
+
plan = {**plan, "move_aside": str(aside)}
|
|
2254
|
+
if args.dry_run:
|
|
2255
|
+
return {"dry_run": True, **plan}
|
|
2014
2256
|
target = os.path.relpath(root / "consumers" / "aurora", compat.parent)
|
|
2015
|
-
with mutation(root):
|
|
2257
|
+
with mutation(root) as created:
|
|
2258
|
+
with kode_facts() as kf:
|
|
2259
|
+
rows = kode_rows(root, current_generation(root, "aurora"))
|
|
2260
|
+
rec = begin(ctx, "replace-tools-dir", created, kf, rows, **{"from": str(aside), "to": target})
|
|
2261
|
+
done = separate(rec, kf, rows)
|
|
2262
|
+
fault("pre-tools-flip")
|
|
2016
2263
|
guard_write(compat)
|
|
2017
2264
|
guard_write(aside)
|
|
2018
2265
|
os.rename(compat, aside)
|
|
2019
2266
|
os.symlink(target, compat)
|
|
2020
2267
|
fsync_path(compat.parent)
|
|
2021
|
-
history(root, "migrate",
|
|
2022
|
-
|
|
2023
|
-
|
|
2268
|
+
history(root, "migrate", result="ok", **rec)
|
|
2269
|
+
return {**plan, "moved_aside": str(aside), "tools": f"{compat} -> {target}", "kode_home": done}
|
|
2270
|
+
|
|
2271
|
+
|
|
2272
|
+
def migrate_kode(ctx: Ctx, args, plan: dict) -> dict:
|
|
2273
|
+
"""~/.operator/tools is already on consumers/aurora (0.1.350's migrate left KODE_HOME as it was), but KODE_HOME still links
|
|
2274
|
+
or points into ~/.hermes: only that separation, recorded and undoable like the other kinds."""
|
|
2275
|
+
root, compat = ctx.root, operator_home() / "tools"
|
|
2276
|
+
if args.dry_run:
|
|
2277
|
+
return {"dry_run": True, **plan}
|
|
2278
|
+
with mutation(root) as created:
|
|
2279
|
+
with kode_facts() as kf:
|
|
2280
|
+
rows = kode_rows(root, current_generation(root, "aurora"))
|
|
2281
|
+
rec = begin(ctx, "kode-only", created, kf, rows, **{"from": os.readlink(compat), "to": os.readlink(compat)})
|
|
2282
|
+
done = separate(rec, kf, rows)
|
|
2283
|
+
history(root, "migrate", result="ok", **rec)
|
|
2284
|
+
return {**plan, "kode_home": done}
|
|
2285
|
+
|
|
2286
|
+
|
|
2287
|
+
def undo_state(root: pathlib.Path, rec: dict) -> str:
|
|
2288
|
+
"""Where ~/.operator/tools stands against a migrate record: 'migrated' (the migrate's link, or for replace-tools-dir no
|
|
2289
|
+
path at all: a run killed between its two renames), 'restored' (as it was before the migrate, so only KODE_HOME and the
|
|
2290
|
+
record are left) or 'unchanged' (kode-only never moves it). Anything else is refused, before any write."""
|
|
2291
|
+
compat, kind, frm = operator_home() / "tools", rec.get("kind"), str(rec.get("from") or "")
|
|
2292
|
+
if kind == "kode-only":
|
|
2293
|
+
return "unchanged"
|
|
2294
|
+
ours = compat.is_symlink() and os.path.realpath(compat) == os.path.realpath(root / "consumers" / "aurora")
|
|
2295
|
+
if kind == "replace-tools-dir":
|
|
2296
|
+
if ours or not os.path.lexists(compat):
|
|
2297
|
+
if not os.path.isdir(frm):
|
|
2298
|
+
raise Refused(f"{frm}, where migrate moved {compat}, is gone: nothing to restore")
|
|
2299
|
+
return "migrated"
|
|
2300
|
+
if compat.is_dir() and not compat.is_symlink() and not os.path.lexists(frm):
|
|
2301
|
+
return "restored"
|
|
2302
|
+
elif ours:
|
|
2303
|
+
return "migrated"
|
|
2304
|
+
elif compat.is_symlink() and (os.readlink(compat) == frm or os.path.realpath(compat) == os.path.realpath(compat.parent / frm)):
|
|
2305
|
+
return "restored"
|
|
2306
|
+
raise Refused(f"{compat} is neither the link to consumers/aurora nor what migrate moved away ({frm}): nothing to undo")
|
|
2307
|
+
|
|
2308
|
+
|
|
2309
|
+
def restore_kode_facts(rec: dict) -> dict:
|
|
2310
|
+
"""facts.json as it was before the migrate: the keys it added go, the rows it replaced or dropped come back (a dropped row
|
|
2311
|
+
only where no row has taken its key since), and generated and source return. When that is the file the migrate found,
|
|
2312
|
+
the recorded text goes back byte for byte; when another writer (toolkit-verify.sh) has changed it since, the result
|
|
2313
|
+
keeps that change, as JSON. Content that is already right is not rewritten. 0.1.350's from-hermes record carries none
|
|
2314
|
+
of this, so those facts stay as they are."""
|
|
2315
|
+
rows, added, replaced = rec.get("kode_rows") or {}, rec.get("kode_added") or [], rec.get("kode_replaced") or {}
|
|
2316
|
+
if not (rows or added or replaced or "kode_facts_before" in rec):
|
|
2317
|
+
return {"restored_rows": [], "removed_rows": []}
|
|
2318
|
+
with kode_facts() as kf:
|
|
2319
|
+
tools = kf.tools()
|
|
2320
|
+
removed = sorted(k for k in added if tools.pop(k, None) is not None)
|
|
2321
|
+
tools.update(replaced)
|
|
2322
|
+
back = sorted(k for k in rows if k not in tools)
|
|
2323
|
+
tools.update({k: rows[k] for k in back})
|
|
2324
|
+
facts = {**kf.facts, "tools": tools}
|
|
2325
|
+
if "kode_facts_before" in rec:
|
|
2326
|
+
before = rec["kode_facts_before"]
|
|
2327
|
+
for k in ("generated", "source"):
|
|
2328
|
+
if k in (before or {}):
|
|
2329
|
+
facts[k] = before[k]
|
|
2330
|
+
else:
|
|
2331
|
+
facts.pop(k, None)
|
|
2332
|
+
if before is None and facts == {"tools": {}}:
|
|
2333
|
+
facts = None
|
|
2334
|
+
text = rec.get("kode_facts_text")
|
|
2335
|
+
if facts is None:
|
|
2336
|
+
if kf.existed:
|
|
2337
|
+
kf.save(None)
|
|
2338
|
+
elif text is not None and json.loads(text) == facts:
|
|
2339
|
+
if kf.text != text:
|
|
2340
|
+
kf.save(text)
|
|
2341
|
+
elif facts != kf.facts:
|
|
2342
|
+
kf.save(facts)
|
|
2343
|
+
return {"restored_rows": back, "removed_rows": removed}
|
|
2344
|
+
|
|
2345
|
+
|
|
2346
|
+
def migrate_undo(ctx: Ctx, args) -> dict:
|
|
2347
|
+
"""Takes back the newest migrate no --undo has taken back, finished ("ok") or interrupted ("started"): KODE_HOME's links
|
|
2348
|
+
and facts first, ~/.operator/tools last, so running --undo again finishes one that was killed part-way. If that migrate
|
|
2349
|
+
created .lock, --undo removes it: the box is unmanaged again, as before R1, and the gateway runs the restored link.
|
|
2350
|
+
With no migrate to take back, an orphan .lock (orphan_lock) is removed instead."""
|
|
2351
|
+
root, compat, tools = ctx.root, operator_home() / "tools", kode_home() / "tools"
|
|
2352
|
+
runs = migrate_runs(root)
|
|
2353
|
+
if not runs and orphan_lock(root):
|
|
2354
|
+
return undo_orphan(ctx, args)
|
|
2355
|
+
if not runs:
|
|
2356
|
+
last = last_migrate(root)
|
|
2357
|
+
raise Refused(f"the last migrate in history is {last.get('kind')}: nothing left to undo" if last else "history records no migrate to undo")
|
|
2358
|
+
rec = runs[-1]
|
|
2359
|
+
kind = rec.get("kind")
|
|
2360
|
+
if kind not in TOOLS_KINDS + ("kode-only",):
|
|
2361
|
+
raise Refused(f"the last migrate in history is of kind {kind!r}, which --undo does not know")
|
|
2362
|
+
aside, names = rec.get("kode_aside"), sorted(rec.get("kode_links") or {})
|
|
2363
|
+
if aside and not within(os.path.abspath(aside), str(kode_home())):
|
|
2364
|
+
raise Refused(f"history puts KODE_HOME's links in {aside}, outside {kode_home()}")
|
|
2365
|
+
clash = [n for n in names if aside and os.path.lexists(os.path.join(aside, n)) and os.path.lexists(tools / n)]
|
|
2366
|
+
if clash:
|
|
2367
|
+
raise Refused(f"{tools} has {', '.join(clash)} again: move them away before undoing")
|
|
2368
|
+
undo_state(root, rec)
|
|
2369
|
+
with mutation(root):
|
|
2370
|
+
state = undo_state(root, rec)
|
|
2371
|
+
restored = move_links(names, pathlib.Path(aside), tools) if aside else []
|
|
2372
|
+
if aside and os.path.isdir(aside):
|
|
2373
|
+
guard_write(aside)
|
|
2374
|
+
with contextlib.suppress(OSError):
|
|
2375
|
+
os.rmdir(aside) # empty once every link is back; anything left there keeps it
|
|
2376
|
+
facts = restore_kode_facts(rec)
|
|
2377
|
+
fault("undo-pre-tools-flip")
|
|
2378
|
+
if state == "migrated" and kind == "replace-tools-dir":
|
|
2379
|
+
guard_write(compat)
|
|
2380
|
+
guard_write(rec["from"])
|
|
2381
|
+
if compat.is_symlink():
|
|
2382
|
+
compat.unlink()
|
|
2383
|
+
try:
|
|
2384
|
+
os.rename(rec["from"], compat)
|
|
2385
|
+
except OSError:
|
|
2386
|
+
os.symlink(rec["to"], compat) # never leave ~/.operator/tools missing
|
|
2387
|
+
raise
|
|
2388
|
+
fsync_path(compat.parent)
|
|
2389
|
+
elif state == "migrated":
|
|
2390
|
+
link_into(compat, rec["from"])
|
|
2391
|
+
lock_removed = rec.get("lock_existed") is False
|
|
2392
|
+
if lock_removed:
|
|
2393
|
+
guard_write(root / ".lock")
|
|
2394
|
+
with contextlib.suppress(FileNotFoundError):
|
|
2395
|
+
(root / ".lock").unlink()
|
|
2396
|
+
history(root, "migrate", kind=f"{kind}-undo", run=rec.get("run"), undid=rec.get("result"), reason=args.reason,
|
|
2397
|
+
**{"from": rec.get("to"), "to": str(compat) if kind == "replace-tools-dir" else rec.get("from")},
|
|
2398
|
+
tools_flipped=state == "migrated", restored_links=restored, **facts, lock_removed=lock_removed)
|
|
2399
|
+
if lock_removed:
|
|
2400
|
+
box = (f"unmanaged again: this migrate had created {root / '.lock'}, so --undo removed it and the gateway's legacy chain "
|
|
2401
|
+
f"runs {compat}; the store and generations stay")
|
|
2402
|
+
else:
|
|
2403
|
+
why = ".lock was there before this migrate" if rec.get("lock_existed") else "history does not say this migrate created .lock"
|
|
2404
|
+
gens = ", ".join(f"{c} on generation {current_generation(root, c)}" for c in consumer_names(root)) or "no consumer"
|
|
2405
|
+
box = f"still managed ({why}): consumers stay where they are ({gens})"
|
|
2406
|
+
now_is = f"{compat}: the directory again" if kind == "replace-tools-dir" else f"{compat} -> {os.readlink(compat) if compat.is_symlink() else '?'}"
|
|
2407
|
+
return {"undone": kind, "of": rec.get("result"), "tools": now_is, "tools_flipped": state == "migrated", "managed": not lock_removed,
|
|
2408
|
+
"box": box, "kode_home": {"restored_links": restored, **facts}}
|
|
2409
|
+
|
|
2410
|
+
|
|
2411
|
+
def undo_orphan(ctx: Ctx, args) -> dict:
|
|
2412
|
+
"""--undo of an orphan .lock: nothing was flipped or moved, so it removes .lock under the flock, records that, and the box
|
|
2413
|
+
is unmanaged again. Under the flock it must still be an orphan: a run that held it may have activated a consumer."""
|
|
2414
|
+
root, compat, lock = ctx.root, operator_home() / "tools", ctx.root / ".lock"
|
|
2415
|
+
with mutation(root) as created:
|
|
2416
|
+
if created or not orphan_lock(root):
|
|
2417
|
+
raise Refused(f"{lock} is no longer an orphan (the run that held it has finished): nothing left to undo")
|
|
2418
|
+
guard_write(lock)
|
|
2419
|
+
lock.unlink()
|
|
2420
|
+
history(root, "migrate", kind="orphan-lock-undo", reason=args.reason, lock_removed=True, tools_flipped=False)
|
|
2421
|
+
now_is = f"{compat} -> {os.readlink(compat)}" if compat.is_symlink() else str(compat)
|
|
2422
|
+
return {"undone": "orphan .lock", "of": None, "tools": now_is, "tools_flipped": False, "managed": False,
|
|
2423
|
+
"box": f"unmanaged again: {lock} was an orphan (no consumer, and history recorded no migrate, activate or rollback), "
|
|
2424
|
+
f"so --undo removed it and the gateway's legacy chain runs {compat}; the store stays",
|
|
2425
|
+
"kode_home": {"restored_links": [], "restored_rows": [], "removed_rows": []}}
|
|
2024
2426
|
|
|
2025
2427
|
|
|
2026
2428
|
def cmd_migrate(args) -> int:
|
|
2027
2429
|
ctx = Ctx(args)
|
|
2028
|
-
if args.
|
|
2029
|
-
out = migrate_from_hermes(ctx, args)
|
|
2030
|
-
else:
|
|
2031
|
-
if args.dry_run:
|
|
2032
|
-
raise Refused("--dry-run applies to --from-hermes")
|
|
2033
|
-
out = migrate_replace_dir(ctx, args)
|
|
2430
|
+
out = migrate_undo(ctx, args) if args.undo else migrate(ctx, args)
|
|
2034
2431
|
emit(args, out, json.dumps(out, indent=1, sort_keys=True))
|
|
2432
|
+
if out.get("dry_run") and out.get("served_matches_manifest") is False:
|
|
2433
|
+
say(f"toolchain: the served {out['preflight']['served']} hashes to {out['preflight']['served_digest']}, not the manifest's "
|
|
2434
|
+
f"expect_pm_digest {out['expect_pm_digest']}: migrate would fetch and seal {out['realize']}, then refuse")
|
|
2435
|
+
return EX_REFUSED
|
|
2035
2436
|
post = out.get("postflight")
|
|
2036
2437
|
return EX_ERROR if post and not post["ok"] else EX_OK
|
|
2037
2438
|
|
|
@@ -2663,12 +3064,12 @@ def parser() -> argparse.ArgumentParser:
|
|
|
2663
3064
|
s.add_argument("--apply", action="store_true")
|
|
2664
3065
|
s.set_defaults(func=cmd_gc)
|
|
2665
3066
|
|
|
2666
|
-
s = sub.add_parser("migrate", parents=[common], help="move ~/.operator/tools onto consumers/aurora")
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
s
|
|
2671
|
-
s.add_argument("--
|
|
3067
|
+
s = sub.add_parser("migrate", parents=[common], help="move ~/.operator/tools onto consumers/aurora (the layout is detected)")
|
|
3068
|
+
mode = s.add_mutually_exclusive_group()
|
|
3069
|
+
mode.add_argument("--dry-run", action="store_true")
|
|
3070
|
+
mode.add_argument("--undo", action="store_true")
|
|
3071
|
+
# 0.1.350's spellings, still accepted so its documented commands run; the layout picks the kind, so they change nothing
|
|
3072
|
+
s.add_argument("--from-hermes", "--replace-tools-dir", dest="legacy_kind_flag", action="store_true", help=argparse.SUPPRESS)
|
|
2672
3073
|
s.add_argument("--reason", default="migrate")
|
|
2673
3074
|
s.add_argument("--cache", metavar="DIR")
|
|
2674
3075
|
s.add_argument("--offline", action="store_true")
|
|
@@ -2708,8 +3109,21 @@ def parser() -> argparse.ArgumentParser:
|
|
|
2708
3109
|
return p
|
|
2709
3110
|
|
|
2710
3111
|
|
|
3112
|
+
def terminate(signum, _frame) -> None:
|
|
3113
|
+
# a second signal must not cut the cleanup short; a no-op handler, not SIG_IGN, which the cleanup's children would inherit
|
|
3114
|
+
for s in (signal.SIGTERM, signal.SIGHUP):
|
|
3115
|
+
if signal.getsignal(s) is terminate:
|
|
3116
|
+
signal.signal(s, lambda *_: None)
|
|
3117
|
+
raise Terminated(signum)
|
|
3118
|
+
|
|
3119
|
+
|
|
2711
3120
|
def main(argv=None) -> int:
|
|
2712
3121
|
args = parser().parse_args(argv)
|
|
3122
|
+
# an agent's command timeout sends SIGTERM and a closed terminal SIGHUP; their default action ends the process with no
|
|
3123
|
+
# cleanup, which left .lock on a box no consumer was activated on. One the caller ignores (nohup) stays ignored.
|
|
3124
|
+
for s in (signal.SIGTERM, signal.SIGHUP):
|
|
3125
|
+
if signal.getsignal(s) != signal.SIG_IGN:
|
|
3126
|
+
signal.signal(s, terminate)
|
|
2713
3127
|
try:
|
|
2714
3128
|
return args.func(args)
|
|
2715
3129
|
except ToolchainError as e:
|
|
@@ -2717,6 +3131,8 @@ def main(argv=None) -> int:
|
|
|
2717
3131
|
return e.code
|
|
2718
3132
|
except KeyboardInterrupt:
|
|
2719
3133
|
return 130
|
|
3134
|
+
except Terminated as e:
|
|
3135
|
+
return 128 + e.signum
|
|
2720
3136
|
|
|
2721
3137
|
|
|
2722
3138
|
if __name__ == "__main__":
|