@ouro.bot/cli 0.1.0-alpha.1685 → 0.1.0-alpha.1686

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,12 @@
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.1686",
6
+ "changes": [
7
+ "The one-time session repair from September (A003), already applied and no longer usable since the Butler's rename, is removed: its private `node dist/heart/session-redaction-repair-cli-main.js` entry point no longer ships."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1685",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1685",
2
+ "runtimeVersion": "0.1.0-alpha.1686",
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.1685</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1686</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -10,7 +10,6 @@ function missingAgent(path) {
10
10
  };
11
11
  }
12
12
  const ROOT_LIFECYCLE = "node dist/heart/daemon/sanctuary-authority-root-lifecycle.js";
13
- const REDACTION = "node dist/heart/session-redaction-repair-cli-main.js";
14
13
  const PROBE = "node dist/senses/sanctuary-health-acceptance-probe-entry.js";
15
14
  const AX_FLOWS = "node dist/ouro-ax/flows.js";
16
15
  const AX_SURFACES = "node dist/ouro-ax/surfaces.js";
@@ -39,29 +38,6 @@ function rootUsage(step, words) {
39
38
  fix: `Run ${step} with exactly ${words}.`,
40
39
  };
41
40
  }
42
- /** A redaction repair step that started but didn't finish. */
43
- function repairUnfinished(step) {
44
- return [
45
- {
46
- code: "not-applied",
47
- means: `${REDACTION} ${step} stopped before it changed the session; the file is as it was.`,
48
- fix: `Its write didn't land and the session is unchanged; run ${step} again with the same manifest.`,
49
- },
50
- {
51
- code: "indeterminate",
52
- means: `${REDACTION} ${step} found the session at neither its preimage nor its postimage (it changed underneath), or reading the session back after the write threw.`,
53
- fix: "Stop, and compare the session with the manifest and preimage by hand before any other step.",
54
- },
55
- ];
56
- }
57
- /** A redaction repair step the repair itself refused, such as a manifest digest that doesn't match. */
58
- function repairRefused(step) {
59
- return {
60
- code: "repair-refused",
61
- means: `${REDACTION} ${step} refused: the session, manifest or digest didn't pass its checks, and nothing changed.`,
62
- fix: "Read the JSON error, then rerun inspect for a fresh manifest and use its exact digest.",
63
- };
64
- }
65
41
  /** A probe step given the wrong coordinates. */
66
42
  function probeUsage(step) {
67
43
  return {
@@ -123,21 +99,6 @@ exports.ENTRY_POINT_COMMANDS = [
123
99
  { name: "node dist/heart/session-playback-cli-main.js", effect: "private", readOnly: true, summary: "Show what replaying a session would change.", ax: { id: "cli:node dist/heart/session-playback-cli-main.js", group: "diagnostics", effect: "read", when: "When an agent loops on replay: see what the sanitizer would drop or insert in a saved session file, writing nothing.", errors: [
124
100
  { code: "usage", means: "Session playback needs the path of a saved session.json.", fix: "Pass the session file, adding --json for the report as data." },
125
101
  ] } },
126
- { name: REDACTION, effect: "private", summary: "Repair a session's redaction with a fixed recipe.", ax: { id: `cli:${REDACTION}`, group: "diagnostics", effect: "write", when: "Only for the one known redaction defect: inspect a session, then apply or roll back with the manifest inspect wrote.", errors: [
127
- { code: "usage", means: `${REDACTION} takes only its three fixed shapes: inspect, apply or rollback with their exact flags.`, fix: "Start with inspect --agent <name> --session <path> --artifacts-dir <dir>." },
128
- ] } },
129
- { name: `${REDACTION} inspect`, effect: "private", summary: "Plan a session's redaction repair.", ax: { id: `cli:${REDACTION} inspect`, group: "diagnostics", effect: "write", when: "First step of the repair: write a manifest and preimage for one session into --artifacts-dir, leaving the session alone.", errors: [
130
- { code: "usage", means: `${REDACTION} inspect needs --agent, --session and --artifacts-dir, in that order.`, fix: "Pass all three with their values and nothing else." },
131
- repairRefused("inspect"),
132
- ] } },
133
- { name: `${REDACTION} apply`, effect: "private", summary: "Apply a planned redaction repair.", ax: { id: `cli:${REDACTION} apply`, group: "diagnostics", effect: "consequential", confirm: "The session file is rewritten from the manifest; rollback with the preimage undoes it.", when: "After inspect: rewrite the session from the manifest, given its exact --manifest-sha256.", errors: [
134
- { code: "usage", means: `${REDACTION} apply needs --manifest-sha256 <digest> and the manifest path, and nothing else.`, fix: "Pass the digest and manifest path inspect printed." },
135
- repairRefused("apply"), ...repairUnfinished("apply"),
136
- ] } },
137
- { name: `${REDACTION} rollback`, effect: "private", summary: "Undo an applied redaction repair.", ax: { id: `cli:${REDACTION} rollback`, group: "diagnostics", effect: "consequential", confirm: "The session file goes back to the preimage inspect saved.", when: "If an applied repair looks wrong: put the session back from the preimage, with the manifest's digest.", errors: [
138
- { code: "usage", means: `${REDACTION} rollback needs --manifest-sha256 <digest>, the manifest path and the preimage path, and nothing else.`, fix: "Pass the digest and both paths inspect printed." },
139
- repairRefused("rollback"), ...repairUnfinished("rollback"),
140
- ] } },
141
102
  { name: "node dist/heart/session-stats-cli-main.js", effect: "private", readOnly: true, summary: "Summarize a saved session.", ax: { id: "cli:node dist/heart/session-stats-cli-main.js", group: "diagnostics", effect: "read", when: "Size up a saved session file: message counts, token use and the last usage record, before deciding to trim it.", errors: [
142
103
  { code: "usage", means: "Session stats needs the path of a saved session.json.", fix: "Pass the session file, adding --json for the numbers as data." },
143
104
  ] } },
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1685",
3
+ "version": "0.1.0-alpha.1686",
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.1685",
9
+ "version": "0.1.0-alpha.1686",
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.1685",
3
+ "version": "0.1.0-alpha.1686",
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": {
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const runtime_1 = require("../nerves/runtime");
4
- const session_redaction_repair_1 = require("./session-redaction-repair");
5
- // Deliberately a direct packaged entrypoint, never public CLI/model routing.
6
- async function main() {
7
- const args = process.argv.slice(2);
8
- (0, runtime_1.emitNervesEvent)({ component: "heart", event: "heart.session_redaction_repair_cli", message: "private fixed repair entrypoint invoked", meta: { argumentCount: args.length } });
9
- try {
10
- let result;
11
- if (args.length === 7 && args[0] === "inspect" && args[1] === "--agent" && args[3] === "--session" && args[5] === "--artifacts-dir") {
12
- result = await (0, session_redaction_repair_1.inspectA003SessionRepair)({ agent: args[2], sessionPath: args[4], artifactsDir: args[6] });
13
- }
14
- else if (args.length === 4 && args[0] === "apply" && args[1] === "--manifest-sha256") {
15
- result = await (0, session_redaction_repair_1.applyA003SessionRepair)({ manifestSha256: args[2], manifestPath: args[3] });
16
- }
17
- else if (args.length === 5 && args[0] === "rollback" && args[1] === "--manifest-sha256") {
18
- result = await (0, session_redaction_repair_1.rollbackA003SessionRepair)({ manifestSha256: args[2], manifestPath: args[3], preimagePath: args[4] });
19
- }
20
- else {
21
- throw Object.assign(new Error("expected fixed inspect, apply, or rollback arguments"), { code: "usage" });
22
- }
23
- // A step that didn't finish says so in its code: not-applied left the session as it was, indeterminate can't tell.
24
- const unfinished = result.status === "indeterminate" ? "indeterminate" : result.status === "not_applied" ? "not-applied" : undefined;
25
- process.stdout.write(`${JSON.stringify(unfinished ? { ...result, code: unfinished } : result)}\n`);
26
- process.exitCode = unfinished ? 1 : 0;
27
- }
28
- catch (error) {
29
- const code = error?.code === "usage" ? "usage" : "repair-refused";
30
- process.stdout.write(`${JSON.stringify({ status: "refused", code, error: (error instanceof Error ? error.message : String(error)).slice(0, 512) })}\n`);
31
- process.exitCode = 2;
32
- }
33
- }
34
- void main();
@@ -1,552 +0,0 @@
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.selectA003LegacyRequiredCorrections = selectA003LegacyRequiredCorrections;
37
- exports.inspectA003SessionRepair = inspectA003SessionRepair;
38
- exports.applyA003SessionRepair = applyA003SessionRepair;
39
- exports.rollbackA003SessionRepair = rollbackA003SessionRepair;
40
- const fs = __importStar(require("node:fs"));
41
- const path = __importStar(require("node:path"));
42
- const node_crypto_1 = require("node:crypto");
43
- const node_util_1 = require("node:util");
44
- const identity_1 = require("./identity");
45
- const runtime_1 = require("../nerves/runtime");
46
- const tool_arguments_1 = require("../repertoire/tool-arguments");
47
- const session_events_1 = require("./session-events");
48
- const structured_output_1 = require("./structured-output");
49
- const session_transaction_1 = require("../mind/session-transaction");
50
- const SCHEMA = "a003-sanctuary-session-repair-v1";
51
- const SELECTOR = "a003-legacy-required-corrections-v1";
52
- const TARGET_BINDINGS = [
53
- { id: "evt-000347", sequence: 347 },
54
- { id: "evt-000355", sequence: 355 },
55
- { id: "evt-000363", sequence: 363 },
56
- { id: "evt-000366", sequence: 366 },
57
- { id: "evt-000369", sequence: 369 },
58
- { id: "evt-000400", sequence: 400 },
59
- { id: "evt-000447", sequence: 447 },
60
- { id: "evt-000448", sequence: 448 },
61
- ];
62
- const SESSION_LIMIT = 32 * 1024 * 1024;
63
- const MANIFEST_LIMIT = 1024 * 1024;
64
- const HASH = /^[a-f0-9]{64}$/u;
65
- function sha(bytes) {
66
- return (0, node_crypto_1.createHash)("sha256").update(bytes).digest("hex");
67
- }
68
- function refuse(reason) {
69
- (0, runtime_1.emitNervesEvent)({
70
- level: "warn", component: "heart", event: "heart.session_redaction_repair_refused",
71
- message: "fixed session repair refused", meta: { reason },
72
- });
73
- throw new Error(reason);
74
- }
75
- function exactKeys(value, keys) {
76
- return value !== null && typeof value === "object" && !Array.isArray(value)
77
- && Object.keys(value).length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
78
- }
79
- function iso(value) {
80
- return typeof value === "string" && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
81
- }
82
- function sameInode(a, b) {
83
- return a.dev === b.dev && a.ino === b.ino;
84
- }
85
- function directoryChain(directory) {
86
- if (!path.isAbsolute(directory) || path.resolve(directory) !== directory)
87
- refuse("noncanonical directory path");
88
- let current = path.parse(directory).root;
89
- const parts = [current];
90
- for (const part of directory.slice(current.length).split(path.sep).filter(Boolean)) {
91
- current = path.join(current, part);
92
- parts.push(current);
93
- }
94
- return parts.map((file) => {
95
- const stat = fs.lstatSync(file, { bigint: true });
96
- if (!stat.isDirectory() || stat.isSymbolicLink())
97
- refuse("directory symlink or type mismatch");
98
- return { path: file, dev: stat.dev, ino: stat.ino };
99
- });
100
- }
101
- function checkDirectories(pin) {
102
- for (const entry of pin) {
103
- const stat = fs.lstatSync(entry.path, { bigint: true });
104
- if (!stat.isDirectory() || stat.isSymbolicLink() || !sameInode(entry, stat))
105
- refuse("directory identity changed");
106
- }
107
- }
108
- function privateDirectory(directory) {
109
- const pin = directoryChain(directory);
110
- if ((fs.lstatSync(directory, { bigint: true }).mode & 511n) !== 448n)
111
- refuse("artifact directory must have mode 0700");
112
- return pin;
113
- }
114
- function privateFile(file, label, limit) {
115
- if (!path.isAbsolute(file) || path.resolve(file) !== file)
116
- refuse("noncanonical file path");
117
- directoryChain(path.dirname(file));
118
- const stat = fs.lstatSync(file, { bigint: true });
119
- if (!stat.isFile() || stat.isSymbolicLink())
120
- refuse(`${label} must be a regular file`);
121
- if ((stat.mode & 511n) !== 384n)
122
- refuse(`${label} must have mode 0600`);
123
- if (stat.size > BigInt(limit))
124
- refuse(`${label} exceeds ${limit / (1024 * 1024)} MiB`);
125
- return stat;
126
- }
127
- function readArtifact(file, label, limit) {
128
- const pin = privateDirectory(path.dirname(file));
129
- const original = privateFile(file, label, limit);
130
- const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
131
- try {
132
- const opened = fs.fstatSync(fd, { bigint: true });
133
- if (!opened.isFile() || !sameInode(original, opened) || (opened.mode & 511n) !== 384n || opened.size > BigInt(limit))
134
- refuse("artifact identity changed");
135
- const bytes = fs.readFileSync(fd);
136
- checkDirectories(pin);
137
- if (bytes.length > limit || !sameInode(opened, fs.lstatSync(file, { bigint: true })))
138
- refuse("artifact changed during read");
139
- return bytes;
140
- }
141
- finally {
142
- fs.closeSync(fd);
143
- }
144
- }
145
- function sessionLocation(agent, sessionPath) {
146
- if (agent !== "sanctuary")
147
- refuse("repair agent must be sanctuary");
148
- const root = path.join((0, identity_1.getAgentRoot)("sanctuary"), "state", "sessions");
149
- directoryChain(root);
150
- const relative = path.relative(root, sessionPath);
151
- if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
152
- refuse("session path escapes sanctuary");
153
- privateFile(sessionPath, "session", SESSION_LIMIT);
154
- return { root, relative: relative.split(path.sep).join("/") };
155
- }
156
- function manifestSessionPath(relative) {
157
- if (!relative || relative.includes("\\") || relative.split("/").some((part) => !part || part === "." || part === ".."))
158
- refuse("invalid session relative path");
159
- const file = path.join((0, identity_1.getAgentRoot)("sanctuary"), "state", "sessions", relative);
160
- sessionLocation("sanctuary", file);
161
- return file;
162
- }
163
- function marker(target, sequence, capturedAt) {
164
- return {
165
- id: `evt-${String(sequence).padStart(6, "0")}`, sequence, role: "system", content: null,
166
- name: null, toolCallId: null, toolCalls: [], attachments: [],
167
- time: {
168
- authoredAt: null, authoredAtSource: "migration", observedAt: null, observedAtSource: "migration",
169
- recordedAt: capturedAt, recordedAtSource: "migration",
170
- },
171
- relations: {
172
- replyToEventId: null, threadRootEventId: null, references: [], toolCallId: null,
173
- supersedesEventId: null, redactsEventId: target.id,
174
- },
175
- provenance: { captureKind: "migration", legacyVersion: 2, sourceMessageIndex: null },
176
- };
177
- }
178
- // Frozen constructor inputs, not a text/regex classifier and not live policy.
179
- // The first media wording is the constructor shipped at 2efc01e5; the other
180
- // finite variants are present in the P0 Sanctuary required-read contracts.
181
- const LEGACY_CORRECTIONS = new Set();
182
- for (const [text, names] of [
183
- ["Before answering, read current active work, cares, system health, and service state. Then give Ari one compact household summary; do not ask him to choose a status slice.", ["query_active_work", "query_cares", "unraid_get_system", "unraid_list_containers"]],
184
- ["Before answering, read current active work, cares, system health, service state, storage, and the download queue. Current tool facts outrank care history; a stale care is a recheck item, not a present-tense fact. Then give Ari one compact household summary; do not ask him to choose a status slice.", ["query_active_work", "query_cares", "unraid_get_system", "unraid_list_containers", "unraid_get_storage", "sanctuary_get_download_queue"]],
185
- ["Run both safe reads now, identify the largest measured evidence, report Unmanic and Jellyfin findings, and propose a sample encode without inventing future savings. Do not ask permission or send Ari to a shell or QDirStat while these typed reads are available.", ["unraid_get_storage", "sanctuary_get_media_optimization"]],
186
- ["Run both safe reads now, identify the largest measured evidence, report Unmanic and Jellyfin findings, and propose a sample encode without inventing future savings. If one read returns a degraded or partial result, continue with the other safe reads and bounded container/log tools before answering. Do not ask permission or send Ari to a shell, dashboard, logs, or QDirStat while these typed reads are available.", ["unraid_get_storage", "sanctuary_get_media_optimization"]],
187
- ["Before answering, read current active work, cares, system health, service state, storage, notifications, and the download queue. Current tool facts outrank care history; a stale care is a recheck item, not a present-tense fact. Then give Ari one compact household summary; do not ask him to choose a status slice.", ["query_active_work", "query_cares", "unraid_get_system", "unraid_list_containers", "unraid_get_storage", "unraid_get_notifications", "sanctuary_get_download_queue"]],
188
- ]) {
189
- for (let bits = 1; bits < 2 ** names.length; bits++) {
190
- LEGACY_CORRECTIONS.add(`${text} Missing required tool calls: ${names.filter((_name, index) => (bits & (1 << index)) !== 0).join(", ")}.`);
191
- }
192
- }
193
- for (const text of [
194
- "Use sanctuary_search_media_catalog before answering. If asked for taste or a favorite, form a light recommendation from returned catalog evidence instead of claiming you cannot have preferences. Keep it honest: say you cannot watch, but you can pick from the household shelf.",
195
- "Use sanctuary_search_media_catalog before answering. If a broader media-optimization read fails or degrades, treat that as a diagnostic note and still use the catalog tool for ordinary library visibility questions. If asked for taste or a favorite, form a light recommendation from returned catalog evidence instead of claiming you cannot have preferences. Keep it honest: say you cannot watch, but you can pick from the household shelf.",
196
- "Use sanctuary_search_media_catalog before answering, then report only the current shelf count in ordinary household language.",
197
- "Use sanctuary_search_media_catalog before answering. Lead with the direct answer from current catalog evidence, report the shelf count in ordinary household language, and stop without sampled titles or a follow-up question.",
198
- "Use sanctuary_search_media_catalog with the requested title before answering. Confirm its presence or absence directly from current catalog evidence.",
199
- "Use sanctuary_search_media_catalog before answering. Make one concise, decisive choice grounded in returned catalog evidence; do not volunteer an AI or 'I cannot watch' disclaimer.",
200
- "Use sanctuary_search_media_catalog before answering and base any named titles on the returned catalog evidence.",
201
- ...Array.from({ length: 20 }, (_, index) => `Use sanctuary_search_media_catalog with limit ${index + 1} before answering, then name exactly the returned catalog titles.`),
202
- ])
203
- LEGACY_CORRECTIONS.add(`${text} Missing required tool calls: sanctuary_search_media_catalog.`);
204
- function selectA003LegacyRequiredCorrections(rawEvents) {
205
- if (!Array.isArray(rawEvents) || rawEvents.length === 0)
206
- refuse("legacy event set is missing");
207
- const events = rawEvents;
208
- if (events.some((event) => !event || typeof event !== "object" || event.relations?.redactsEventId != null))
209
- refuse("legacy event set has a redaction conflict");
210
- const max = events.reduce((value, event) => Math.max(value, event.sequence), 0);
211
- const targets = TARGET_BINDINGS.map(({ id, sequence }) => events.find((event) => event.id === id && event.sequence === sequence));
212
- for (const target of targets) {
213
- if (!target || typeof target.content !== "string" || !LEGACY_CORRECTIONS.has(target.content)
214
- || !(0, session_events_1.isExactRawSessionRedactionMarker)(marker(target, max + 1, "1970-01-01T00:00:00.000Z"), [...events, marker(target, max + 1, "1970-01-01T00:00:00.000Z")])
215
- || target.name !== null || target.toolCallId !== null || target.toolCalls.length !== 0 || target.attachments.length !== 0
216
- || target.provenance.captureKind !== "live" || target.provenance.legacyVersion !== null || target.provenance.sourceMessageIndex !== null
217
- || target.time.authoredAt !== null || target.time.authoredAtSource !== "unknown" || target.time.observedAtSource !== "ingest"
218
- || target.time.recordedAtSource !== "save" || target.time.observedAt !== target.time.recordedAt
219
- || !(0, node_util_1.isDeepStrictEqual)(target.relations, { replyToEventId: null, threadRootEventId: null, references: [], toolCallId: null, supersedesEventId: null, redactsEventId: null }))
220
- refuse("legacy correction constructor mismatch");
221
- }
222
- if (events.filter((event) => typeof event.content === "string" && LEGACY_CORRECTIONS.has(event.content)).length !== TARGET_BINDINGS.length)
223
- refuse("extra or ambiguous legacy corrections");
224
- return targets;
225
- }
226
- function rawEnvelope(bytes) {
227
- if (Buffer.byteLength(bytes) > SESSION_LIMIT)
228
- refuse("session exceeds 32 MiB");
229
- const value = JSON.parse(bytes);
230
- const parsed = (0, session_events_1.parseSessionEnvelope)(value);
231
- if (!parsed || !value || typeof value !== "object" || value.version !== 2)
232
- refuse("session must be a v2 envelope");
233
- const envelope = value;
234
- if (JSON.stringify(value, null, 2) !== bytes)
235
- refuse("session bytes are not canonical transaction serialization");
236
- if (!(0, node_util_1.isDeepStrictEqual)(envelope.events, parsed.events))
237
- refuse("session requires normalization");
238
- const projection = envelope.projection;
239
- if (!exactKeys(projection, ["eventIds", "trimmed", "maxTokens", "contextMargin", "inputTokens", "projectedAt"])
240
- || !Array.isArray(projection.eventIds) || projection.eventIds.some((id) => typeof id !== "string")
241
- || typeof projection.trimmed !== "boolean"
242
- || ![projection.maxTokens, projection.contextMargin, projection.inputTokens].every((value) => value === null || typeof value === "number")
243
- || !(projection.projectedAt === null || iso(projection.projectedAt)))
244
- refuse("invalid session projection");
245
- const byId = new Map(envelope.events.map((event) => [event.id, event]));
246
- const seenIds = new Set();
247
- let sequence = 0;
248
- for (const [index, id] of projection.eventIds.entries()) {
249
- const event = byId.get(id);
250
- if (!event || seenIds.has(id))
251
- refuse("invalid projection order or identity");
252
- seenIds.add(id);
253
- if (index === 0 && event.role === "system")
254
- continue;
255
- if (event.sequence <= sequence)
256
- refuse("invalid projection order or identity");
257
- sequence = event.sequence;
258
- }
259
- return envelope;
260
- }
261
- function projectedStructuredOutputs(envelope) {
262
- const byId = new Map(envelope.events.map((event) => [event.id, event]));
263
- const events = (0, session_events_1.projectedSessionEventIds)(envelope).map((id) => byId.get(id));
264
- return (0, structured_output_1.extractStructuredOutputsFromEvents)(events, { emitTelemetry: false });
265
- }
266
- function compute(bytes, relative, capturedAt) {
267
- const envelope = rawEnvelope(bytes);
268
- const targets = selectA003LegacyRequiredCorrections(envelope.events);
269
- const max = envelope.events.reduce((value, event) => Math.max(value, event.sequence), 0);
270
- const entries = targets.map((target, index) => {
271
- const position = envelope.events.indexOf(target);
272
- return {
273
- target, targetSha256: (0, tool_arguments_1.digestJson)(target),
274
- previousEventId: envelope.events[position - 1]?.id ?? null,
275
- nextEventId: envelope.events[position + 1]?.id ?? null,
276
- marker: marker(target, max + index + 1, capturedAt),
277
- };
278
- });
279
- const events = [...envelope.events, ...entries.map((entry) => entry.marker)];
280
- if (!entries.every((entry) => (0, session_events_1.isExactRawSessionRedactionMarker)(entry.marker, events)))
281
- refuse("invalid computed marker block");
282
- const removed = new Set(entries.flatMap((entry) => [entry.target.id, entry.marker.id]));
283
- const selected = new Set((0, session_events_1.projectedSessionEventIds)(envelope).filter((id) => !removed.has(id)));
284
- const postimage = {
285
- ...envelope, events,
286
- projection: {
287
- ...envelope.projection, eventIds: envelope.projection.eventIds.filter((id) => !removed.has(id)),
288
- trimmed: envelope.projection.trimmed || (0, session_events_1.selectEffectiveSessionEvents)(events).some((event) => !selected.has(event.id)),
289
- },
290
- };
291
- postimage.structuredOutputs = projectedStructuredOutputs(postimage);
292
- const postBytes = JSON.stringify(postimage, null, 2);
293
- if (Buffer.byteLength(postBytes) > SESSION_LIMIT)
294
- refuse("postimage exceeds 32 MiB");
295
- return {
296
- manifest: { schemaVersion: SCHEMA, selectorVersion: SELECTOR, agent: "sanctuary", sessionRelativePath: relative, capturedAt, preimageRevision: sha(bytes), postimageRevision: sha(postBytes), entries },
297
- postimage,
298
- };
299
- }
300
- function readManifest(authority) {
301
- if (typeof authority.manifestSha256 !== "string" || !HASH.test(authority.manifestSha256))
302
- refuse("invalid manifest hash");
303
- const bytes = readArtifact(authority.manifestPath, "manifest", MANIFEST_LIMIT);
304
- if (sha(bytes) !== authority.manifestSha256)
305
- refuse("manifest hash changed");
306
- const value = JSON.parse(bytes.toString("utf8"));
307
- if (!exactKeys(value, ["schemaVersion", "selectorVersion", "agent", "sessionRelativePath", "capturedAt", "preimageRevision", "postimageRevision", "entries"])
308
- || value.schemaVersion !== SCHEMA || value.selectorVersion !== SELECTOR || value.agent !== "sanctuary"
309
- || typeof value.sessionRelativePath !== "string" || !iso(value.capturedAt)
310
- || typeof value.preimageRevision !== "string" || !HASH.test(value.preimageRevision)
311
- || typeof value.postimageRevision !== "string" || !HASH.test(value.postimageRevision)
312
- || !Array.isArray(value.entries) || value.entries.length !== TARGET_BINDINGS.length
313
- || JSON.stringify(value, null, 2) !== bytes.toString("utf8"))
314
- refuse("invalid closed repair manifest");
315
- for (const entry of value.entries) {
316
- if (!exactKeys(entry, ["target", "targetSha256", "previousEventId", "nextEventId", "marker"])
317
- || typeof entry.targetSha256 !== "string" || !HASH.test(entry.targetSha256)
318
- || ![entry.previousEventId, entry.nextEventId].every((id) => id === null || typeof id === "string" && id.trim().length > 0))
319
- refuse("invalid manifest entry");
320
- }
321
- const manifest = value;
322
- const targets = selectA003LegacyRequiredCorrections(manifest.entries.map((entry) => entry.target));
323
- const block = manifest.entries.map((entry) => entry.marker);
324
- for (let index = 0; index < manifest.entries.length; index++) {
325
- const entry = manifest.entries[index];
326
- if (!(0, node_util_1.isDeepStrictEqual)(entry.target, targets[index])
327
- || entry.targetSha256 !== (0, tool_arguments_1.digestJson)(entry.target)
328
- || !(0, session_events_1.isExactRawSessionRedactionMarker)(entry.marker, [...targets, ...block])
329
- || !(0, node_util_1.isDeepStrictEqual)(entry.marker, marker(entry.target, block[0].sequence + index, manifest.capturedAt)))
330
- refuse("manifest target or marker mismatch");
331
- }
332
- return manifest;
333
- }
334
- function publishArtifacts(directory, artifacts) {
335
- const pin = privateDirectory(directory);
336
- for (const artifact of artifacts) {
337
- try {
338
- fs.lstatSync(artifact.path, { bigint: true });
339
- refuse("final artifact already exists");
340
- }
341
- catch (error) {
342
- if (error.code !== "ENOENT")
343
- throw error;
344
- }
345
- }
346
- const created = [];
347
- try {
348
- for (const artifact of artifacts) {
349
- checkDirectories(pin);
350
- const record = { temporary: path.join(directory, `.${path.basename(artifact.path)}.${(0, node_crypto_1.randomUUID)()}`), final: artifact.path, identity: null, published: false };
351
- created.push(record);
352
- const fd = fs.openSync(record.temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
353
- try {
354
- record.identity = fs.fstatSync(fd, { bigint: true });
355
- fs.writeFileSync(fd, artifact.bytes);
356
- fs.fsyncSync(fd);
357
- }
358
- catch (error) {
359
- try {
360
- fs.closeSync(fd);
361
- }
362
- catch {
363
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "heart", event: "heart.session_repair_artifact_cleanup_refused", message: "artifact descriptor cleanup failed; primary error retained", meta: { stage: "descriptor" } });
364
- }
365
- throw error;
366
- }
367
- fs.closeSync(fd);
368
- checkDirectories(pin);
369
- fs.linkSync(record.temporary, record.final);
370
- record.published = true;
371
- const directoryFd = fs.openSync(directory, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
372
- try {
373
- fs.fsyncSync(directoryFd);
374
- }
375
- finally {
376
- fs.closeSync(directoryFd);
377
- }
378
- checkDirectories(pin);
379
- const readFd = fs.openSync(record.final, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
380
- try {
381
- const stat = fs.fstatSync(readFd, { bigint: true });
382
- if (!stat.isFile() || !sameInode(record.identity, stat) || (stat.mode & 511n) !== 384n || stat.size !== BigInt(artifact.bytes.length)
383
- || sha(fs.readFileSync(readFd)) !== sha(artifact.bytes))
384
- refuse("published artifact identity or hash mismatch");
385
- }
386
- finally {
387
- fs.closeSync(readFd);
388
- }
389
- }
390
- }
391
- catch (error) {
392
- for (const record of created) {
393
- if (!record.published || !record.identity)
394
- continue;
395
- try {
396
- checkDirectories(pin);
397
- const current = fs.lstatSync(record.final, { bigint: true });
398
- if (current.isFile() && !current.isSymbolicLink() && sameInode(current, record.identity))
399
- fs.unlinkSync(record.final);
400
- }
401
- catch {
402
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "heart", event: "heart.session_repair_artifact_cleanup_refused", message: "artifact cleanup could not safely address its original file", meta: { stage: "final" } });
403
- }
404
- }
405
- throw error;
406
- }
407
- finally {
408
- for (const record of created) {
409
- if (!record.identity)
410
- continue;
411
- try {
412
- checkDirectories(pin);
413
- const current = fs.lstatSync(record.temporary, { bigint: true });
414
- if (current.isFile() && !current.isSymbolicLink() && sameInode(current, record.identity))
415
- fs.unlinkSync(record.temporary);
416
- }
417
- catch {
418
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "heart", event: "heart.session_repair_artifact_cleanup_refused", message: "artifact cleanup could not safely address its original file", meta: { stage: "sibling" } });
419
- }
420
- }
421
- }
422
- }
423
- async function inspectA003SessionRepair(input) {
424
- const location = sessionLocation(input.agent, input.sessionPath);
425
- privateDirectory(input.artifactsDir);
426
- return (0, session_transaction_1.withSessionTurnLease)(input.sessionPath, async (lease) => {
427
- privateFile(input.sessionPath, "session", SESSION_LIMIT);
428
- const current = (0, session_transaction_1.readSessionTransaction)(input.sessionPath, lease);
429
- const { manifest } = compute(current.bytes, location.relative, new Date().toISOString());
430
- const manifestBytes = Buffer.from(JSON.stringify(manifest, null, 2));
431
- if (manifestBytes.length > MANIFEST_LIMIT)
432
- refuse("manifest exceeds 1 MiB");
433
- const manifestPath = path.join(input.artifactsDir, "a003-session-manifest.json");
434
- const preimagePath = path.join(input.artifactsDir, "a003-session-preimage.json");
435
- publishArtifacts(input.artifactsDir, [{ path: preimagePath, bytes: Buffer.from(current.bytes) }, { path: manifestPath, bytes: manifestBytes }]);
436
- (0, runtime_1.emitNervesEvent)({ component: "heart", event: "heart.session_redaction_repair_inspected", message: "fixed repair inspected without session mutation", meta: { targetCount: manifest.entries.length } });
437
- return { status: "inspected", manifestPath, preimagePath, manifestSha256: sha(manifestBytes), preimageRevision: manifest.preimageRevision, postimageRevision: manifest.postimageRevision };
438
- }, { confinementRoot: location.root });
439
- }
440
- function alreadyApplied(envelope, manifest, currentRevision) {
441
- const blockIndex = envelope.events.findIndex((event) => event.id === manifest.entries[0].marker.id);
442
- if (blockIndex < 0 || !(0, node_util_1.isDeepStrictEqual)(envelope.events.slice(blockIndex, blockIndex + TARGET_BINDINGS.length), manifest.entries.map((entry) => entry.marker)))
443
- return false;
444
- if (currentRevision !== manifest.postimageRevision && envelope.events.at(-1).sequence <= manifest.entries.at(-1).marker.sequence)
445
- return false;
446
- try {
447
- const targets = selectA003LegacyRequiredCorrections(envelope.events.slice(0, blockIndex));
448
- if (!(0, node_util_1.isDeepStrictEqual)(targets, manifest.entries.map((entry) => entry.target)))
449
- return false;
450
- }
451
- catch {
452
- return false;
453
- }
454
- const marked = envelope.events.filter((event) => event.relations.redactsEventId !== null);
455
- if (!(0, node_util_1.isDeepStrictEqual)(marked, manifest.entries.map((entry) => entry.marker))
456
- || !marked.every((event) => (0, session_events_1.isExactRawSessionRedactionMarker)(event, envelope.events)))
457
- return false;
458
- const effective = (0, session_events_1.selectEffectiveSessionEvents)(envelope.events);
459
- const visible = new Set(effective.map((event) => event.id));
460
- return envelope.projection.eventIds.every((id) => visible.has(id))
461
- && (0, node_util_1.isDeepStrictEqual)(envelope.structuredOutputs, projectedStructuredOutputs(envelope));
462
- }
463
- async function reconcileWrite(sessionPath, lease, value, before, after, success) {
464
- try {
465
- (0, session_transaction_1.writeSessionTransaction)(sessionPath, value, { lease, expectedRevision: before });
466
- }
467
- catch {
468
- // A throw may occur after rename; only exact, still-confined readback decides.
469
- }
470
- try {
471
- privateFile(sessionPath, "session", SESSION_LIMIT);
472
- const current = (0, session_transaction_1.readSessionTransaction)(sessionPath, lease);
473
- if (current.revision === after)
474
- return { status: success, revision: after };
475
- if (current.revision === before)
476
- return { status: "not_applied", revision: before };
477
- }
478
- catch {
479
- return { status: "indeterminate" };
480
- }
481
- return { status: "indeterminate" };
482
- }
483
- async function applyA003SessionRepair(authority) {
484
- const manifest = readManifest(authority);
485
- const sessionPath = manifestSessionPath(manifest.sessionRelativePath);
486
- const { root } = sessionLocation("sanctuary", sessionPath);
487
- let attemptedWrite = false;
488
- try {
489
- const result = await (0, session_transaction_1.withSessionTurnLease)(sessionPath, async (lease) => {
490
- privateFile(sessionPath, "session", SESSION_LIMIT);
491
- const current = (0, session_transaction_1.readSessionTransaction)(sessionPath, lease);
492
- if (current.revision !== manifest.preimageRevision) {
493
- let envelope;
494
- try {
495
- envelope = rawEnvelope(current.bytes);
496
- }
497
- catch {
498
- return { status: "indeterminate" };
499
- }
500
- if (alreadyApplied(envelope, manifest, current.revision))
501
- return { status: "already_applied", revision: current.revision };
502
- if (!envelope.events.some((event) => event.relations.redactsEventId !== null))
503
- refuse("session preimage revision changed");
504
- return { status: "indeterminate" };
505
- }
506
- const computed = compute(current.bytes, manifest.sessionRelativePath, manifest.capturedAt);
507
- if (!(0, node_util_1.isDeepStrictEqual)(computed.manifest, manifest))
508
- refuse("manifest differs from independently computed repair");
509
- attemptedWrite = true;
510
- return reconcileWrite(sessionPath, lease, computed.postimage, manifest.preimageRevision, manifest.postimageRevision, "applied");
511
- }, { confinementRoot: root });
512
- (0, runtime_1.emitNervesEvent)({ component: "heart", event: "heart.session_redaction_repair_applied", message: "fixed repair apply readback classified", meta: { status: result.status } });
513
- return result;
514
- }
515
- catch (error) {
516
- if (attemptedWrite)
517
- return { status: "indeterminate" };
518
- throw error;
519
- }
520
- }
521
- async function rollbackA003SessionRepair(authority) {
522
- const manifest = readManifest(authority);
523
- const preimage = readArtifact(authority.preimagePath, "preimage", SESSION_LIMIT);
524
- if (sha(preimage) !== manifest.preimageRevision)
525
- refuse("preimage digest mismatch");
526
- const computed = compute(preimage.toString("utf8"), manifest.sessionRelativePath, manifest.capturedAt);
527
- if (!(0, node_util_1.isDeepStrictEqual)(computed.manifest, manifest))
528
- refuse("rollback manifest differs from preimage");
529
- const value = JSON.parse(preimage.toString("utf8"));
530
- const sessionPath = manifestSessionPath(manifest.sessionRelativePath);
531
- const { root } = sessionLocation("sanctuary", sessionPath);
532
- let attemptedWrite = false;
533
- try {
534
- const result = await (0, session_transaction_1.withSessionTurnLease)(sessionPath, async (lease) => {
535
- privateFile(sessionPath, "session", SESSION_LIMIT);
536
- const current = (0, session_transaction_1.readSessionTransaction)(sessionPath, lease);
537
- if (current.revision === manifest.preimageRevision)
538
- return { status: "already_rolled_back", revision: current.revision };
539
- if (current.revision !== manifest.postimageRevision)
540
- refuse("rollback requires the exact untouched postimage");
541
- attemptedWrite = true;
542
- return reconcileWrite(sessionPath, lease, value, manifest.postimageRevision, manifest.preimageRevision, "rolled_back");
543
- }, { confinementRoot: root });
544
- (0, runtime_1.emitNervesEvent)({ component: "heart", event: "heart.session_redaction_repair_rolled_back", message: "fixed repair rollback readback classified", meta: { status: result.status } });
545
- return result;
546
- }
547
- catch (error) {
548
- if (attemptedWrite)
549
- return { status: "indeterminate" };
550
- throw error;
551
- }
552
- }