@ouro.bot/cli 0.1.0-alpha.1635 → 0.1.0-alpha.1637

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.
@@ -53,12 +53,15 @@ const sanctuary_authority_vault_migration_1 = require("./sanctuary-authority-vau
53
53
  const session_transaction_1 = require("../../mind/session-transaction");
54
54
  const runtime_1 = require("../../nerves/runtime");
55
55
  const failure_code_1 = require("./cli-commands/failure-code");
56
+ const butler_agent_1 = require("../butler-agent");
56
57
  const ROOT = "/mnt/user/appdata/ouro-authority";
57
- const BUNDLE = "/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro";
58
+ // The host folder that holds the Butler's bundle. The bundle in it keeps the name it has on disk (the live host's stays
59
+ // sanctuary.ouro through the rename); only where it is mounted inside the container follows the image's name.
60
+ const AGENT = "/mnt/user/appdata/ouro-butler/agent";
58
61
  const RUNTIME = "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli";
59
- const OFFSET = `${BUNDLE}/state/senses/telegram/offset.json`;
62
+ const OFFSET = "state/senses/telegram/offset.json";
60
63
  const SOCKET = "/run/ouro-authority";
61
- // Operator-set grants, root-owned on the host and mounted read-only into the Butler at /etc/ouro/trust/sanctuary.
64
+ // Operator-set grants, root-owned on the host and mounted read-only into the Butler at /etc/ouro/trust/<the image's Butler name>.
62
65
  const TRUST = "/mnt/user/appdata/ouro-butler/trust/sanctuary";
63
66
  // The bundle sync deploy key's host folder, mounted read-only where the sync wrapper reads it (from alpha.991).
64
67
  const SYNC = "/mnt/user/appdata/ouro-butler/sync";
@@ -91,6 +94,8 @@ const GATEWAY_LOG_TAIL_CHARS = 2_000;
91
94
  // Read more than is shown, so masking sees whole tokens before the tail is cut.
92
95
  const GATEWAY_LOG_READ_BYTES = 4_096;
93
96
  const GATEWAY_LOG_MAX_BYTES = 5 * 1024 * 1024;
97
+ // A container mounting the host bundle under either name could poll Telegram directly.
98
+ const HOST_BUNDLES = butler_agent_1.BUTLER_AGENT_NAMES.map((name) => `${AGENT}/${name}.ouro`);
94
99
  const TEMPLATE_JOURNAL = "/boot/config/custom/ouro-butler/docker-man-template-transaction.json";
95
100
  // In-place upgrade of an installed authority: same epoch (token, issuer, cursor,
96
101
  // gateway state), new reviewed package and resident image. Every root record it
@@ -281,8 +286,8 @@ class SanctuaryAuthorityRootLifecycle {
281
286
  throw new Error("Sanctuary previous epoch handoff is incomplete");
282
287
  }
283
288
  // A missing cursor is not a fresh install: it is lost handoff evidence.
284
- fs.lstatSync(this.#p(OFFSET));
285
- const predecessorCursor = new telegram_client_1.FileTelegramOffsetStore(this.#p(OFFSET)).load();
289
+ fs.lstatSync(this.#p(this.#offset()));
290
+ const predecessorCursor = new telegram_client_1.FileTelegramOffsetStore(this.#p(this.#offset())).load();
286
291
  const snapshot = this.#vault("snapshot");
287
292
  if (["botId", "ownerUserId", "ownerChatId"].some((key) => snapshot[key] !== this.#request[key]))
288
293
  throw new Error("Sanctuary predecessor identity changed");
@@ -762,7 +767,7 @@ class SanctuaryAuthorityRootLifecycle {
762
767
  return false;
763
768
  this.#record(`${this.#epochRoot()}/restored.json`, { tokenDigest: this.#epoch().tokenDigest, cursor: this.#epoch().terminalCursor });
764
769
  const token = this.#vault("snapshot");
765
- return digest(token.token) === this.#epoch().tokenDigest && new telegram_client_1.FileTelegramOffsetStore(this.#p(OFFSET)).load() >= this.#epoch().terminalCursor;
770
+ return digest(token.token) === this.#epoch().tokenDigest && new telegram_client_1.FileTelegramOffsetStore(this.#p(this.#offset())).load() >= this.#epoch().terminalCursor;
766
771
  }
767
772
  #restoreToken() {
768
773
  this.#requireStopped();
@@ -776,12 +781,12 @@ class SanctuaryAuthorityRootLifecycle {
776
781
  if (digest(token) !== epoch.tokenDigest)
777
782
  throw new Error("Sanctuary current token handoff identity changed");
778
783
  this.#vault("restore", { token, botId: epoch.botId, ownerUserId: epoch.ownerUserId, ownerChatId: epoch.ownerChatId });
779
- new telegram_client_1.FileTelegramOffsetStore(this.#p(OFFSET)).save(epoch.terminalCursor);
784
+ new telegram_client_1.FileTelegramOffsetStore(this.#p(this.#offset())).save(epoch.terminalCursor);
780
785
  // Restore the original resident ownership; root must not strand a root-owned cursor.
781
- fs.chownSync(this.#p(OFFSET), this.#uid === 0 ? 10001 : this.#uid, this.#uid === 0 ? 10001 : this.#gid);
786
+ fs.chownSync(this.#p(this.#offset()), this.#uid === 0 ? 10001 : this.#uid, this.#uid === 0 ? 10001 : this.#gid);
782
787
  this.#write(`${this.#epochRoot()}/restored.json`, JSON.stringify({ tokenDigest: epoch.tokenDigest, cursor: epoch.terminalCursor }));
783
788
  const restored = this.#vault("snapshot");
784
- if (digest(restored.token) !== epoch.tokenDigest || new telegram_client_1.FileTelegramOffsetStore(this.#p(OFFSET)).load() !== epoch.terminalCursor)
789
+ if (digest(restored.token) !== epoch.tokenDigest || new telegram_client_1.FileTelegramOffsetStore(this.#p(this.#offset())).load() !== epoch.terminalCursor)
785
790
  throw new Error("Sanctuary token and cursor handoff readback failed");
786
791
  (0, sanctuary_authority_epoch_1.releaseSanctuaryAuthorityToken)(this.#p(this.#epochRoot()), { expectedUid: this.#uid, expectedGid: this.#gid, tokenDigest: epoch.tokenDigest, cursor: epoch.terminalCursor });
787
792
  if (fs.existsSync(this.#p(`${ROOT}/incoming-token`))) {
@@ -1038,14 +1043,19 @@ class SanctuaryAuthorityRootLifecycle {
1038
1043
  * release's audit refuses it.
1039
1044
  */
1040
1045
  #recreateResident(reference, imageId, { psycheMount, syncMount }) {
1046
+ // The image names where its bundle and trust are mounted; the host folders stay where they are. `--mount` refuses a
1047
+ // missing source, where `-v` would have Docker create an empty folder in its place. Both are read before the resident
1048
+ // goes, so a failed inspect leaves it standing.
1049
+ const bundle = this.#hostBundle();
1050
+ const { agentRoot, trustRoot } = (0, butler_agent_1.butlerContainerPaths)(this.#imageButler(imageId));
1041
1051
  if (this.#containers().some((container) => container.Name === "/ouro-butler"))
1042
1052
  this.#docker(["rm", "-f", "ouro-butler"]);
1043
1053
  this.#docker(["create", "--name", "ouro-butler", "--network", "host", "--restart", "unless-stopped", "--user", "10001:10001",
1044
1054
  "-l", "net.unraid.docker.managed=dockerman", "-l", `net.unraid.docker.icon=${ICON}`, "-l", "org.opencontainers.image.source=https://github.com/ourostack/ouroboros",
1045
- "-v", `${RUNTIME}:/home/ouro/.ouro-cli:rw`, "-v", `${BUNDLE}:/home/ouro/AgentBundles/sanctuary.ouro:rw`,
1055
+ "-v", `${RUNTIME}:/home/ouro/.ouro-cli:rw`, "--mount", `type=bind,src=${bundle},dst=${agentRoot}`,
1046
1056
  "-v", `${EVENTS}:/run/ouro-events:ro`, "-v", `${SOCKET}:${SOCKET}:ro`,
1047
- ...(psycheMount ? ["-v", `${BUNDLE}/psyche:/home/ouro/AgentBundles/sanctuary.ouro/psyche:ro`] : []),
1048
- "-v", `${TRUST}:/etc/ouro/trust/sanctuary:ro`,
1057
+ ...(psycheMount ? ["--mount", `type=bind,src=${bundle}/psyche,dst=${agentRoot}/psyche,readonly`] : []),
1058
+ "--mount", `type=bind,src=${TRUST},dst=${trustRoot},readonly`,
1049
1059
  ...(syncMount ? ["-v", `${SYNC}:/run/ouro-sync:ro`] : []), reference]);
1050
1060
  const resident = this.#containers().find((container) => container.Name === "/ouro-butler");
1051
1061
  if (resident?.Image !== imageId || resident.State.Running)
@@ -1054,10 +1064,10 @@ class SanctuaryAuthorityRootLifecycle {
1054
1064
  /** Run the installed package's bundle migration CLI, then return the bundle to the resident. */
1055
1065
  #bundle(operation) {
1056
1066
  (0, node_child_process_1.execFileSync)(this.#p("/usr/local/bin/node"), [this.#p(`${ROOT}/package/deploy/unraid/migrate-sanctuary-bundle.mjs`),
1057
- "--package-root", this.#p(`${ROOT}/package/deploy/unraid/sanctuary.ouro`), "--agent-root", this.#p(BUNDLE), ...operation], {
1067
+ "--package-root", this.#p(`${ROOT}/package/deploy/unraid/sanctuary.ouro`), "--agent-root", this.#p(this.#hostBundle()), ...operation], {
1058
1068
  encoding: "utf8", timeout: 300_000, stdio: ["ignore", "pipe", "pipe"], env: { PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" }, cwd: "/",
1059
1069
  });
1060
- (0, node_child_process_1.execFileSync)("/bin/chown", ["-R", "10001:10001", this.#p(BUNDLE)], { stdio: "ignore" });
1070
+ (0, node_child_process_1.execFileSync)("/bin/chown", ["-R", "10001:10001", this.#p(this.#hostBundle())], { stdio: "ignore" });
1061
1071
  this.#restoreReplayRoot();
1062
1072
  }
1063
1073
  /**
@@ -1072,7 +1082,7 @@ class SanctuaryAuthorityRootLifecycle {
1072
1082
  * `state` itself may be a link too: compare realpaths before any chown or chmod ever runs.
1073
1083
  */
1074
1084
  #stateChild(name) {
1075
- const bundle = this.#p(BUNDLE);
1085
+ const bundle = this.#p(this.#hostBundle());
1076
1086
  const directory = path.join(bundle, "state", name);
1077
1087
  let stat;
1078
1088
  try {
@@ -1139,6 +1149,15 @@ class SanctuaryAuthorityRootLifecycle {
1139
1149
  return !fs.readFileSync(file, "utf8").split("\n").some((line) => /^ouro-butler(?:-rollback|-staging|-legacy-evidence)?(?:\s|$)/u.test(line));
1140
1150
  }
1141
1151
  #p(absolute) { return `${this.#prefix}${absolute}`; }
1152
+ /** The host bundle folder, by the name it has on disk; sanctuary.ouro when neither or both are there. */
1153
+ #hostBundle() {
1154
+ return `${AGENT}/${(0, butler_agent_1.butlerOnDisk)(this.#p(AGENT), fs.existsSync) ?? "sanctuary"}.ouro`;
1155
+ }
1156
+ #offset() { return `${this.#hostBundle()}/${OFFSET}`; }
1157
+ /** The Butler an image runs, from its own ENTRYPOINT. */
1158
+ #imageButler(imageId) {
1159
+ return (0, butler_agent_1.butlerNameFromEntrypoint)(JSON.parse(this.#docker(["image", "inspect", "--format", "{{json .Config.Entrypoint}}", imageId])));
1160
+ }
1142
1161
  #bootScript() {
1143
1162
  const mode = fs.lstatSync(this.#p("/boot/config/go")).mode & 0o7777;
1144
1163
  if (![0o600, 0o644, 0o700, 0o755].includes(mode))
@@ -1233,7 +1252,7 @@ class SanctuaryAuthorityRootLifecycle {
1233
1252
  (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_poller_scan_container_gone", message: "skipped a container that stopped during the direct-poller scan", meta: { name } });
1234
1253
  continue;
1235
1254
  }
1236
- if (containers.some((container) => container.Mounts.some((mount) => mount.Source === BUNDLE || mount.Source === RUNTIME)))
1255
+ if (containers.some((container) => container.Mounts.some((mount) => HOST_BUNDLES.includes(mount.Source) || mount.Source === RUNTIME)))
1237
1256
  throw new Error("Sanctuary has an unowned possible direct poller");
1238
1257
  }
1239
1258
  }
@@ -1268,7 +1287,7 @@ class SanctuaryAuthorityRootLifecycle {
1268
1287
  "--cap-drop=ALL", "--cap-add=DAC_OVERRIDE", "--security-opt=no-new-privileges", "--entrypoint", "/bin/sh",
1269
1288
  "--mount", `type=bind,src=${RUNTIME},dst=/home/ouro/.ouro-cli,readonly`,
1270
1289
  ...bitwarden,
1271
- "--mount", `type=bind,src=${BUNDLE},dst=/home/ouro/AgentBundles/sanctuary.ouro,readonly`,
1290
+ "--mount", `type=bind,src=${this.#hostBundle()},dst=${(0, butler_agent_1.butlerContainerPaths)(this.#imageButler(this.#transaction.targetImageId)).agentRoot},readonly`,
1272
1291
  "--tmpfs", "/home/ouro/.config:rw,nosuid,nodev,noexec,mode=0700",
1273
1292
  "--tmpfs", "/tmp:rw,nosuid,nodev,noexec,mode=0700",
1274
1293
  "--env", `OURO_AUTHORITY_REMOVE_INTERLOCK=${this.#request.epochId}`,
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.SANCTUARY_GIT_EXCLUDES = exports.SANCTUARY_BUNDLE_ROLLBACK_FILE = exports.SANCTUARY_STARTER_PSYCHE_FILES = exports.SANCTUARY_PACKAGE_MANAGED_FILES = void 0;
36
+ exports.SANCTUARY_BUNDLE_PATH_FILES = exports.SANCTUARY_GIT_EXCLUDES = exports.SANCTUARY_BUNDLE_ROLLBACK_FILE = exports.SANCTUARY_STARTER_PSYCHE_FILES = exports.SANCTUARY_PACKAGE_MANAGED_FILES = void 0;
37
37
  exports.sanctuaryGitExcludeText = sanctuaryGitExcludeText;
38
38
  exports.bundleSyncEnabled = bundleSyncEnabled;
39
39
  exports.writeSanctuaryGitExclude = writeSanctuaryGitExclude;
@@ -52,6 +52,7 @@ const node_child_process_1 = require("node:child_process");
52
52
  const node_crypto_1 = require("node:crypto");
53
53
  const runtime_1 = require("../../nerves/runtime");
54
54
  const house_names_1 = require("../../mind/house-names");
55
+ const butler_agent_1 = require("../butler-agent");
55
56
  exports.SANCTUARY_PACKAGE_MANAGED_FILES = [
56
57
  "provider-readiness.json",
57
58
  "tool-profiles.json",
@@ -315,6 +316,60 @@ function writeAtomic(filePath, content, mode = 0o600) {
315
316
  syncDirectory(path.dirname(filePath));
316
317
  }
317
318
  const SNAPSHOT_RELATIVES = [...exports.SANCTUARY_PACKAGE_MANAGED_FILES, "bundle-meta.json"];
319
+ /**
320
+ * The install's own files that name the bundle's container path, and so follow the Butler's name on a migrate. Nothing
321
+ * else is rewritten: never psyche/, friends/, sessions or logs. `skills/*.md` stands for every skill file at the top of skills/.
322
+ */
323
+ exports.SANCTUARY_BUNDLE_PATH_FILES = ["agent.json", "state/replay-client/provision.json", "state/attachments/recent.json", "skills/*.md", "house/HOUSE.md"];
324
+ const SKILL_FILE = /^skills\/[^/]+\.md$/u;
325
+ function isBundlePathFile(relative) {
326
+ return SKILL_FILE.test(relative) || exports.SANCTUARY_BUNDLE_PATH_FILES.includes(relative);
327
+ }
328
+ const containerBundlePath = (name) => `/home/ouro/AgentBundles/${name}.ouro`;
329
+ /**
330
+ * The Butler a migrate runs for: the one it is told, or the one its agent root is named after; null for any other bundle,
331
+ * and for `null`, which the host passes when it names no Butler: its folder keeps the name `sanctuary` whatever the image runs.
332
+ */
333
+ function migrationButlerName(agentRoot, given) {
334
+ if (given !== undefined)
335
+ return given;
336
+ const name = path.basename(agentRoot).replace(/\.ouro$/u, "");
337
+ return (0, butler_agent_1.isButlerAgent)(name) ? name : null;
338
+ }
339
+ /** The allowlisted files that name the other Butler's container path, with that path changed to `name`'s. */
340
+ function planBundlePathRewrites(agentRoot, name) {
341
+ if (!name)
342
+ return [];
343
+ const other = butler_agent_1.BUTLER_AGENT_NAMES.find((candidate) => candidate !== name);
344
+ // The other bundle's path, and not a longer folder name that starts with it.
345
+ const escaped = containerBundlePath(other).replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
346
+ const pattern = new RegExp(`${escaped}(?![A-Za-z0-9._-])`, "gu");
347
+ const skills = path.join(agentRoot, "skills");
348
+ let skillFiles = [];
349
+ try {
350
+ if (fs.statSync(skills).isDirectory())
351
+ skillFiles = fs.readdirSync(skills).filter((entry) => entry.endsWith(".md")).sort().map((entry) => `skills/${entry}`);
352
+ }
353
+ catch (error) {
354
+ if (!isMissing(error))
355
+ throw error;
356
+ }
357
+ const relatives = [...exports.SANCTUARY_BUNDLE_PATH_FILES.filter((relative) => !relative.includes("*")), ...skillFiles];
358
+ const rewrites = [];
359
+ for (const relative of relatives) {
360
+ const filePath = path.join(agentRoot, relative);
361
+ if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile())
362
+ continue;
363
+ const text = fs.readFileSync(filePath, "utf8");
364
+ const next = text.replace(pattern, containerBundlePath(name));
365
+ if (next === text)
366
+ continue;
367
+ // Only a file that needs the rewrite must be a real one inside the bundle; anything else is left as it is.
368
+ validateDestination(agentRoot, relative);
369
+ rewrites.push({ relative, content: Buffer.from(next, "utf8"), mode: fs.lstatSync(filePath).mode & 0o777 });
370
+ }
371
+ return rewrites;
372
+ }
318
373
  function packageManagedArtifactPaths(agentRoot) {
319
374
  return SNAPSHOT_RELATIVES.map((relative) => path.join(agentRoot, relative));
320
375
  }
@@ -377,8 +432,8 @@ function snapshotDirectoryRelatives() {
377
432
  }
378
433
  return [...directories].sort((left, right) => left.length - right.length);
379
434
  }
380
- function captureMigrationSnapshot(agentRoot) {
381
- const files = SNAPSHOT_RELATIVES.map((relative) => {
435
+ function captureMigrationSnapshot(agentRoot, extraRelatives = []) {
436
+ const files = [...SNAPSHOT_RELATIVES, ...extraRelatives].map((relative) => {
382
437
  const filePath = path.join(agentRoot, relative);
383
438
  if (!fs.existsSync(filePath))
384
439
  return { path: filePath, content: null, mode: null };
@@ -447,9 +502,12 @@ function readDurableRecord(agentRoot) {
447
502
  const fileRelatives = record.files.map((file) => file?.relative);
448
503
  const directoryRelatives = record.directories.map((directory) => directory?.relative);
449
504
  const expectedDirectories = snapshotDirectoryRelatives();
450
- if (JSON.stringify(fileRelatives) !== JSON.stringify(SNAPSHOT_RELATIVES) || JSON.stringify(directoryRelatives) !== JSON.stringify(expectedDirectories))
505
+ // After the managed files come any bundle-path files the migrate rewrote, each once and each on the allowlist.
506
+ const extraRelatives = fileRelatives.slice(SNAPSHOT_RELATIVES.length);
507
+ const validExtras = extraRelatives.every((relative) => typeof relative === "string" && isBundlePathFile(relative)) && new Set(extraRelatives).size === extraRelatives.length;
508
+ if (JSON.stringify(fileRelatives.slice(0, SNAPSHOT_RELATIVES.length)) !== JSON.stringify(SNAPSHOT_RELATIVES) || !validExtras || JSON.stringify(directoryRelatives) !== JSON.stringify(expectedDirectories))
451
509
  throw new Error("Sanctuary bundle rollback record paths are invalid");
452
- for (const relative of SNAPSHOT_RELATIVES)
510
+ for (const relative of [...SNAPSHOT_RELATIVES, ...extraRelatives])
453
511
  validateDestination(agentRoot, relative);
454
512
  const validMode = (mode) => mode === null || (Number.isInteger(mode) && mode >= 0 && mode <= 0o777);
455
513
  const files = record.files.map((file) => {
@@ -916,8 +974,10 @@ function migrateSanctuaryPackageManagedBundle(input) {
916
974
  if (!(field in packagedMeta))
917
975
  throw new Error(`packaged bundle-meta.json is missing ${field}`);
918
976
  validatePackagedPolicy(input.packageRoot);
919
- cleanupInterruptedWrites(packageManagedArtifactPaths(input.agentRoot));
920
- snapshot = captureMigrationSnapshot(input.agentRoot);
977
+ const rewrites = planBundlePathRewrites(input.agentRoot, migrationButlerName(input.agentRoot, input.butlerName));
978
+ const rewriteModes = new Map(rewrites.map((rewrite) => [path.join(input.agentRoot, rewrite.relative), rewrite.mode]));
979
+ cleanupInterruptedWrites([...packageManagedArtifactPaths(input.agentRoot), ...rewriteModes.keys()], rewriteModes);
980
+ snapshot = captureMigrationSnapshot(input.agentRoot, rewrites.map((rewrite) => rewrite.relative));
921
981
  if (input.retainRollback) {
922
982
  writeAtomic(existingRollback, `${JSON.stringify(durableSnapshot(input.agentRoot, snapshot, input.rollbackImageId, input.targetImageId))}\n`);
923
983
  }
@@ -950,9 +1010,14 @@ function migrateSanctuaryPackageManagedBundle(input) {
950
1010
  fs.closeSync(meta);
951
1011
  }
952
1012
  }
1013
+ // The install's own files that name the bundle's container path now name the Butler this release runs.
1014
+ for (const rewrite of rewrites)
1015
+ writeAtomic(path.join(input.agentRoot, rewrite.relative), rewrite.content, rewrite.mode);
1016
+ if (rewrites.length > 0)
1017
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_bundle_paths_rewritten", message: "pointed the bundle's own container paths at the Butler's name", meta: { agentRoot: input.agentRoot, files: rewrites.map((rewrite) => rewrite.relative) } });
953
1018
  if (!seedSanctuaryPsycheIfAbsent({ packageRoot: input.packageRoot, agentRoot: input.agentRoot }).ok)
954
1019
  throw new Error("psyche must be a real directory, not a symlink or file");
955
- const result = { managedFilesUpdated };
1020
+ const result = { managedFilesUpdated, ...(rewrites.length > 0 ? { bundlePathsRewritten: rewrites.length } : {}) };
956
1021
  (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_bundle_migration_end", message: "completed Sanctuary package-managed bundle migration", meta: result });
957
1022
  return result;
958
1023
  }
@@ -37,6 +37,7 @@ exports.ExternalEventScanCache = void 0;
37
37
  exports.getExternalEventRoot = getExternalEventRoot;
38
38
  exports.externalEventRecordPath = externalEventRecordPath;
39
39
  exports.readExternalEventRecord = readExternalEventRecord;
40
+ exports.prepareButlerExternalEvents = prepareButlerExternalEvents;
40
41
  exports.repairExternalEventsFromManifest = repairExternalEventsFromManifest;
41
42
  exports.listExternalEventStatus = listExternalEventStatus;
42
43
  exports.buildExternalEventMessage = buildExternalEventMessage;
@@ -318,17 +319,87 @@ function isRecord(value) {
318
319
  && validFailure
319
320
  && validGrant;
320
321
  }
321
- function readExternalEventRecord(recordPath) {
322
+ // The Butler this daemon runs, set once at daemon start. Records saved under the Butler's other name are its records.
323
+ let runningButler = null;
324
+ /** The agent a record or new event belongs to: a Butler name means the running Butler, or the Butler folder it sits in. */
325
+ function eventAgent(agent, folder) {
326
+ if (!(0, butler_agent_1.isButlerAgent)(agent))
327
+ return agent;
328
+ if (runningButler)
329
+ return runningButler;
330
+ return folder !== undefined && (0, butler_agent_1.isButlerAgent)(folder) ? folder : agent;
331
+ }
332
+ /** The record as the daemon sees it: owned by the running Butler, at the path it was read from. */
333
+ function normaliseButlerRecord(record, recordPath) {
334
+ const agent = eventAgent(record.agent, path.basename(path.dirname(path.dirname(recordPath))));
335
+ return agent === record.agent && record.recordPath === recordPath ? record : { ...record, agent, recordPath };
336
+ }
337
+ /** The record exactly as saved, after checking it sits where its identity says (or in the other Butler name's folder). */
338
+ function readStoredExternalEventRecord(recordPath) {
322
339
  const parsed = JSON.parse(fs.readFileSync(recordPath, "utf8"));
323
340
  if (!isRecord(parsed))
324
341
  throw new Error(`External event record is invalid: ${recordPath}`);
325
342
  const root = path.dirname(path.dirname(path.dirname(recordPath)));
326
- const expectedPath = externalEventRecordPath(root, parsed);
327
- if (path.resolve(parsed.recordPath) !== path.resolve(recordPath) || path.resolve(expectedPath) !== path.resolve(recordPath)) {
343
+ const here = path.resolve(recordPath);
344
+ const expectedPath = path.resolve(externalEventRecordPath(root, parsed));
345
+ if (path.resolve(parsed.recordPath) === here && expectedPath === here)
346
+ return parsed;
347
+ // A Butler record whose folder was adopted under the Butler's other name: it names the folder it was written in, or this one.
348
+ const folder = path.basename(path.dirname(path.dirname(recordPath)));
349
+ const adopted = (0, butler_agent_1.isButlerAgent)(parsed.agent) && (0, butler_agent_1.isButlerAgent)(folder)
350
+ && path.resolve(externalEventRecordPath(root, { ...parsed, agent: folder })) === here
351
+ && [here, expectedPath].includes(path.resolve(parsed.recordPath));
352
+ if (!adopted)
328
353
  throw new Error(`External event record identity is invalid: ${recordPath}`);
329
- }
330
354
  return parsed;
331
355
  }
356
+ function readExternalEventRecord(recordPath) {
357
+ return normaliseButlerRecord(readStoredExternalEventRecord(recordPath), recordPath);
358
+ }
359
+ /**
360
+ * At daemon start, the running Butler takes over the event folder saved under its other name (from before the rename,
361
+ * or from the release a rollback left). A same-filesystem rename; with both folders present, both stay and it warns.
362
+ */
363
+ function prepareButlerExternalEvents(root, managedAgents) {
364
+ const butler = (0, butler_agent_1.managedButlerAgent)(managedAgents);
365
+ runningButler = butler;
366
+ if (!butler)
367
+ return "none";
368
+ const own = path.join(root, butler);
369
+ const others = butler_agent_1.BUTLER_AGENT_NAMES.filter((name) => name !== butler).map((name) => path.join(root, name)).filter((dir) => fs.existsSync(dir));
370
+ if (others.length === 0)
371
+ return "none";
372
+ if (fs.existsSync(own)) {
373
+ (0, runtime_1.emitNervesEvent)({
374
+ level: "warn",
375
+ component: "daemon",
376
+ event: "daemon.external_events_adoption_conflict",
377
+ message: "both Butler names have external-event folders; leaving both in place",
378
+ meta: { butler, own, others },
379
+ });
380
+ return "both-present";
381
+ }
382
+ try {
383
+ fs.renameSync(others[0], own);
384
+ }
385
+ catch (error) {
386
+ (0, runtime_1.emitNervesEvent)({
387
+ level: "warn",
388
+ component: "daemon",
389
+ event: "daemon.external_events_adoption_failed",
390
+ message: "could not move the Butler's other-name external-event folder",
391
+ meta: { butler, from: others[0], to: own, error: error instanceof Error ? error.message : /* v8 ignore next -- fs throws Error objects @preserve */ String(error) },
392
+ });
393
+ return "failed";
394
+ }
395
+ (0, runtime_1.emitNervesEvent)({
396
+ component: "daemon",
397
+ event: "daemon.external_events_adopted",
398
+ message: "moved the Butler's other-name external-event folder to the running Butler",
399
+ meta: { butler, from: others[0], to: own },
400
+ });
401
+ return "adopted";
402
+ }
332
403
  const MAX_REPAIR_MANIFEST_BYTES = 1024 * 1024;
333
404
  const MAX_REPAIR_ENTRIES = 512;
334
405
  const SHA256_HEX = /^[a-f0-9]{64}$/u;
@@ -409,9 +480,17 @@ function parseRepairManifest(manifestPath) {
409
480
  }
410
481
  return value;
411
482
  }
483
+ /** The folder a reviewed repair's record is in: its own agent's, or the other Butler name's once the daemon adopted it. */
484
+ function repairFolderAgent(root, entry) {
485
+ if (!(0, butler_agent_1.isButlerAgent)(entry.agent))
486
+ return entry.agent;
487
+ const names = [entry.agent, ...butler_agent_1.BUTLER_AGENT_NAMES.filter((name) => name !== entry.agent)];
488
+ return names.find((agent) => fs.existsSync(externalEventRecordPath(root, { ...entry, agent }))) ?? entry.agent;
489
+ }
412
490
  function assertRepairRecordPath(root, entry) {
413
491
  const resolvedRoot = path.resolve(root);
414
- const recordPath = externalEventRecordPath(resolvedRoot, entry);
492
+ const folderAgent = repairFolderAgent(resolvedRoot, entry);
493
+ const recordPath = externalEventRecordPath(resolvedRoot, { ...entry, agent: folderAgent });
415
494
  const relative = path.relative(resolvedRoot, path.resolve(recordPath));
416
495
  /* v8 ignore next -- defense in depth: safePathSegment cannot emit traversal @preserve */
417
496
  if (relative.startsWith("..") || path.isAbsolute(relative))
@@ -425,8 +504,8 @@ function assertRepairRecordPath(root, entry) {
425
504
  }
426
505
  const expected = [
427
506
  [resolvedRoot, "directory"],
428
- [path.join(resolvedRoot, safePathSegment(entry.agent)), "directory"],
429
- [path.join(resolvedRoot, safePathSegment(entry.agent), safePathSegment(entry.source)), "directory"],
507
+ [path.join(resolvedRoot, safePathSegment(folderAgent)), "directory"],
508
+ [path.join(resolvedRoot, safePathSegment(folderAgent), safePathSegment(entry.source)), "directory"],
430
509
  [recordPath, "file"],
431
510
  ];
432
511
  for (const [candidate, kind] of expected) {
@@ -467,7 +546,7 @@ function repairExternalEventsFromManifest(manifestPath, options) {
467
546
  const recordPath = assertRepairRecordPath(root, entry);
468
547
  const raw = fs.readFileSync(recordPath);
469
548
  const digest = digestBytes(raw);
470
- const record = readExternalEventRecord(recordPath);
549
+ const record = readStoredExternalEventRecord(recordPath);
471
550
  if (digest === entry.postimageSha256) {
472
551
  assertRepairPostimage(record, entry, manifest.repairedAt);
473
552
  prepared.push({ entry, recordPath, state: "post" });
@@ -504,13 +583,13 @@ function repairExternalEventsFromManifest(manifestPath, options) {
504
583
  const raw = fs.readFileSync(item.recordPath);
505
584
  const digest = digestBytes(raw);
506
585
  if (digest === item.entry.postimageSha256) {
507
- assertRepairPostimage(readExternalEventRecord(item.recordPath), item.entry, manifest.repairedAt);
586
+ assertRepairPostimage(readStoredExternalEventRecord(item.recordPath), item.entry, manifest.repairedAt);
508
587
  result.alreadyApplied.push(identity);
509
588
  return;
510
589
  }
511
590
  if (digest !== item.entry.preimageSha256)
512
591
  throw new Error("record advanced after prevalidation");
513
- const record = readExternalEventRecord(item.recordPath);
592
+ const record = readStoredExternalEventRecord(item.recordPath);
514
593
  atomicWrite(item.recordPath, repairedRecord(record, manifest.repairedAt));
515
594
  result.applied.push(identity);
516
595
  });
@@ -686,7 +765,7 @@ function readExisting(recordPath) {
686
765
  try {
687
766
  const parsed = JSON.parse(fs.readFileSync(recordPath, "utf8"));
688
767
  if (isRecord(parsed))
689
- return { record: parsed, corruptDuplicateCount: 0 };
768
+ return { record: normaliseButlerRecord(parsed, recordPath), corruptDuplicateCount: 0 };
690
769
  const duplicateCount = parsed && typeof parsed === "object" && !Array.isArray(parsed) && typeof parsed.duplicateCount === "number"
691
770
  ? Number(parsed.duplicateCount) + 1
692
771
  : 1;
@@ -741,8 +820,10 @@ const EXHAUSTED_RECOVERY_SLOTS = 6;
741
820
  function exhaustedRecoverySlot(record) {
742
821
  return (0, node_crypto_1.createHash)("sha256").update(`${record.agent}\0${record.source}\0${record.eventId}`).digest().readUInt32BE(0) % EXHAUSTED_RECOVERY_SLOTS;
743
822
  }
744
- function recordExternalEventInternal(input, options = {}) {
745
- validateExternalEventInput(input);
823
+ function recordExternalEventInternal(given, options = {}) {
824
+ validateExternalEventInput(given);
825
+ // An event naming the Butler's other name is the running Butler's, filed in its folder.
826
+ const input = { ...given, agent: eventAgent(given.agent) };
746
827
  const now = options.now?.() ?? new Date().toISOString();
747
828
  const root = options.root ?? getExternalEventRoot();
748
829
  const recordPath = externalEventRecordPath(root, input);
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1635",
3
+ "version": "0.1.0-alpha.1637",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1635",
9
+ "version": "0.1.0-alpha.1637",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1635",
3
+ "version": "0.1.0-alpha.1637",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {