@ouro.bot/cli 0.1.0-alpha.1684 → 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 +18 -1
- package/deploy/unraid/container-runtime.json +1 -1
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/a2a/config.js +4 -4
- package/dist/heart/daemon/cli-commands/entry-points.js +0 -39
- package/dist/heart/daemon/daemon-entry.js +14 -5
- package/dist/heart/external-events/router.js +19 -12
- package/dist/heart/product/active.js +28 -3
- package/dist/products/butler.js +16 -0
- package/dist/senses/telegram-effect-adapter.js +3 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/heart/session-redaction-repair-cli-main.js +0 -34
- package/dist/heart/session-redaction-repair.js +0 -552
package/changelog.json
CHANGED
|
@@ -1,13 +1,30 @@
|
|
|
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
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"version": "0.1.0-alpha.1685",
|
|
12
|
+
"changes": [
|
|
13
|
+
"The Butler now registers itself with the harness as a product. The Unraid image names its module in `container-runtime.json`, and every process in the container loads it. Core learns the Butler's two names (`butler`, and `sanctuary` from before the rename) from that registration instead of importing Butler code, for the A2A port, the saved external events and the Telegram failsafe. Nothing changes for the person: the Butler keeps its port and its saved events under either name."
|
|
14
|
+
]
|
|
15
|
+
},
|
|
4
16
|
{
|
|
5
17
|
"version": "0.1.0-alpha.1684",
|
|
6
18
|
"changes": [
|
|
7
|
-
"Update the Ouro UI files to Ouro UI v1.3.617.",
|
|
8
19
|
"Update the Ouro UI files to Ouro UI v1.3.618."
|
|
9
20
|
]
|
|
10
21
|
},
|
|
22
|
+
{
|
|
23
|
+
"version": "0.1.0-alpha.1683",
|
|
24
|
+
"changes": [
|
|
25
|
+
"Update the Ouro UI files to Ouro UI v1.3.617."
|
|
26
|
+
]
|
|
27
|
+
},
|
|
11
28
|
{
|
|
12
29
|
"version": "0.1.0-alpha.1682",
|
|
13
30
|
"changes": [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"scheduler":"supercronic","updates":"disabled"}
|
|
1
|
+
{"scheduler":"supercronic","updates":"disabled","product":"/opt/ouro/dist/products/butler.js"}
|
|
@@ -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.
|
|
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>
|
package/dist/a2a/config.js
CHANGED
|
@@ -6,14 +6,14 @@ exports.normalizeA2APath = normalizeA2APath;
|
|
|
6
6
|
exports.a2aEndpointFromBaseUrl = a2aEndpointFromBaseUrl;
|
|
7
7
|
const node_crypto_1 = require("node:crypto");
|
|
8
8
|
const runtime_1 = require("../nerves/runtime");
|
|
9
|
-
const
|
|
9
|
+
const active_1 = require("../heart/product/active");
|
|
10
10
|
exports.A2A_DEFAULT_PROTOCOL_VERSION = "1.0";
|
|
11
11
|
exports.A2A_DEFAULT_HOST = "127.0.0.1";
|
|
12
12
|
exports.A2A_DEFAULT_PATH = "/a2a";
|
|
13
13
|
function defaultA2APort(agentName) {
|
|
14
|
-
//
|
|
15
|
-
// rename must not move it.
|
|
16
|
-
const portKey = (0,
|
|
14
|
+
// A product's agent keeps the port its first name gave, whatever it is called now: peers saved its agent card at that
|
|
15
|
+
// port, so a rename must not move it. Its names run current first, so the first name is the last one listed.
|
|
16
|
+
const portKey = (0, active_1.productFor)(agentName)?.agents.at(-1) ?? agentName;
|
|
17
17
|
const digest = (0, node_crypto_1.createHash)("sha256").update(portKey).digest();
|
|
18
18
|
const port = 18920 + (digest[0] % 60);
|
|
19
19
|
(0, runtime_1.emitNervesEvent)({
|
|
@@ -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
|
] } },
|
|
@@ -52,7 +52,7 @@ const sense_manager_1 = require("./sense-manager");
|
|
|
52
52
|
const agent_discovery_1 = require("./agent-discovery");
|
|
53
53
|
const agent_home_1 = require("./agent-home");
|
|
54
54
|
const identity_1 = require("../identity");
|
|
55
|
-
const
|
|
55
|
+
const active_1 = require("../product/active");
|
|
56
56
|
const app_sessions_record_1 = require("./app-sessions-record");
|
|
57
57
|
const runtime_mode_1 = require("./runtime-mode");
|
|
58
58
|
const habit_scheduler_1 = require("../habits/habit-scheduler");
|
|
@@ -117,6 +117,15 @@ if (homeFilesystemProblem) {
|
|
|
117
117
|
process.exit(1);
|
|
118
118
|
}
|
|
119
119
|
/* v8 ignore stop */
|
|
120
|
+
/* v8 ignore start -- the product module the image names loads first, so a broken one stops the start; the loader is unit-tested in heart/product @preserve */
|
|
121
|
+
try {
|
|
122
|
+
(0, active_1.loadImageProduct)();
|
|
123
|
+
}
|
|
124
|
+
catch (failure) {
|
|
125
|
+
process.stderr.write(`${failure instanceof Error ? failure.message : String(failure)}\ncode: product-invalid\n`);
|
|
126
|
+
process.exit(1);
|
|
127
|
+
}
|
|
128
|
+
/* v8 ignore stop */
|
|
120
129
|
const entryPath = path.resolve(__dirname, "daemon-entry.js");
|
|
121
130
|
const mode = (0, runtime_mode_1.detectRuntimeMode)((0, identity_1.getRepoRoot)());
|
|
122
131
|
// Each agent runs on exactly one machine: manage only agents homed here
|
|
@@ -125,7 +134,7 @@ const daemonMachine = (0, machine_identity_1.loadOrCreateMachineIdentity)();
|
|
|
125
134
|
const daemonMachineId = daemonMachine.machineId;
|
|
126
135
|
const managedAgents = (0, agent_discovery_1.listHomeBundleAgents)({ machineId: daemonMachineId });
|
|
127
136
|
// The Butler under whichever name its bundle has; its container paths follow that name.
|
|
128
|
-
const butlerName = (0,
|
|
137
|
+
const butlerName = (0, active_1.productAgentAmong)(managedAgents) ?? "sanctuary";
|
|
129
138
|
// Its saved external events follow that name too: a folder left under the other name (by the rename or a rollback) moves over.
|
|
130
139
|
// It must: records left under the other name can't be settled, so a failed move or merge stops the start.
|
|
131
140
|
try {
|
|
@@ -550,7 +559,7 @@ const daemon = new daemon_1.OuroDaemon({
|
|
|
550
559
|
},
|
|
551
560
|
schedulerFireConsumer: (origin) => (0, sanctuary_scheduler_liveness_1.consumeSanctuarySchedulerFire)(path.join((0, identity_1.getAgentBundlesRoot)(), `${butlerName}.ouro`), origin),
|
|
552
561
|
nativeHabitRunner: async ({ agent, habitName, trigger, occurrenceId, runnerId, schedulerOrigin }) => {
|
|
553
|
-
if (!(0,
|
|
562
|
+
if (!(0, active_1.productFor)(agent) || habitName !== "sanctuary-health")
|
|
554
563
|
return null;
|
|
555
564
|
const marker = (0, sanctuary_acceptance_marker_1.readSanctuaryAcceptanceMarker)(agent);
|
|
556
565
|
const schedulerScenario = marker?.label === "unit-16f-cron-fingerprint" ? marker : null;
|
|
@@ -593,7 +602,7 @@ const daemon = new daemon_1.OuroDaemon({
|
|
|
593
602
|
}
|
|
594
603
|
return result;
|
|
595
604
|
},
|
|
596
|
-
nativeHabitMatch: (agent, habitName) => (0,
|
|
605
|
+
nativeHabitMatch: (agent, habitName) => (0, active_1.productFor)(agent) !== null && habitName === "sanctuary-health",
|
|
597
606
|
mode,
|
|
598
607
|
onStopCommandComplete: async () => {
|
|
599
608
|
await stopEntryRuntime();
|
|
@@ -910,7 +919,7 @@ void (0, daemon_bootstrap_startup_1.startDaemonAfterContainerCredentialBootstrap
|
|
|
910
919
|
habitsDir,
|
|
911
920
|
osCronManager,
|
|
912
921
|
onHabitFire: (habitName, trigger, context) => {
|
|
913
|
-
if ((0, habit_policy_1.isRsvpHabitName)(habitName) || ((0,
|
|
922
|
+
if ((0, habit_policy_1.isRsvpHabitName)(habitName) || ((0, active_1.productFor)(agent) !== null && habitName === "sanctuary-health")) {
|
|
914
923
|
(0, socket_client_1.sendDaemonCommand)(socketPath, {
|
|
915
924
|
kind: "habit.poke",
|
|
916
925
|
agent,
|
|
@@ -63,7 +63,7 @@ const path = __importStar(require("node:path"));
|
|
|
63
63
|
const runtime_1 = require("../../nerves/runtime");
|
|
64
64
|
const ouro_version_manager_1 = require("../versioning/ouro-version-manager");
|
|
65
65
|
const atomic_file_1 = require("../atomic-file");
|
|
66
|
-
const
|
|
66
|
+
const active_1 = require("../product/active");
|
|
67
67
|
const MAX_EVENT_TEXT_BYTES = 4_096;
|
|
68
68
|
const MAX_EVENT_EVIDENCE = 32;
|
|
69
69
|
const MAX_EVENT_RECORD_BYTES = 64 * 1_024;
|
|
@@ -323,13 +323,17 @@ function isRecord(value) {
|
|
|
323
323
|
}
|
|
324
324
|
// The Butler this daemon runs, set once at daemon start. Records saved under the Butler's other name are its records.
|
|
325
325
|
let runningButler = null;
|
|
326
|
+
/** Whether this name (an agent, a record's `agent` or an event folder) is one of the product's names. */
|
|
327
|
+
function isProductAgentName(name) {
|
|
328
|
+
return (0, active_1.productFor)(name) !== null;
|
|
329
|
+
}
|
|
326
330
|
/** The agent a record or new event belongs to: a Butler name means the running Butler, or the Butler folder it sits in. */
|
|
327
331
|
function eventAgent(agent, folder) {
|
|
328
|
-
if (!(
|
|
332
|
+
if (!isProductAgentName(agent))
|
|
329
333
|
return agent;
|
|
330
334
|
if (runningButler)
|
|
331
335
|
return runningButler;
|
|
332
|
-
return folder !== undefined && (
|
|
336
|
+
return folder !== undefined && isProductAgentName(folder) ? folder : agent;
|
|
333
337
|
}
|
|
334
338
|
/** The record as the daemon sees it: owned by the running Butler, at the path it was read from. */
|
|
335
339
|
function normaliseButlerRecord(record, recordPath) {
|
|
@@ -348,7 +352,7 @@ function readStoredExternalEventRecord(recordPath) {
|
|
|
348
352
|
return parsed;
|
|
349
353
|
// A Butler record whose folder was adopted under the Butler's other name: it names the folder it was written in, or this one.
|
|
350
354
|
const folder = path.basename(path.dirname(path.dirname(recordPath)));
|
|
351
|
-
const adopted = (
|
|
355
|
+
const adopted = isProductAgentName(parsed.agent) && isProductAgentName(folder)
|
|
352
356
|
&& path.resolve(externalEventRecordPath(root, { ...parsed, agent: folder })) === here
|
|
353
357
|
&& [here, expectedPath].includes(path.resolve(parsed.recordPath));
|
|
354
358
|
if (!adopted)
|
|
@@ -366,7 +370,7 @@ function readExternalEventRecord(recordPath) {
|
|
|
366
370
|
function externalEventAwaitRecordPath(agentName, filedFromKey, root = getExternalEventRoot()) {
|
|
367
371
|
const resolvedRoot = path.resolve(root);
|
|
368
372
|
const [folder, ...rest] = path.relative(resolvedRoot, path.resolve(filedFromKey)).split(path.sep);
|
|
369
|
-
if (!(
|
|
373
|
+
if (!isProductAgentName(agentName) || !isProductAgentName(folder) || folder === agentName || fs.existsSync(filedFromKey))
|
|
370
374
|
return filedFromKey;
|
|
371
375
|
return path.join(resolvedRoot, agentName, ...rest);
|
|
372
376
|
}
|
|
@@ -489,11 +493,14 @@ function removeMergedEventFolder(dir) {
|
|
|
489
493
|
* Butler's folder can't be settled. A symlinked other folder is left alone, with a warning.
|
|
490
494
|
*/
|
|
491
495
|
function prepareButlerExternalEvents(root, managedAgents, now = () => new Date().toISOString()) {
|
|
492
|
-
const butler = (0,
|
|
496
|
+
const butler = (0, active_1.productAgentAmong)(managedAgents);
|
|
493
497
|
runningButler = butler;
|
|
494
498
|
if (!butler)
|
|
495
499
|
return "none";
|
|
496
|
-
|
|
500
|
+
// The product's other name: the Butler has exactly two, the one it runs as and the one from before the rename.
|
|
501
|
+
const otherName = (0, active_1.productFor)(butler).agents.find((name) => name !== butler);
|
|
502
|
+
if (otherName === undefined)
|
|
503
|
+
return "none";
|
|
497
504
|
const own = path.join(root, butler);
|
|
498
505
|
const other = path.join(root, otherName);
|
|
499
506
|
let otherStat;
|
|
@@ -637,9 +644,9 @@ function parseRepairManifest(manifestPath) {
|
|
|
637
644
|
}
|
|
638
645
|
/** The folder a reviewed repair's record is in: its own agent's, or the other Butler name's once the daemon adopted it. */
|
|
639
646
|
function repairFolderAgent(root, entry) {
|
|
640
|
-
if (!(
|
|
647
|
+
if (!isProductAgentName(entry.agent))
|
|
641
648
|
return entry.agent;
|
|
642
|
-
const names = [entry.agent, ...
|
|
649
|
+
const names = [entry.agent, ...(0, active_1.productFor)(entry.agent).agents.filter((name) => name !== entry.agent)];
|
|
643
650
|
return names.find((agent) => fs.existsSync(externalEventRecordPath(root, { ...entry, agent }))) ?? entry.agent;
|
|
644
651
|
}
|
|
645
652
|
function assertRepairRecordPath(root, entry) {
|
|
@@ -1114,7 +1121,7 @@ function parsePrivilegedEnvelope(raw, fileName, now) {
|
|
|
1114
1121
|
const observationTransitionIsAllowed = value.eventType !== "usenet.health_observation" || /^(?:auth-failed|stalled|recovered|indeterminate):\d{8}T\d{6}Z$/u.test(String(value.transitionId));
|
|
1115
1122
|
const expectedKeys = ["action", "actionReceipt", "agent", "createdAt", "critical", "eventType", "evidence", "expiresAt", "incidentKey", "nonce", "observationRevision", "protectiveStateDigest", "protectiveStateObservedAt", "protectiveStateVerified", "schemaVersion", "source", "summary", "transitionId"];
|
|
1116
1123
|
if (Object.keys(value).sort().join("\0") !== expectedKeys.sort().join("\0")
|
|
1117
|
-
|| value.schemaVersion !== 1 || !(
|
|
1124
|
+
|| value.schemaVersion !== 1 || !isProductAgentName(value.agent) || value.source !== PRIVILEGED_EVENT_SOURCE
|
|
1118
1125
|
|| !eventShapeIsAllowed || !observationTransitionIsAllowed
|
|
1119
1126
|
|| value.critical !== true || !boundedIdentifier(value.incidentKey) || !boundedIdentifier(value.transitionId)
|
|
1120
1127
|
|| !/^[a-f0-9]{64}$/u.test(String(value.observationRevision)) || !/^[a-f0-9]{64}$/u.test(String(value.nonce))
|
|
@@ -1265,7 +1272,7 @@ function isReplayState(value) {
|
|
|
1265
1272
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1266
1273
|
return false;
|
|
1267
1274
|
const state = value;
|
|
1268
|
-
if (state.schemaVersion !== 1 || !(
|
|
1275
|
+
if (state.schemaVersion !== 1 || !isProductAgentName(state.agent) || state.source !== PRIVILEGED_EVENT_SOURCE || !canonicalIso(state.updatedAt))
|
|
1269
1276
|
return false;
|
|
1270
1277
|
try {
|
|
1271
1278
|
replayBytes(state);
|
|
@@ -1444,7 +1451,7 @@ function commitMutation(recordPath, record, now) {
|
|
|
1444
1451
|
function bindPrivilegedFailsafeArtifact(recordPath, input) {
|
|
1445
1452
|
return withRecordLock(recordPath, () => {
|
|
1446
1453
|
const record = readExternalEventRecord(recordPath);
|
|
1447
|
-
if (!(
|
|
1454
|
+
if (!isProductAgentName(record.agent) || record.source !== PRIVILEGED_EVENT_SOURCE || !record.privilegedProtectiveAction) {
|
|
1448
1455
|
throw new Error("System failsafe requires a privileged Sanctuary event");
|
|
1449
1456
|
}
|
|
1450
1457
|
if (!/^[a-f0-9]{64}$/u.test(input.artifactId))
|
|
@@ -2,11 +2,16 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.PRODUCT_SEAM_VERSION = void 0;
|
|
4
4
|
exports.loadProduct = loadProduct;
|
|
5
|
+
exports.loadImageProduct = loadImageProduct;
|
|
5
6
|
exports.productFor = productFor;
|
|
7
|
+
exports.productAgentAmong = productAgentAmong;
|
|
6
8
|
const runtime_1 = require("../../nerves/runtime");
|
|
9
|
+
const container_runtime_1 = require("../daemon/container-runtime");
|
|
7
10
|
/** The seam version this harness runs. A product built for another stops the start. */
|
|
8
11
|
exports.PRODUCT_SEAM_VERSION = 1;
|
|
9
12
|
let active = null;
|
|
13
|
+
// Whether this process has settled which product it runs: by an explicit load, or by the first productFor reading the image's policy.
|
|
14
|
+
let settled = false;
|
|
10
15
|
function invalid(modulePath, problem) {
|
|
11
16
|
(0, runtime_1.emitNervesEvent)({
|
|
12
17
|
level: "error",
|
|
@@ -39,10 +44,13 @@ function validProduct(value, modulePath) {
|
|
|
39
44
|
* invalid stops the start.
|
|
40
45
|
*/
|
|
41
46
|
function loadProduct(modulePath, load = require) {
|
|
47
|
+
active = null;
|
|
42
48
|
if (modulePath === undefined) {
|
|
43
|
-
|
|
49
|
+
settled = true;
|
|
44
50
|
return null;
|
|
45
51
|
}
|
|
52
|
+
// A module that fails stays unsettled, so every later productFor in this process fails the same way instead of answering null.
|
|
53
|
+
settled = false;
|
|
46
54
|
let loaded;
|
|
47
55
|
try {
|
|
48
56
|
loaded = load(modulePath);
|
|
@@ -51,6 +59,7 @@ function loadProduct(modulePath, load = require) {
|
|
|
51
59
|
throw invalid(modulePath, `it did not load (${error instanceof Error ? error.message : String(error)})`);
|
|
52
60
|
}
|
|
53
61
|
active = validProduct(loaded, modulePath);
|
|
62
|
+
settled = true;
|
|
54
63
|
(0, runtime_1.emitNervesEvent)({
|
|
55
64
|
component: "daemon",
|
|
56
65
|
event: "daemon.product_loaded",
|
|
@@ -59,7 +68,23 @@ function loadProduct(modulePath, load = require) {
|
|
|
59
68
|
});
|
|
60
69
|
return active;
|
|
61
70
|
}
|
|
62
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* Loads the product /opt/ouro/container-runtime.json names (`product`), or none when the file is absent or names none. The
|
|
73
|
+
* daemon calls it first, so a broken product stops the start; every other process (each sense, the agent's own turns, the CLI)
|
|
74
|
+
* settles it on its first `productFor`, so no child can run without the product its image names.
|
|
75
|
+
*/
|
|
76
|
+
function loadImageProduct(options = {}) {
|
|
77
|
+
const policy = (0, container_runtime_1.readContainerRuntimePolicy)(options.policyPath === undefined ? {} : { path: options.policyPath });
|
|
78
|
+
return loadProduct(policy?.product, options.load);
|
|
79
|
+
}
|
|
80
|
+
/** The loaded product when this agent (or a saved record's `agent`) is one of its names, else null. */
|
|
63
81
|
function productFor(agentName) {
|
|
64
|
-
|
|
82
|
+
if (!settled)
|
|
83
|
+
loadImageProduct();
|
|
84
|
+
return active && typeof agentName === "string" && active.agents.includes(agentName) ? active : null;
|
|
85
|
+
}
|
|
86
|
+
/** The one agent among `agents` that the product runs, or null when there is none or more than one. */
|
|
87
|
+
function productAgentAmong(agents) {
|
|
88
|
+
const owned = agents.filter((agent) => productFor(agent) !== null);
|
|
89
|
+
return owned.length === 1 ? owned[0] : null;
|
|
65
90
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.product = void 0;
|
|
4
|
+
const butler_agent_1 = require("../heart/butler-agent");
|
|
5
|
+
const runtime_1 = require("../nerves/runtime");
|
|
6
|
+
/**
|
|
7
|
+
* The Butler, registered with the harness through the product seam. The Unraid image names this module in
|
|
8
|
+
* /opt/ouro/container-runtime.json, so core loads it at runtime and never imports it. Each of the Butler's jobs gets its
|
|
9
|
+
* slot here as it moves behind the seam (M3).
|
|
10
|
+
*/
|
|
11
|
+
exports.product = {
|
|
12
|
+
seamVersion: 1,
|
|
13
|
+
id: "butler",
|
|
14
|
+
agents: butler_agent_1.BUTLER_AGENT_NAMES,
|
|
15
|
+
};
|
|
16
|
+
(0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.butler_product_registered", message: "Butler product registered", meta: { agents: [...exports.product.agents] } });
|
|
@@ -57,7 +57,7 @@ const session_events_1 = require("../heart/session-events");
|
|
|
57
57
|
const session_transaction_1 = require("../mind/session-transaction");
|
|
58
58
|
const telegram_client_1 = require("./telegram-client");
|
|
59
59
|
const telegram_markdown_1 = require("./telegram-markdown");
|
|
60
|
-
const
|
|
60
|
+
const active_1 = require("../heart/product/active");
|
|
61
61
|
exports.FIXED_ADMISSION_ACKNOWLEDGEMENT = "Thanks — I’ve asked the person I work for. Your message is still unread and unprocessed; I’ll only read it if they welcome you in.";
|
|
62
62
|
exports.FIXED_USENET_SYSTEM_FAILSAFE = "Quick heads-up: I paused downloads because the server was discarding most of what it fetched. Nothing needs doing this second — I’ll investigate and follow up when I’m back online.";
|
|
63
63
|
const SYSTEM_FAILSAFE_UNAVAILABLE_MS = 2 * 60_000;
|
|
@@ -544,7 +544,7 @@ async function reconcileTelegramSystemFailsafe(input) {
|
|
|
544
544
|
const action = record.privilegedProtectiveAction;
|
|
545
545
|
if (record.privilegedFailsafe)
|
|
546
546
|
return { sent: false, reason: "already_recorded", artifactId: record.privilegedFailsafe.artifactId };
|
|
547
|
-
if (!(0,
|
|
547
|
+
if (!(0, active_1.productFor)(record.agent) || record.source !== "sanctuary-usenet" || record.eventType !== "usenet.protective_action"
|
|
548
548
|
|| record.priority !== "critical" || !action?.critical)
|
|
549
549
|
return { sent: false, reason: "noncritical" };
|
|
550
550
|
if (!action.verification.verified)
|
|
@@ -579,7 +579,7 @@ async function reconcileTelegramSystemFailsafe(input) {
|
|
|
579
579
|
async function sweepTelegramSystemFailsafes(input) {
|
|
580
580
|
const scanned = (input.scanCache ?? new router_1.ExternalEventScanCache()).scan(input.eventRoot);
|
|
581
581
|
const records = scanned
|
|
582
|
-
.flatMap((entry) => entry.record && (0,
|
|
582
|
+
.flatMap((entry) => entry.record && (0, active_1.productFor)(entry.record.agent) && entry.record.source === "sanctuary-usenet" && !entry.record.privilegedFailsafe ? [entry.record] : [])
|
|
583
583
|
.sort((left, right) => left.eventId.localeCompare(right.eventId))
|
|
584
584
|
.slice(0, 32);
|
|
585
585
|
let sent = 0;
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
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.
|
|
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.
|
|
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
|
-
}
|