@ouro.bot/cli 0.1.0-alpha.1500 → 0.1.0-alpha.1502

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/changelog.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1502",
6
+ "changes": [
7
+ "State retention now deletes a gzipped local mail copy once Blob is proven to hold the same mail: under the same key, Blob's message records the same raw size and SHA-256, and its raw object exists. A copy whose upload it can't confirm stays, and the daemon logs counts only (`daemon.state_retention_mailroom_proven_copies`)."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1501",
12
+ "changes": [
13
+ "The eval sandbox can build Slugger's bundle for a run from a `git archive` of one commit of his bundle, keeping only `psyche/` (without `TACIT.md` or `psyche/memory/`), `skills/`, `bundle-meta.json` and an allowlisted `agent.json` whose MCP servers point at the run's fakes. It creates every path his profile writes and stops before any model call if a projected file's name or contents, a folder's name or a reported gap holds one of his household's leak patterns."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1500",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1500",
2
+ "runtimeVersion": "0.1.0-alpha.1502",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1500</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1502</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -0,0 +1,289 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.LEAK_PATTERNS = exports.SLUGGER_WRITABLE = void 0;
7
+ exports.archiveBundle = archiveBundle;
8
+ exports.removeArchive = removeArchive;
9
+ exports.projectAgentConfig = projectAgentConfig;
10
+ exports.readLeakPatterns = readLeakPatterns;
11
+ exports.leakLint = leakLint;
12
+ exports.projectSlugger = projectSlugger;
13
+ exports.sluggerProfile = sluggerProfile;
14
+ /**
15
+ * Slugger's bundle for a sandboxed run: a projection built from an allowlist, never a mount of his live bundle.
16
+ *
17
+ * - **Source.** `archiveBundle` runs `git archive <commit>` of his bundle into a new temporary folder, so the live
18
+ * working tree is never read or written. The projection refuses any source folder that isn't an archive this module
19
+ * made and hasn't yet removed, and `removeArchive` deletes one by its exact path and reads back that it is gone.
20
+ * - **Kept:** `psyche/` except `TACIT.md` and the old fact store `psyche/memory/`, `skills/`, and `bundle-meta.json`.
21
+ * - **`agent.json`:** rebuilt from an allowlist of keys (`version`, `enabled`, `humanFacing`, `agentFacing`,
22
+ * `context`, `phrases`), each sense's on and off flag only, and `mcpServers` pointed at the run's fakes with no `env`.
23
+ * A server with no fake is left out, and so is every other key (`vault`, `home`, `sync`, `hostUsername`, ...).
24
+ * - **Dropped:** everything else, including `friends/`, `state/`, `desk/`, `arc/`, `tasks/`, `vault`, every
25
+ * dot-file and dot-folder (`.git`, `.backup/`, ...) and every symbolic link.
26
+ * - **Created empty:** every path Slugger's profile may write, so `books/` too, where the sandbox writes the books
27
+ * CLI's synthetic settings.
28
+ * - **Leak lint.** The household's names, handles, emails and addresses are kept in his private bundle at
29
+ * `eval/leak-patterns.json` (`{ "literals": [...] }`) and never committed to the harness. They are read from the
30
+ * same commit as the rest, so an older commit is checked against the list it had then. Each one is matched, in any
31
+ * case, against every projected file's and folder's name, every file's contents and every gap before any model call.
32
+ * A match, or no pattern file, stops the projection and removes it; the error gives counts only, never a match.
33
+ * `git archive` follows the bundle repository's `export-ignore` and `export-subst` attributes; a top-level entry left
34
+ * out that way fails the archive's completeness check.
35
+ * What differs from the live bundle comes back as `gaps`, which every report lists.
36
+ */
37
+ const node_child_process_1 = require("node:child_process");
38
+ const node_fs_1 = __importDefault(require("node:fs"));
39
+ const node_os_1 = __importDefault(require("node:os"));
40
+ const node_path_1 = __importDefault(require("node:path"));
41
+ const runtime_1 = require("../../nerves/runtime");
42
+ /**
43
+ * What Slugger's turn writes; everything else in his projected bundle is read-only. The books CLI's download folder,
44
+ * removed folder and ledger are here, as in the Butler's profile, so a books case runs the same way for him.
45
+ */
46
+ exports.SLUGGER_WRITABLE = ["books/work", "books/removed", "books/ledger.ndjson", "state", "friends", "arc", "desk/_record"];
47
+ /** Folders created empty: the writable folders, and the desk's `_record` folders a fresh agent root has. */
48
+ const EMPTY = ["books/work", "books/removed", "state", "friends", "arc", "desk/_record/diary/daily", "desk/_record/notes"];
49
+ /** Top-level paths a case may include, and that are copied. */
50
+ const KEPT = ["psyche", "skills", "bundle-meta.json"];
51
+ /** Never copied, wherever they sit under a kept path. Every dot-folder or dot-file (`.git`, `.backup`, ...) is left out too. */
52
+ const LEFT_OUT = ["psyche/TACIT.md", "psyche/memory"];
53
+ /**
54
+ * Top-level `agent.json` keys kept as they are. `enabled` is kept because the harness refuses an `agent.json` without
55
+ * it; it says only whether the agent is switched on.
56
+ */
57
+ const AGENT_KEYS = ["version", "enabled", "humanFacing", "agentFacing", "context", "phrases"];
58
+ /** Where the household's leak patterns sit in his bundle. */
59
+ exports.LEAK_PATTERNS = "eval/leak-patterns.json";
60
+ const ARCHIVE_PREFIX = "eval-slugger-archive-";
61
+ /** Archive folders this module made and hasn't removed. */
62
+ const archives = new Set();
63
+ function run(command, args, stdin) {
64
+ // A reader's own output is never read, so it goes nowhere instead of filling a pipe.
65
+ const child = (0, node_child_process_1.spawn)(command, args, { stdio: [stdin ? "pipe" : "ignore", stdin ? "ignore" : "pipe", "pipe"] });
66
+ if (stdin) {
67
+ // A reader that stops early closes the writer's output too, so the writer ends on a broken pipe instead of waiting.
68
+ const stop = () => { stdin.destroy(); };
69
+ child.stdin.on("error", stop);
70
+ child.on("close", stop);
71
+ stdin.pipe(child.stdin);
72
+ }
73
+ let stderr = "";
74
+ child.stderr.setEncoding("utf8");
75
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
76
+ const done = new Promise((resolve, reject) => {
77
+ child.on("error", reject);
78
+ child.on("close", (code) => (code === 0 ? resolve(stderr) : reject(new Error(`${[command, ...args].join(" ")} exited ${code}: ${stderr.trim()}`))));
79
+ });
80
+ return { stdout: child.stdout, done };
81
+ }
82
+ async function output(command, args) {
83
+ const { stdout, done } = run(command, args);
84
+ let text = "";
85
+ stdout.setEncoding("utf8");
86
+ stdout.on("data", (chunk) => { text += chunk; });
87
+ await done;
88
+ return text.trim();
89
+ }
90
+ /** `git archive` of `commit` in the bundle repository `repo`, unpacked into a new folder under `workRoot`. */
91
+ async function archiveBundle(input) {
92
+ const commit = await output("git", ["-C", input.repo, "rev-parse", "--verify", "--end-of-options", `${input.commit}^{commit}`]);
93
+ const dir = node_fs_1.default.mkdtempSync(node_path_1.default.join(input.workRoot ?? node_os_1.default.tmpdir(), ARCHIVE_PREFIX));
94
+ archives.add(dir);
95
+ try {
96
+ const archive = run("git", ["-C", input.repo, "archive", "--format=tar", commit]);
97
+ const unpack = run(input.tar ?? "tar", ["-x", "-f", "-", "-C", dir], archive.stdout);
98
+ // Both must have ended before the folder can be removed, whichever failed first.
99
+ const ended = await Promise.allSettled([archive.done, unpack.done]);
100
+ for (const each of ended)
101
+ if (each.status === "rejected")
102
+ throw each.reason;
103
+ // Every top-level entry of the commit must have arrived, so a reader that stops early can't pass for a smaller bundle.
104
+ const names = (await output("git", ["-C", input.repo, "ls-tree", "-z", "--name-only", commit])).split("\0").filter(Boolean);
105
+ const missing = names.filter((name) => !node_fs_1.default.lstatSync(node_path_1.default.join(dir, name), { throwIfNoEntry: false }));
106
+ if (missing.length > 0)
107
+ throw new Error(`the archive of ${commit} is missing ${missing.length} of its top-level entries`);
108
+ }
109
+ catch (error) {
110
+ removeArchive(dir);
111
+ throw error;
112
+ }
113
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.slugger_archive", message: "archived a bundle commit for a projection", meta: { commit } });
114
+ return { dir, commit };
115
+ }
116
+ /** Deletes an archive folder this module made, by its exact path, and reads back that it is gone. */
117
+ function removeArchive(dir) {
118
+ if (!archives.has(dir))
119
+ throw new Error(`${dir} is no archive this run made`);
120
+ node_fs_1.default.rmSync(dir, { recursive: true, force: true });
121
+ if (node_fs_1.default.existsSync(dir))
122
+ throw new Error(`${dir} is still there after its removal`);
123
+ archives.delete(dir);
124
+ }
125
+ function refuse(why) {
126
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "error", event: "eval.slugger_projection_refused", message: "refused a Slugger projection", meta: { why } });
127
+ throw new Error(`Slugger projection: ${why}`);
128
+ }
129
+ const leftOut = (relative) => {
130
+ const lower = relative.toLowerCase();
131
+ return lower.split("/").some((part) => part.startsWith(".")) || LEFT_OUT.some((p) => lower === p.toLowerCase() || lower.startsWith(`${p.toLowerCase()}/`));
132
+ };
133
+ function copyTree(from, to, relative, gaps) {
134
+ const source = node_path_1.default.join(from, relative);
135
+ const stat = node_fs_1.default.lstatSync(source);
136
+ if (stat.isSymbolicLink()) {
137
+ gaps.push(`${relative}: a symbolic link, left out`);
138
+ }
139
+ else if (stat.isDirectory()) {
140
+ node_fs_1.default.mkdirSync(node_path_1.default.join(to, relative), { recursive: true });
141
+ for (const name of node_fs_1.default.readdirSync(source).sort()) {
142
+ const child = node_path_1.default.posix.join(relative, name);
143
+ if (!leftOut(child))
144
+ copyTree(from, to, child, gaps);
145
+ }
146
+ }
147
+ else {
148
+ // A git archive holds only files, folders and links.
149
+ node_fs_1.default.copyFileSync(source, node_path_1.default.join(to, relative));
150
+ node_fs_1.default.chmodSync(node_path_1.default.join(to, relative), stat.mode & 0o755);
151
+ }
152
+ }
153
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
154
+ /** The allowlisted `agent.json`, and the names of the keys and servers it left out. */
155
+ function projectAgentConfig(config, fakes) {
156
+ if (!isRecord(config))
157
+ refuse("agent.json is not an object");
158
+ const kept = {};
159
+ const dropped = [];
160
+ for (const key of Object.keys(config).sort()) {
161
+ if (AGENT_KEYS.includes(key))
162
+ kept[key] = config[key];
163
+ else if (key !== "senses" && key !== "mcpServers")
164
+ dropped.push(key);
165
+ }
166
+ if (isRecord(config.senses)) {
167
+ const senses = {};
168
+ for (const [name, sense] of Object.entries(config.senses).sort(([a], [b]) => (a < b ? -1 : 1))) {
169
+ senses[name] = { enabled: isRecord(sense) && sense.enabled === true };
170
+ if (isRecord(sense))
171
+ for (const field of Object.keys(sense).filter((f) => f !== "enabled").sort())
172
+ dropped.push(`senses.${name}.${field}`);
173
+ }
174
+ kept.senses = senses;
175
+ }
176
+ if (isRecord(config.mcpServers)) {
177
+ const servers = {};
178
+ for (const name of Object.keys(config.mcpServers).sort()) {
179
+ const fake = fakes[name];
180
+ if (fake)
181
+ servers[name] = { command: fake.command, ...(fake.args ? { args: [...fake.args] } : {}), ...(fake.tools ? { tools: fake.tools } : {}) };
182
+ else
183
+ dropped.push(`mcpServers.${name}`);
184
+ }
185
+ kept.mcpServers = servers;
186
+ }
187
+ return { config: kept, dropped };
188
+ }
189
+ /** Reads the household's leak patterns from the archive: literals of three or more characters, matched in any case. */
190
+ function readLeakPatterns(archiveDir) {
191
+ const file = node_path_1.default.join(archiveDir, exports.LEAK_PATTERNS);
192
+ if (!node_fs_1.default.existsSync(file))
193
+ refuse(`the bundle has no ${exports.LEAK_PATTERNS}, so its projection can't be checked for leaks`);
194
+ let value;
195
+ try {
196
+ value = JSON.parse(node_fs_1.default.readFileSync(file, "utf8"));
197
+ }
198
+ catch {
199
+ refuse(`${exports.LEAK_PATTERNS} is not JSON`);
200
+ }
201
+ const literals = isRecord(value) ? value.literals : undefined;
202
+ if (!Array.isArray(literals) || literals.length === 0 || !literals.every((l) => typeof l === "string" && l.trim().length >= 3)) {
203
+ refuse(`${exports.LEAK_PATTERNS} needs a non-empty "literals" list of strings of three or more characters`);
204
+ }
205
+ return literals.map((literal) => literal.trim().toLowerCase());
206
+ }
207
+ /** Every file or folder under `root` whose path, or a file's contents, holds a pattern, by its path relative to `root`. */
208
+ function leakLint(root, patterns) {
209
+ const flagged = [];
210
+ const holds = (text) => patterns.some((pattern) => text.toLowerCase().includes(pattern));
211
+ const walk = (relative) => {
212
+ const full = node_path_1.default.join(root, relative);
213
+ if (node_fs_1.default.lstatSync(full).isDirectory()) {
214
+ if (relative && holds(relative))
215
+ flagged.push(`${relative}/`);
216
+ for (const name of node_fs_1.default.readdirSync(full).sort())
217
+ walk(relative ? node_path_1.default.posix.join(relative, name) : name);
218
+ }
219
+ else if (holds(`${relative}\n${node_fs_1.default.readFileSync(full, "utf8")}`)) {
220
+ flagged.push(relative);
221
+ }
222
+ };
223
+ walk("");
224
+ return flagged;
225
+ }
226
+ function projectSlugger(input) {
227
+ if (!archives.has(input.archive))
228
+ refuse(`${input.archive} is no git archive this run made`);
229
+ for (const include of input.include) {
230
+ const top = include.split("/")[0];
231
+ if (include !== "agent.json" && (!KEPT.includes(top) || node_path_1.default.posix.normalize(include) !== include || include.split("/").includes("..") || leftOut(include))) {
232
+ refuse(`a case may include agent.json, ${KEPT.join(", ")} or paths inside them, not ${JSON.stringify(include)}`);
233
+ }
234
+ }
235
+ if (node_fs_1.default.existsSync(input.out))
236
+ refuse(`the projection folder ${input.out} already exists`);
237
+ const patterns = readLeakPatterns(input.archive);
238
+ node_fs_1.default.mkdirSync(input.out, { recursive: true, mode: 0o755 });
239
+ const gaps = [];
240
+ try {
241
+ for (const include of input.include.filter((each) => each !== "agent.json")) {
242
+ const parts = include.split("/");
243
+ const linked = parts.slice(0, -1).some((_part, i) => node_fs_1.default.lstatSync(node_path_1.default.join(input.archive, ...parts.slice(0, i + 1)), { throwIfNoEntry: false })?.isSymbolicLink());
244
+ if (linked)
245
+ gaps.push(`${include}: under a symbolic link, left out`);
246
+ else if (!node_fs_1.default.existsSync(node_path_1.default.join(input.archive, include)))
247
+ gaps.push(`${include}: not in the bundle`);
248
+ else
249
+ copyTree(input.archive, input.out, include, gaps);
250
+ }
251
+ if (input.include.includes("agent.json")) {
252
+ let config;
253
+ try {
254
+ config = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(input.archive, "agent.json"), "utf8"));
255
+ }
256
+ catch {
257
+ refuse("agent.json is missing or not JSON");
258
+ }
259
+ const projected = projectAgentConfig(config, input.fakes);
260
+ node_fs_1.default.writeFileSync(node_path_1.default.join(input.out, "agent.json"), `${JSON.stringify(projected.config, null, 2)}\n`);
261
+ if (projected.dropped.length > 0)
262
+ gaps.push(`agent.json: left out ${projected.dropped.join(", ")}`);
263
+ for (const name of Object.keys(projected.config.mcpServers ?? {}))
264
+ gaps.push(`${name}: a fake MCP server with synthetic data stands in for the real one`);
265
+ }
266
+ for (const dir of EMPTY)
267
+ node_fs_1.default.mkdirSync(node_path_1.default.join(input.out, dir), { recursive: true });
268
+ node_fs_1.default.writeFileSync(node_path_1.default.join(input.out, "books/ledger.ndjson"), "");
269
+ gaps.push("psyche/TACIT.md and psyche/memory: left out", "friends, state, arc, desk and books: start empty", "browser: left out");
270
+ // Gaps go into every report, so they are checked like the files are.
271
+ const flagged = leakLint(input.out, patterns).length + gaps.filter((gap) => patterns.some((pattern) => gap.toLowerCase().includes(pattern))).length;
272
+ if (flagged > 0)
273
+ refuse(`${flagged} projected path(s) or gap(s) hold a leak pattern; nothing was run`);
274
+ }
275
+ catch (error) {
276
+ node_fs_1.default.rmSync(input.out, { recursive: true, force: true });
277
+ throw error;
278
+ }
279
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.slugger_projection", message: "projected Slugger's bundle", meta: { gaps: gaps.length } });
280
+ return { gaps };
281
+ }
282
+ /** Slugger's profile for a run on an archive `archiveBundle` made; the caller removes the archive afterwards. */
283
+ function sluggerProfile(input) {
284
+ return {
285
+ agent: "slugger",
286
+ bundleSource: ({ include, out }) => projectSlugger({ archive: input.archive, include, out, fakes: input.fakes }),
287
+ writable: exports.SLUGGER_WRITABLE,
288
+ };
289
+ }
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.pruneProvenMailroomCopies = pruneProvenMailroomCopies;
37
+ const crypto_1 = require("crypto");
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const zlib = __importStar(require("zlib"));
41
+ const runtime_1 = require("../../nerves/runtime");
42
+ const core_1 = require("../../mailroom/core");
43
+ const DEFAULT_MAX_PER_PASS = 5000;
44
+ function emptyResult() {
45
+ return { checked: 0, deleted: 0, bytesFreed: 0, notInBlob: 0, mismatched: 0, unconfirmed: 0, localInvalid: 0, changed: 0, deferred: 0 };
46
+ }
47
+ function text(value) {
48
+ return typeof value === "string" && value.length > 0 ? value : null;
49
+ }
50
+ /** Reads a gzipped local copy and checks its raw file matches its own record; null when it doesn't. */
51
+ function readLocalCopy(root, messagePath) {
52
+ try {
53
+ const messageStat = fs.statSync(messagePath);
54
+ const record = JSON.parse(zlib.gunzipSync(fs.readFileSync(messagePath)).toString("utf-8"));
55
+ const id = text(record.id);
56
+ const rawObject = text(record.rawObject);
57
+ const rawSha256 = text(record.rawSha256);
58
+ if (!id || !rawObject || !rawSha256 || typeof record.rawSize !== "number")
59
+ return null;
60
+ const rawPath = path.resolve(root, `${rawObject}.gz`);
61
+ if (!rawPath.startsWith(path.join(path.resolve(root), "raw") + path.sep))
62
+ return null;
63
+ const rawStat = fs.statSync(rawPath);
64
+ const raw = zlib.gunzipSync(fs.readFileSync(rawPath));
65
+ if (raw.byteLength !== record.rawSize || (0, crypto_1.createHash)("sha256").update(raw).digest("hex") !== rawSha256)
66
+ return null;
67
+ const keys = [id];
68
+ const agentId = text(record.agentId);
69
+ const mailboxId = text(record.mailboxId);
70
+ const address = text(record.recipient);
71
+ if (agentId && mailboxId && address && record.envelope && typeof record.envelope === "object") {
72
+ keys.unshift((0, core_1.hostedMessageStorageId)(record.envelope, raw, { agentId, mailboxId, address }));
73
+ }
74
+ return { messagePath, rawPath, keys: [...new Set(keys)], rawSha256, rawSize: raw.byteLength, messageStat, rawStat };
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
80
+ async function verdictFor(copy, hosted) {
81
+ let mismatched = false;
82
+ for (const key of copy.keys) {
83
+ const record = await hosted.readMessage(key);
84
+ if (!record)
85
+ continue;
86
+ if (record.rawSha256 !== copy.rawSha256 || record.rawSize !== copy.rawSize) {
87
+ mismatched = true;
88
+ continue;
89
+ }
90
+ const rawObject = text(record.rawObject);
91
+ const size = rawObject ? await hosted.rawObjectSize(rawObject) : null;
92
+ if (size !== null && size > 0)
93
+ return "proven";
94
+ }
95
+ return mismatched ? "mismatched" : "not-in-blob";
96
+ }
97
+ function unchanged(before, file) {
98
+ try {
99
+ const after = fs.statSync(file);
100
+ return after.size === before.size && after.mtimeMs === before.mtimeMs;
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ async function pruneProvenMailroomCopies(input) {
107
+ const result = emptyResult();
108
+ const messagesDir = path.join(input.mailroomRoot, "messages");
109
+ let names;
110
+ try {
111
+ names = fs.readdirSync(messagesDir).filter((name) => name.endsWith(".json.gz")).sort();
112
+ }
113
+ catch {
114
+ return result;
115
+ }
116
+ const limit = input.maxPerPass ?? DEFAULT_MAX_PER_PASS;
117
+ result.deferred = Math.max(0, names.length - limit);
118
+ for (const name of names.slice(0, limit)) {
119
+ result.checked += 1;
120
+ const copy = readLocalCopy(input.mailroomRoot, path.join(messagesDir, name));
121
+ if (!copy) {
122
+ result.localInvalid += 1;
123
+ continue;
124
+ }
125
+ let verdict;
126
+ try {
127
+ verdict = await verdictFor(copy, input.hosted);
128
+ }
129
+ catch {
130
+ result.unconfirmed += 1;
131
+ continue;
132
+ }
133
+ if (verdict === "not-in-blob") {
134
+ result.notInBlob += 1;
135
+ continue;
136
+ }
137
+ if (verdict === "mismatched") {
138
+ result.mismatched += 1;
139
+ continue;
140
+ }
141
+ if (!unchanged(copy.rawStat, copy.rawPath) || !unchanged(copy.messageStat, copy.messagePath)) {
142
+ result.changed += 1;
143
+ continue;
144
+ }
145
+ // The raw file first: a message record without its raw file is caught as localInvalid next pass and kept.
146
+ fs.unlinkSync(copy.rawPath);
147
+ fs.unlinkSync(copy.messagePath);
148
+ result.deleted += 1;
149
+ result.bytesFreed += copy.rawStat.size + copy.messageStat.size;
150
+ }
151
+ (0, runtime_1.emitNervesEvent)({
152
+ component: "daemon",
153
+ event: "daemon.state_retention_mailroom_proven_copies",
154
+ message: "deleted gzipped local mail copies that Blob is proven to hold",
155
+ meta: { ...(input.agent ? { agent: input.agent } : {}), ...result },
156
+ });
157
+ return result;
158
+ }
@@ -179,6 +179,10 @@ function mailroomStoreFromRuntimeConfig(runtime) {
179
179
  const account = mailroom && typeof mailroom === "object" ? mailroom.azureAccountUrl : undefined;
180
180
  return typeof account === "string" && account.trim().length > 0 ? "hosted" : "local";
181
181
  }
182
+ // Loaded only for an agent whose mail is hosted, so the daemon's startup doesn't load the mail store.
183
+ async function defaultHostedMailCopies(agent) {
184
+ return (await Promise.resolve().then(() => __importStar(require("../../mailroom/reader")))).openHostedMailCopies(agent);
185
+ }
182
186
  /** Runs retention for each agent in turn; one agent's failure doesn't stop the rest. Telemetry is counts only. */
183
187
  async function runAgentStateRetention(input) {
184
188
  const compactSessions = input.compactSessions ?? compactLegacySessionArchives;
@@ -205,7 +209,15 @@ async function runAgentStateRetention(input) {
205
209
  message: "gzipped the local mail file store once the agent's mail is hosted",
206
210
  meta: { agent, ...mailroom },
207
211
  });
208
- results.push({ agent, sessionArchives, mailroom });
212
+ const hosted = store === "hosted" ? await (input.hostedMailCopies ?? defaultHostedMailCopies)(agent) : null;
213
+ const mailroomCopies = hosted
214
+ ? await (await Promise.resolve().then(() => __importStar(require("./mailroom-copy-proof")))).pruneProvenMailroomCopies({
215
+ mailroomRoot: path.join(input.bundlesRoot, `${agent}.ouro`, "state", "mailroom"),
216
+ hosted,
217
+ agent,
218
+ })
219
+ : null;
220
+ results.push({ agent, sessionArchives, mailroom, mailroomCopies });
209
221
  }
210
222
  catch (error) {
211
223
  (0, runtime_1.emitNervesEvent)({
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AzureBlobMailroomStore = void 0;
4
4
  exports.canonicalMailIndexRecordSnapshot = canonicalMailIndexRecordSnapshot;
5
5
  exports.decryptBlobMessages = decryptBlobMessages;
6
+ exports.blobHostedMailCopies = blobHostedMailCopies;
6
7
  const node_crypto_1 = require("node:crypto");
7
8
  const runtime_1 = require("../nerves/runtime");
8
9
  const core_1 = require("./core");
@@ -972,3 +973,19 @@ exports.AzureBlobMailroomStore = AzureBlobMailroomStore;
972
973
  function decryptBlobMessages(messages, privateKeys) {
973
974
  return messages.map((message) => (0, core_1.readDecryptedMailMessage)(message, privateKeys));
974
975
  }
976
+ function blobHostedMailCopies(container, timeoutMs = DEFAULT_BLOB_OPERATION_TIMEOUT_MS) {
977
+ return {
978
+ readMessage: (id) => downloadJson(container.getBlockBlobClient(`messages/${id}.json`), timeoutMs),
979
+ rawObjectSize: async (name) => {
980
+ try {
981
+ const properties = await withBlobOperationTimeout(timeoutMs, (abortSignal) => container.getBlockBlobClient(name).getProperties({ abortSignal }));
982
+ return typeof properties.contentLength === "number" ? properties.contentLength : null;
983
+ }
984
+ catch (error) {
985
+ if (isBlobNotFoundError(error))
986
+ return null;
987
+ throw error;
988
+ }
989
+ },
990
+ };
991
+ }
@@ -47,6 +47,7 @@ exports.encryptJsonForMailKey = encryptJsonForMailKey;
47
47
  exports.decryptMailJson = decryptMailJson;
48
48
  exports.resolveMailAddress = resolveMailAddress;
49
49
  exports.describeMailProvenance = describeMailProvenance;
50
+ exports.hostedMessageStorageId = hostedMessageStorageId;
50
51
  exports.htmlMailBodyToText = htmlMailBodyToText;
51
52
  exports.privateMailEnvelopeReadableText = privateMailEnvelopeReadableText;
52
53
  exports.buildStoredMailMessageMetadata = buildStoredMailMessageMetadata;
@@ -394,6 +395,13 @@ function messageStorageId(envelope, raw, destination) {
394
395
  const value = digest.digest("hex");
395
396
  return `mail_${value.slice(0, 32)}`;
396
397
  }
398
+ /**
399
+ * The id the hosted (Blob) store gives a message: the local file store's id plus its destination. Retention uses it to
400
+ * find a local copy's hosted counterpart before deleting the local copy.
401
+ */
402
+ function hostedMessageStorageId(envelope, raw, destination) {
403
+ return messageStorageId(envelope, raw, destination);
404
+ }
397
405
  function candidateSender(input) {
398
406
  const parsed = input.parsedFrom[0];
399
407
  if (parsed)
@@ -37,6 +37,7 @@ exports.parseMailroomConfig = parseMailroomConfig;
37
37
  exports.readMailroomRegistry = readMailroomRegistry;
38
38
  exports.writeMailroomRegistry = writeMailroomRegistry;
39
39
  exports.resolveMailroomReader = resolveMailroomReader;
40
+ exports.openHostedMailCopies = openHostedMailCopies;
40
41
  exports.resolveHostedMailAuthority = resolveHostedMailAuthority;
41
42
  exports.resolveMailroomReaderWithRefresh = resolveMailroomReaderWithRefresh;
42
43
  const fs = __importStar(require("node:fs"));
@@ -223,6 +224,22 @@ function resolveMailroomReader(agentName = (0, identity_1.getAgentName)()) {
223
224
  });
224
225
  return result;
225
226
  }
227
+ /**
228
+ * Read-only lookups in the agent's hosted mail container, for retention to prove a local copy was uploaded before it
229
+ * deletes it. Null when the agent's mail isn't hosted or its runtime config can't be read.
230
+ */
231
+ function openHostedMailCopies(agentName) {
232
+ const runtime = (0, runtime_credentials_1.readRuntimeCredentialConfig)(agentName);
233
+ if (!runtime.ok)
234
+ return null;
235
+ const mailroom = isRecord(runtime.config.mailroom) ? runtime.config.mailroom : null;
236
+ const azureAccountUrl = mailroom ? textField(mailroom, "azureAccountUrl") : undefined;
237
+ if (!mailroom || !azureAccountUrl)
238
+ return null;
239
+ const container = createBlobServiceClient(azureAccountUrl, textField(mailroom, "azureManagedIdentityClientId"))
240
+ .getContainerClient(textField(mailroom, "azureContainer") ?? "mailroom");
241
+ return (0, blob_store_1.blobHostedMailCopies)(container);
242
+ }
226
243
  function resolveHostedMailAuthority(agentName = (0, identity_1.getAgentName)()) {
227
244
  const runtime = (0, runtime_credentials_1.readRuntimeCredentialConfig)(agentName);
228
245
  if (!runtime.ok) {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1500",
3
+ "version": "0.1.0-alpha.1502",
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.1500",
9
+ "version": "0.1.0-alpha.1502",
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.1500",
3
+ "version": "0.1.0-alpha.1502",
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": {