@aikdna/kdna-mcp-server 0.5.0 → 0.8.0
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/NOTICE +8 -2
- package/README.md +304 -222
- package/bin/kdna-mcp.mjs +200 -1425
- package/bin/model-view.mjs +30 -0
- package/bin/operator-binding.mjs +144 -0
- package/bin/read-session.mjs +120 -0
- package/bin/reading-views.mjs +161 -0
- package/bin/task-content.mjs +123 -0
- package/package.json +39 -12
- package/vendor/aikdna-kdna-cli-0.44.0.tgz +0 -0
- package/vendor/aikdna-kdna-core-0.37.11.tgz +0 -0
- package/vendor/aikdna-kdna-read-0.13.5.tgz +0 -0
- package/vendor/ajv-8.20.0.tgz +0 -0
- package/vendor/ajv-formats-3.0.1.tgz +0 -0
- package/vendor/cbor-x-1.6.9.tgz +0 -0
- package/vendor/fast-deep-equal-3.1.3.tgz +0 -0
- package/vendor/fast-uri-3.1.9.tgz +0 -0
- package/vendor/json-schema-traverse-1.0.0.tgz +0 -0
- package/vendor/noble-hashes-1.8.0.tgz +0 -0
- package/vendor/pako-2.1.0.tgz +0 -0
- package/vendor/require-from-string-2.0.2.tgz +0 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
|
|
3
|
+
const require = createRequire(import.meta.url);
|
|
4
|
+
|
|
5
|
+
// The installed Read package owns the projection function; this adapter calls
|
|
6
|
+
// the same official entry the CLI uses and never reshapes fields itself. The
|
|
7
|
+
// capability is detected at runtime, so an installation without it keeps the
|
|
8
|
+
// previous default instead of receiving an invented surface.
|
|
9
|
+
export function loadModelView() {
|
|
10
|
+
try {
|
|
11
|
+
const module = require("@aikdna/kdna-read");
|
|
12
|
+
return typeof module.projectModelView === "function" &&
|
|
13
|
+
typeof module.MODEL_VIEW_CONTRACT === "string"
|
|
14
|
+
? module
|
|
15
|
+
: null;
|
|
16
|
+
} catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function projectBody(modelView, value) {
|
|
22
|
+
// A channel that is not a read envelope, a rejection and a no-body control
|
|
23
|
+
// pass through the projection unchanged; the official function decides.
|
|
24
|
+
return modelView.projectModelView(value, {
|
|
25
|
+
view: "body",
|
|
26
|
+
...(typeof value?.envelope?.mode === "string" && value.envelope.mode
|
|
27
|
+
? { mode: value.envelope.mode }
|
|
28
|
+
: {}),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
|
|
6
|
+
export class AdapterError extends Error {
|
|
7
|
+
constructor(code, message) { super(message); this.code = code; }
|
|
8
|
+
}
|
|
9
|
+
const invalid = () => new AdapterError("MCP_BINDING_INVALID", "The operator-selected local file is unavailable or changed.");
|
|
10
|
+
const invalidPassword = () => new AdapterError("MCP_BINDING_INVALID", "The operator-supplied password source is unavailable or invalid.");
|
|
11
|
+
const sameFile = (a, b) => a.isFile() && b.isFile() && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
|
|
12
|
+
|
|
13
|
+
function stripTrailingNewline(bytes) {
|
|
14
|
+
let end = bytes.length;
|
|
15
|
+
if (end > 0 && bytes[end - 1] === 0x0a) {
|
|
16
|
+
end -= 1;
|
|
17
|
+
if (end > 0 && bytes[end - 1] === 0x0d) end -= 1;
|
|
18
|
+
}
|
|
19
|
+
return bytes.subarray(0, end);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function readPasswordFile(passwordPath) {
|
|
23
|
+
if (!path.isAbsolute(passwordPath) || path.resolve(passwordPath) !== passwordPath || passwordPath.length > 4096) throw invalidPassword();
|
|
24
|
+
let fd;
|
|
25
|
+
try {
|
|
26
|
+
const before = fs.lstatSync(passwordPath);
|
|
27
|
+
if (!before.isFile() || before.isSymbolicLink() || before.size === 0 || before.size > 4096 || fs.realpathSync(passwordPath) !== passwordPath) throw invalidPassword();
|
|
28
|
+
fd = fs.openSync(passwordPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
29
|
+
const opened = fs.fstatSync(fd);
|
|
30
|
+
if (!sameFile(before, opened)) throw invalidPassword();
|
|
31
|
+
const raw = Buffer.alloc(opened.size);
|
|
32
|
+
let count = 0;
|
|
33
|
+
while (count < raw.length) {
|
|
34
|
+
const n = fs.readSync(fd, raw, count, raw.length - count, null);
|
|
35
|
+
if (n === 0) throw invalidPassword();
|
|
36
|
+
count += n;
|
|
37
|
+
}
|
|
38
|
+
if (fs.readSync(fd, Buffer.alloc(1), 0, 1, null) !== 0 || !sameFile(opened, fs.fstatSync(fd))) throw invalidPassword();
|
|
39
|
+
const trimmed = stripTrailingNewline(raw);
|
|
40
|
+
if (trimmed.length === 0) throw invalidPassword();
|
|
41
|
+
return Buffer.from(trimmed);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (error instanceof AdapterError) throw error;
|
|
44
|
+
throw invalidPassword();
|
|
45
|
+
} finally {
|
|
46
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readPasswordFd(fdNumber) {
|
|
51
|
+
try {
|
|
52
|
+
const chunks = [];
|
|
53
|
+
let total = 0;
|
|
54
|
+
const buf = Buffer.alloc(1024);
|
|
55
|
+
while (true) {
|
|
56
|
+
const n = fs.readSync(fdNumber, buf, 0, buf.length, null);
|
|
57
|
+
if (n === 0) break;
|
|
58
|
+
total += n;
|
|
59
|
+
if (total > 4096) throw invalidPassword();
|
|
60
|
+
chunks.push(Buffer.from(buf.subarray(0, n)));
|
|
61
|
+
}
|
|
62
|
+
const raw = Buffer.concat(chunks, total);
|
|
63
|
+
const trimmed = stripTrailingNewline(raw);
|
|
64
|
+
if (trimmed.length === 0) throw invalidPassword();
|
|
65
|
+
return Buffer.from(trimmed);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (error instanceof AdapterError) throw error;
|
|
68
|
+
throw invalidPassword();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Only the local operator/trusted launcher supplies argv, never MCP input.
|
|
73
|
+
export function bindOperatorInput(argv) {
|
|
74
|
+
let selected, allowed = false, passwordFile, passwordFd;
|
|
75
|
+
for (let i = 0; i < argv.length; i++) {
|
|
76
|
+
if (argv[i] === "--asset" && selected === undefined && typeof argv[i + 1] === "string") selected = argv[++i];
|
|
77
|
+
else if (argv[i] === "--allow-read" && !allowed) allowed = true;
|
|
78
|
+
else if (argv[i] === "--password-file" && passwordFile === undefined && passwordFd === undefined && typeof argv[i + 1] === "string" && argv[i + 1].length > 0) passwordFile = argv[++i];
|
|
79
|
+
else if (argv[i] === "--password-fd" && passwordFd === undefined && passwordFile === undefined && typeof argv[i + 1] === "string" && /^[1-9][0-9]*$/.test(argv[i + 1]) && Number(argv[i + 1]) >= 3 && Number.isSafeInteger(Number(argv[i + 1]))) passwordFd = Number(argv[++i]);
|
|
80
|
+
else throw new AdapterError("MCP_ARGUMENT_INVALID", "Use --asset /absolute/selected.kdna --allow-read [--password-file /absolute/passphrase | --password-fd <fd>=3..], or start without a binding.");
|
|
81
|
+
}
|
|
82
|
+
if (allowed && selected === undefined) throw new AdapterError("MCP_ARGUMENT_INVALID", "An operator-selected file is required.");
|
|
83
|
+
if ((passwordFile !== undefined || passwordFd !== undefined) && (!allowed || selected === undefined)) throw new AdapterError("MCP_ARGUMENT_INVALID", "Password options require --asset /absolute/selected.kdna --allow-read.");
|
|
84
|
+
let directory = null, identity = null, closed = false;
|
|
85
|
+
const binding = {
|
|
86
|
+
state: "unbound", file: null, passwordFile: null, name: null, digest: null,
|
|
87
|
+
assertReadable() {
|
|
88
|
+
if (closed) throw new AdapterError("MCP_BINDING_CANCELLED", "This process binding is closed. The operator must start a new process to select again.");
|
|
89
|
+
if (!this.file) throw new AdapterError("MCP_BINDING_REQUIRED", "The local operator must select one file and permit local read before starting this process.");
|
|
90
|
+
},
|
|
91
|
+
close() {
|
|
92
|
+
closed = true; this.state = "cancelled"; this.file = null;
|
|
93
|
+
if (this.passwordFile !== null) {
|
|
94
|
+
try {
|
|
95
|
+
const stat = fs.lstatSync(this.passwordFile);
|
|
96
|
+
if (stat.isFile() && !stat.isSymbolicLink()) fs.writeFileSync(this.passwordFile, Buffer.alloc(stat.size, 0));
|
|
97
|
+
} catch { /* cleaned up with directory below */ }
|
|
98
|
+
this.passwordFile = null;
|
|
99
|
+
}
|
|
100
|
+
if (directory !== null) {
|
|
101
|
+
const current = fs.lstatSync(directory);
|
|
102
|
+
if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== identity.dev || current.ino !== identity.ino) throw new AdapterError("MCP_CLEANUP_FAILED", "The private binding directory changed.");
|
|
103
|
+
fs.rmSync(directory, { recursive: true }); directory = null;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
if (!allowed) return binding;
|
|
108
|
+
if (!path.isAbsolute(selected) || path.resolve(selected) !== selected || path.extname(selected) !== ".kdna" || selected.length > 4096) throw invalid();
|
|
109
|
+
let descriptor;
|
|
110
|
+
try {
|
|
111
|
+
const before = fs.lstatSync(selected);
|
|
112
|
+
if (!before.isFile() || before.isSymbolicLink() || before.size > 64 * 1024 * 1024 || fs.realpathSync(selected) !== selected) throw invalid();
|
|
113
|
+
descriptor = fs.openSync(selected, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
114
|
+
const opened = fs.fstatSync(descriptor);
|
|
115
|
+
if (!sameFile(before, opened)) throw invalid();
|
|
116
|
+
const bytes = Buffer.alloc(opened.size);
|
|
117
|
+
let count = 0;
|
|
118
|
+
while (count < bytes.length) {
|
|
119
|
+
const read = fs.readSync(descriptor, bytes, count, bytes.length - count, null);
|
|
120
|
+
if (read === 0) throw invalid();
|
|
121
|
+
count += read;
|
|
122
|
+
}
|
|
123
|
+
if (fs.readSync(descriptor, Buffer.alloc(1), 0, 1, null) !== 0 || !sameFile(opened, fs.fstatSync(descriptor))) throw invalid();
|
|
124
|
+
const passphraseBytes = passwordFile !== undefined ? readPasswordFile(passwordFile) : passwordFd !== undefined ? readPasswordFd(passwordFd) : null;
|
|
125
|
+
directory = fs.mkdtempSync(path.join(os.tmpdir(), "kdna-mcp-read-"));
|
|
126
|
+
fs.chmodSync(directory, 0o700); identity = fs.lstatSync(directory);
|
|
127
|
+
const copy = path.join(directory, "selected.kdna");
|
|
128
|
+
fs.writeFileSync(copy, bytes, { flag: "wx", mode: 0o600 });
|
|
129
|
+
if (passphraseBytes !== null) {
|
|
130
|
+
const passCopy = path.join(directory, "passphrase");
|
|
131
|
+
fs.writeFileSync(passCopy, passphraseBytes, { flag: "wx", mode: 0o600 });
|
|
132
|
+
passphraseBytes.fill(0);
|
|
133
|
+
binding.passwordFile = passCopy;
|
|
134
|
+
}
|
|
135
|
+
binding.file = copy; binding.name = path.basename(selected);
|
|
136
|
+
binding.digest = "sha256:" + createHash("sha256").update(bytes).digest("hex");
|
|
137
|
+
binding.state = "bound";
|
|
138
|
+
return binding;
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (directory !== null) binding.close();
|
|
141
|
+
if (error instanceof AdapterError) throw error;
|
|
142
|
+
throw invalid();
|
|
143
|
+
} finally { if (descriptor !== undefined) fs.closeSync(descriptor); }
|
|
144
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { createRequire } from "node:module";
|
|
7
|
+
import { AdapterError } from "./operator-binding.mjs";
|
|
8
|
+
|
|
9
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
10
|
+
export const packageInfo = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
|
11
|
+
const versions = { cli: "0.44.0", core: "0.37.11", read: "0.13.5" };
|
|
12
|
+
function localPackage(name) {
|
|
13
|
+
const roots = [path.join(root, "node_modules")];
|
|
14
|
+
if (path.basename(path.dirname(root)) === "@aikdna" && path.basename(path.dirname(path.dirname(root))) === "node_modules") roots.push(path.dirname(path.dirname(root)));
|
|
15
|
+
for (const base of roots) {
|
|
16
|
+
const directory = path.join(base, "@aikdna", "kdna-" + name);
|
|
17
|
+
if (!fs.existsSync(path.join(directory, "package.json"))) continue;
|
|
18
|
+
if (fs.realpathSync(directory) !== directory) break;
|
|
19
|
+
const value = JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8"));
|
|
20
|
+
if (value.name !== "@aikdna/kdna-" + name || value.version !== versions[name]) break;
|
|
21
|
+
return { directory, value };
|
|
22
|
+
}
|
|
23
|
+
throw new AdapterError("MCP_RUNTIME_INVALID", "The fixed local CLI/Core/Read installation is unavailable.");
|
|
24
|
+
}
|
|
25
|
+
const cli = localPackage("cli"), core = localPackage("core"), read = localPackage("read");
|
|
26
|
+
const cliEntry = path.resolve(cli.directory, cli.value.bin?.kdna || "");
|
|
27
|
+
const bindingBytes = fs.readFileSync(path.join(cli.directory, "public-contract-binding.json"));
|
|
28
|
+
export const publicBinding = JSON.parse(bindingBytes);
|
|
29
|
+
if (packageInfo.kdna_runtime?.cli !== versions.cli || packageInfo.kdna_runtime?.core !== versions.core || packageInfo.kdna_runtime?.read !== versions.read || createHash("sha256").update(bindingBytes).digest("hex") !== "982e37adfa9726a56a8e58cf9295560ea6674c2cc67f1b4fdaf9b3c26ebd19ae" || publicBinding.implementation?.version !== versions.cli || publicBinding.tuple?.container !== "0.6.0" || publicBinding.tuple?.read !== "kdna.read/0.7.0-candidate" || publicBinding.accepted_core?.version !== versions.core || publicBinding.accepted_read?.version !== versions.read || packageInfo.kdna_runtime?.read_contract !== "kdna.read/0.7.0-candidate" || !cliEntry.startsWith(cli.directory + path.sep) || !fs.statSync(cliEntry).isFile()) throw new AdapterError("MCP_RUNTIME_INVALID", "The fixed native runtime contract binding is invalid.");
|
|
30
|
+
// Every consumer resolves the same fixed Core/Read instance; nested shadow copies are refused.
|
|
31
|
+
for (const [consumer, dependency] of [[cli, core], [cli, read], [read, core]]) {
|
|
32
|
+
const resolved = createRequire(path.join(consumer.directory, "package.json")).resolve(dependency.value.name + "/package.json");
|
|
33
|
+
if (resolved !== path.join(dependency.directory, "package.json")) throw new AdapterError("MCP_RUNTIME_INVALID", "The fixed native runtime contains a shadow dependency.");
|
|
34
|
+
}
|
|
35
|
+
const childEnv = Object.fromEntries(["HOME", "TMPDIR", "XDG_CACHE_HOME", "PATH", "LANG", "LC_ALL", "NODE_DISABLE_COMPILE_CACHE"].filter(key => process.env[key] !== undefined).map(key => [key, process.env[key]]));
|
|
36
|
+
const unavailable = () => new AdapterError("MCP_CLI_UNAVAILABLE", "The official local CLI session did not complete. Start a new operator-bound process.");
|
|
37
|
+
const cancelled = () => new AdapterError("MCP_READ_CANCELLED", "Local read presentation was cancelled; this process binding is closed.");
|
|
38
|
+
|
|
39
|
+
export class ReadSession {
|
|
40
|
+
constructor(binding) { this.binding = binding; this.child = null; this.pending = null; this.closing = null; this.stopped = false; }
|
|
41
|
+
start() {
|
|
42
|
+
this.binding.assertReadable();
|
|
43
|
+
if (this.stopped) throw unavailable();
|
|
44
|
+
if (this.child) return;
|
|
45
|
+
// The session keeps the raw library envelope: the complete official
|
|
46
|
+
// result with the reduction machinery intact, so this adapter's own
|
|
47
|
+
// projection can fold members and name their issued handles, and its
|
|
48
|
+
// machinery (handle scope, exact audit records, task presentation) reads
|
|
49
|
+
// the same envelope fields. What the model receives is projected later,
|
|
50
|
+
// per request, from the same official projection the CLI uses.
|
|
51
|
+
const sessionArgs = [cliEntry, "read", this.binding.file, "--session", "--allow-read", "--view", "raw", ...(this.binding.passwordFile ? ["--password-file", this.binding.passwordFile] : [])];
|
|
52
|
+
const child = spawn(process.execPath, sessionArgs, { env: childEnv, stdio: ["pipe", "pipe", "pipe"], shell: false });
|
|
53
|
+
this.child = child; this.buffer = Buffer.alloc(0); this.stderrBytes = 0;
|
|
54
|
+
this.exited = new Promise(resolve => child.once("close", (code, signal) => { this.stopped = true; this.rejectPending(unavailable()); resolve({ code, signal }); }));
|
|
55
|
+
child.on("error", () => { this.rejectPending(unavailable()); void this.close(false); });
|
|
56
|
+
child.stdin.on("error", () => { this.rejectPending(unavailable()); void this.close(false); });
|
|
57
|
+
child.stderr.on("data", chunk => { this.stderrBytes += chunk.length; if (this.stderrBytes > 65536) { this.rejectPending(unavailable()); void this.close(false); } });
|
|
58
|
+
child.stdout.on("data", chunk => {
|
|
59
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
60
|
+
if (this.buffer.length > 8 * 1024 * 1024) { this.rejectPending(unavailable()); void this.close(false); return; }
|
|
61
|
+
let newline;
|
|
62
|
+
while ((newline = this.buffer.indexOf(10)) !== -1) {
|
|
63
|
+
const bytes = this.buffer.subarray(0, newline); this.buffer = this.buffer.subarray(newline + 1);
|
|
64
|
+
const pending = this.pending;
|
|
65
|
+
if (!pending) { void this.close(false); return; }
|
|
66
|
+
this.pending = null; clearTimeout(pending.timer);
|
|
67
|
+
try { pending.resolve(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))); }
|
|
68
|
+
catch { pending.reject(unavailable()); void this.close(false); }
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
rejectPending(error) {
|
|
73
|
+
if (!this.pending) return;
|
|
74
|
+
const pending = this.pending; this.pending = null; clearTimeout(pending.timer); pending.reject(error);
|
|
75
|
+
}
|
|
76
|
+
request(value) {
|
|
77
|
+
this.start();
|
|
78
|
+
if (this.pending) throw new AdapterError("MCP_READ_BUSY", "Wait for the current local read or cancel it.");
|
|
79
|
+
return new Promise((resolve, reject) => {
|
|
80
|
+
const timer = setTimeout(() => { this.rejectPending(new AdapterError("MCP_READ_TIMEOUT", "The bounded local CLI read timed out.")); void this.close(false); }, 30000);
|
|
81
|
+
this.pending = { resolve, reject, timer };
|
|
82
|
+
this.child.stdin.write(JSON.stringify(value) + "\n", error => { if (error) { this.rejectPending(unavailable()); void this.close(false); } });
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
async close(graceful = true) {
|
|
86
|
+
if (this.closing) return this.closing;
|
|
87
|
+
this.stopped = true;
|
|
88
|
+
this.closing = (async () => {
|
|
89
|
+
this.rejectPending(cancelled());
|
|
90
|
+
if (!this.child) return;
|
|
91
|
+
if (graceful) this.child.stdin.end(); else this.child.kill("SIGTERM");
|
|
92
|
+
const timer = setTimeout(() => this.child.kill("SIGKILL"), 1000);
|
|
93
|
+
try { return await this.exited; } finally { clearTimeout(timer); }
|
|
94
|
+
})();
|
|
95
|
+
return this.closing;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function inspectBoundFile(binding, signal) {
|
|
100
|
+
binding.assertReadable();
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
const inspectArgs = [cliEntry, "inspect", binding.file, ...(binding.passwordFile ? ["--password-file", binding.passwordFile] : [])];
|
|
103
|
+
const child = spawn(process.execPath, inspectArgs, { env: childEnv, stdio: ["ignore", "pipe", "pipe"], shell: false });
|
|
104
|
+
let output = Buffer.alloc(0), errorBytes = 0, failure, killTimer;
|
|
105
|
+
const stop = error => { failure ??= error; child.kill("SIGTERM"); killTimer ??= setTimeout(() => child.kill("SIGKILL"), 1000); };
|
|
106
|
+
const aborted = () => stop(cancelled());
|
|
107
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
108
|
+
const timer = setTimeout(() => stop(unavailable()), 30000);
|
|
109
|
+
child.on("error", () => { failure ??= unavailable(); });
|
|
110
|
+
child.stdout.on("data", chunk => { output = Buffer.concat([output, chunk]); if (output.length > 8 * 1024 * 1024) stop(unavailable()); });
|
|
111
|
+
child.stderr.on("data", chunk => { errorBytes += chunk.length; if (errorBytes > 65536) stop(unavailable()); });
|
|
112
|
+
child.once("close", code => {
|
|
113
|
+
clearTimeout(timer); clearTimeout(killTimer); signal.removeEventListener("abort", aborted);
|
|
114
|
+
if (failure) { reject(failure); return; }
|
|
115
|
+
if (code !== 0 && code !== 1) { reject(unavailable()); return; }
|
|
116
|
+
try { resolve(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(output))); } catch { reject(unavailable()); }
|
|
117
|
+
});
|
|
118
|
+
if (signal.aborted) aborted();
|
|
119
|
+
});
|
|
120
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { AdapterError } from "./operator-binding.mjs";
|
|
3
|
+
import { compactTaskContent } from "./task-content.mjs";
|
|
4
|
+
|
|
5
|
+
const object = v => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
6
|
+
const encode = v => JSON.stringify(v);
|
|
7
|
+
const bytes = v => Buffer.byteLength(encode(v));
|
|
8
|
+
const digest = v => "sha256:" + createHash("sha256").update(encode(v)).digest("hex");
|
|
9
|
+
const fail = (code, message) => { throw new AdapterError(code, message); };
|
|
10
|
+
const envelopeKeys = ["contract", "mode", "request_id", "status", "tuple", "asset", "snapshot_id", "digests", "content", "states", "diagnostics", "omissions", "assessment", "verification", "receipt", "budget"];
|
|
11
|
+
const contentKeys = ["declarations", "catalog", "selected", "closure", "references", "relationships", "missing", "provenance", "asset_capability", "asset_index", "expansion_handles"];
|
|
12
|
+
const handleKeys = ["binding_kind", "handle_id", "asset", "tuple", "origin", "issuing_operation_id", "issuing_request_digest", "anchor", "target", "scope", "issued_at", "expires_at", "host_id", "host_epoch"];
|
|
13
|
+
const exact = (v, names) => object(v) && Object.keys(v).length === names.length && names.every(k => Object.hasOwn(v, k));
|
|
14
|
+
const byteAdmissionContract = v => exact(v, ["id", "version", "definition_digest"]) && v.id === "kdna.section-bytes-node" && v.version === "0.1.1-candidate" && v.definition_digest === "sha256:8358dfe622117bb88866d7f72ca15e21961a87b37e108978ed05015b102277ef";
|
|
15
|
+
const uint = v => Number.isSafeInteger(v) && v >= 0;
|
|
16
|
+
const identifier = v => typeof v === "string" && v.length > 0 && [...v].length <= 256 && !/[\u0000-\u001f\u007f-\u009f\ud800-\udfff]/u.test(v);
|
|
17
|
+
const entryName = v => typeof v === "string" && [...v].length <= 4096 && /^(?!\/)(?!.*(?:^|\/)(?:\.|\.\.)(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\u0000-\u001f\u007f-\u009f]+$/u.test(v);
|
|
18
|
+
const sha = v => typeof v === "string" && /^sha256:[0-9a-f]{64}$/.test(v);
|
|
19
|
+
const singleRangePurposes = ["zip_end", "zip_directory", "zip_local_header", "zip_local_name", "mimetype", "manifest", "whole_after_authorization", "zip_directory_header", "zip_directory_name", "section_table_after_authorization", "section_content_after_authorization", "resource_after_authorization", "section_structure_after_authorization", "zip_locator_local_signature", "zip_locator_local_header", "zip_locator_directory_signature", "zip_locator_directory_header", "zip_locator_directory_name", "zip_locator_local_name", "zip_locator_eocd", "zip_comment", "checksum_document_after_authorization", "checksum_member_after_authorization", "signature_document_after_authorization", "signature_member_after_authorization"];
|
|
20
|
+
const rangeBytes = v => exact(v, ["offset_bytes", "length_bytes"]) && uint(v.offset_bytes) && uint(v.length_bytes);
|
|
21
|
+
function byteObservation(v) {
|
|
22
|
+
if (v === null) return true;
|
|
23
|
+
if (!exact(v, ["contract", "input_kind", "input_byte_length", "ownership_copy", "capture", "access_ranges", "filesystem_reads"]) || !byteAdmissionContract(v.contract) || v.input_kind !== "owned_uint8array" || !uint(v.input_byte_length) || !rangeBytes(v.ownership_copy) || v.ownership_copy.offset_bytes !== 0 || v.ownership_copy.length_bytes !== v.input_byte_length || v.filesystem_reads !== 0 || !Array.isArray(v.access_ranges)) return false;
|
|
24
|
+
const c = v.capture;
|
|
25
|
+
if (c !== null && (!exact(c, ["capture_id", "input_byte_length", "manifest_bytes_digest", "zip_directory_bytes_digest", "table_frames", "identity_scope"]) || !identifier(c.capture_id) || !uint(c.input_byte_length) || !sha(c.manifest_bytes_digest) || !sha(c.zip_directory_bytes_digest) || c.identity_scope !== "observed_metadata_and_loaded_sections_only" || !Array.isArray(c.table_frames) || !c.table_frames.every(row => exact(row, ["section_id", "member", "offset_bytes", "length_bytes", "digest"]) && identifier(row.section_id) && entryName(row.member) && uint(row.offset_bytes) && uint(row.length_bytes) && row.length_bytes > 0 && sha(row.digest)))) return false;
|
|
26
|
+
return v.access_ranges.every(row => exact(row, ["offset_bytes", "length_bytes", "purpose"]) ? uint(row.offset_bytes) && uint(row.length_bytes) && singleRangePurposes.includes(row.purpose) : exact(row, ["purpose", "ranges"]) && ["section_structure_after_authorization", "section_interpretation_after_authorization"].includes(row.purpose) && Array.isArray(row.ranges) && row.ranges.length >= 1 && row.ranges.length <= 4096 && row.ranges.every(rangeBytes));
|
|
27
|
+
}
|
|
28
|
+
function byteAdmissionRejection(v) {
|
|
29
|
+
// Recognize the pinned official no-body layout only. This does not parse,
|
|
30
|
+
// validate an asset, grant authority or reinterpret its original diagnosis.
|
|
31
|
+
return exact(v, ["contract", "request_id", "status", "reason", "stage", "diagnostic", "input_observation", "snapshot"]) && byteAdmissionContract(v.contract) && ["rejected", "unsupported"].includes(v.status) && (v.request_id === null || identifier(v.request_id)) && typeof v.reason === "string" && /\S/u.test(v.reason) && ["input", "metadata", "authorization", "content", "semantic", "integrity"].includes(v.stage) && v.snapshot === null && (v.diagnostic === null || exact(v.diagnostic, ["field", "subject"]) && (v.diagnostic.field === null || typeof v.diagnostic.field === "string") && (v.diagnostic.subject === null || identifier(v.diagnostic.subject))) && byteObservation(v.input_observation);
|
|
32
|
+
}
|
|
33
|
+
const unavailable = () => fail("MCP_TASK_VIEW_UNAVAILABLE", "This official result cannot be represented completely by the task view. Request full presentation explicitly.");
|
|
34
|
+
const stale = () => fail("MCP_REFERENCE_UNAVAILABLE", "The reference is absent, expired or outside this live operator-bound session. A reference grants no permission.");
|
|
35
|
+
function summaryFields(value, kept, proof, required = []) {
|
|
36
|
+
if (!object(value) || Object.keys(value).some(k => ![...kept, ...proof].includes(k)) || !required.every(k => Object.hasOwn(value, k))) unavailable();
|
|
37
|
+
return Object.fromEntries(kept.filter(k => Object.hasOwn(value, k)).map(k => [k, structuredClone(value[k])]));
|
|
38
|
+
}
|
|
39
|
+
function verificationSummary(v) {
|
|
40
|
+
const names = ["contract", "operation_id", "origin", "request_digest", "intent_digest", "mode", "origin_verification", "signature_policy_check", "new_capture", "io", "new_domain_validation", "new_digest_computation"];
|
|
41
|
+
if (!exact(v, names)) unavailable();
|
|
42
|
+
const o = v.origin_verification;
|
|
43
|
+
if (!exact(o, ["signature_integrity", "checksum_integrity", "capture", "request_digest", "checked_sections", "unchecked_sections", "routing_integrity", "runtime_entry_digest", "whole_container_digest", "whole_content_digest", "ir_digest", "mode", "semantic_status"])) unavailable();
|
|
44
|
+
const signature = summaryFields(o.signature_integrity, ["status", "policy", "profile", "profile_version", "algorithm", "public_key", "key_fingerprint", "members", "excluded_members"], ["policy_digest", "read_intent_digest", "capture_id", "request_digest", "signature_document_digest", "expected_signature_content_digest", "observed_signature_content_digest"], ["status", "policy"]);
|
|
45
|
+
const checksum = summaryFields(o.checksum_integrity, ["status", "profile", "profile_version", "covered_entries"], ["document_digest", "expected_entry_set_digest", "observed_entry_set_digest", "capture_id", "request_digest", "observed_A", "observed_C"], ["status"]);
|
|
46
|
+
const origin = summaryFields(v.origin, ["kind", "snapshot_id"], ["capture_id", "admission_request_digest", "verification_digest", "checked_sections_digest"], ["kind", "snapshot_id"]);
|
|
47
|
+
const capture = summaryFields(o.capture, ["identity_scope"], ["capture_id", "input_byte_length", "manifest_bytes_digest", "zip_directory_bytes_digest", "table_frames"], ["identity_scope"]);
|
|
48
|
+
const signaturePolicy = summaryFields(v.signature_policy_check, ["basis", "policy", "result", "new_signature_verification"], ["policy_digest", "origin_receipt_digest"], ["basis", "policy", "result", "new_signature_verification"]);
|
|
49
|
+
if (!Array.isArray(o.checked_sections) || !Array.isArray(o.unchecked_sections)) unavailable();
|
|
50
|
+
for (const row of o.checked_sections) if (!exact(row, ["section_id", "member", "offset_bytes", "length_bytes", "digest"])) unavailable();
|
|
51
|
+
const digests = Object.fromEntries(["runtime_entry_digest", "whole_container_digest", "whole_content_digest", "ir_digest"].map(key => [key, summaryFields(o[key], ["status", "profile", "member_names"], ["digest"], ["status", "profile"])]));
|
|
52
|
+
return { origin, signature_integrity: signature, checksum_integrity: checksum, routing_integrity: o.routing_integrity, capture,
|
|
53
|
+
mode: o.mode, semantic_status: o.semantic_status, digest_verification: digests,
|
|
54
|
+
checked_sections: o.checked_sections.map(row => row.section_id), unchecked_sections: o.unchecked_sections,
|
|
55
|
+
signature_policy_check: signaturePolicy, new_capture: v.new_capture, new_domain_validation: v.new_domain_validation, new_digest_computation: v.new_digest_computation, io: v.io };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// A presentation adapter, never a parser, verifier or authorization provider.
|
|
59
|
+
// Records are published only after a complete view fits its delivery budget.
|
|
60
|
+
export class ReadingViews {
|
|
61
|
+
constructor(binding, session, { now = () => performance.now(), wallNow = Date.now, ttl = 60000, maxBytes = 4 * 1024 * 1024, maxRecords = 32, maxHandles = 256 } = {}) {
|
|
62
|
+
this.binding = binding; this.session = session; this.now = now; this.wallNow = wallNow;
|
|
63
|
+
this.ttl = Math.min(ttl, 60000); this.maxBytes = maxBytes; this.maxRecords = maxRecords; this.maxHandles = maxHandles;
|
|
64
|
+
this.clear();
|
|
65
|
+
}
|
|
66
|
+
clear() { this.records = new Map(); this.handles = new Map(); this.totalBytes = 0; this.scope = null; }
|
|
67
|
+
storageBytes(records = this.records, handles = this.handles) {
|
|
68
|
+
if (records.size === 0 && handles.size === 0) return 0;
|
|
69
|
+
// Charge the complete encoded tables, including opaque keys, scope,
|
|
70
|
+
// deadlines, lengths, escaping and structural overhead, not only bodies.
|
|
71
|
+
return bytes({ scope: this.scope, records: [...records], handles: [...handles] });
|
|
72
|
+
}
|
|
73
|
+
assertLive() {
|
|
74
|
+
try { this.binding.assertReadable(); }
|
|
75
|
+
catch (cause) { this.clear(); throw cause; }
|
|
76
|
+
if (this.session.stopped) { this.clear(); stale(); }
|
|
77
|
+
}
|
|
78
|
+
prune() {
|
|
79
|
+
const time = this.now();
|
|
80
|
+
for (const [ref, record] of this.records) if (record.expires <= time) this.records.delete(ref);
|
|
81
|
+
for (const [ref, handle] of this.handles) if (handle.expires <= time) this.handles.delete(ref);
|
|
82
|
+
this.totalBytes = this.storageBytes();
|
|
83
|
+
}
|
|
84
|
+
observe(value) {
|
|
85
|
+
const e = value?.channel === "read_envelope" ? value.envelope : null;
|
|
86
|
+
if (e?.states?.read_permission === "denied") { this.clear(); return; }
|
|
87
|
+
if (!e || typeof e.snapshot_id !== "string" || !object(e.receipt) || typeof e.receipt.host_epoch !== "string") return;
|
|
88
|
+
const scope = encode([this.binding.digest, e.snapshot_id, e.asset, e.tuple, e.receipt.host_id, e.receipt.host_epoch]);
|
|
89
|
+
if (this.scope !== scope) { this.clear(); this.scope = scope; }
|
|
90
|
+
}
|
|
91
|
+
task(value, viewBudget) {
|
|
92
|
+
this.assertLive(); this.observe(value); this.prune();
|
|
93
|
+
if (!Number.isSafeInteger(viewBudget) || viewBudget < 0 || viewBudget > 1000000) unavailable();
|
|
94
|
+
// Complete official no-body controls/rejections keep every causal field.
|
|
95
|
+
// They never issue an audit reference or disguise a refusal as a read.
|
|
96
|
+
const byteRejected = byteAdmissionRejection(value);
|
|
97
|
+
if (object(value) && (value.contract?.id === "kdna.section-bytes-node" || Object.hasOwn(value, "input_observation")) && !byteRejected) unavailable();
|
|
98
|
+
if (byteRejected || (value?.channel === "no_body_control") || (value?.status === "rejected" && value.body === null && value.body_bytes === 0) || (value?.status === "rejected" && typeof value?.code === "string" && (value.code.startsWith("KDNA_") || value.code.startsWith("PROTECTION_"))) || (value?.channel === "read_envelope" && value.envelope?.status === "rejected" && value.envelope.content === null)) {
|
|
99
|
+
const model = { contract: { id: "kdna.mcp.task-presentation", version: "0.1.0" }, status: "rejected", official_result: value, authorization: { action_authorized: false }, audit: null, budget: { view_limit_bytes: viewBudget } };
|
|
100
|
+
if (bytes(model) > viewBudget) fail("MCP_TASK_VIEW_BUDGET_EXCEEDED", "The complete refusal view requires " + bytes(model) + " UTF-8 bytes; no partial result was delivered.");
|
|
101
|
+
return model;
|
|
102
|
+
}
|
|
103
|
+
if (!exact(value, ["channel", "envelope", "admission_rejection", "control", "transport_failure"]) || value.channel !== "read_envelope" || value.admission_rejection !== null || value.control !== null || value.transport_failure !== null) unavailable();
|
|
104
|
+
const e = value.envelope;
|
|
105
|
+
if (!exact(e, envelopeKeys) || e.contract?.id !== "kdna.retained-sections" || e.contract?.version !== "0.1.0-candidate" || !["catalog", "exact_selection", "expand"].includes(e.mode) || !["catalog_only", "ready", "rejected"].includes(e.status) || !this.scope || !object(e.content) || Object.keys(e.content).some(k => !contentKeys.includes(k)) || !object(e.states) || !Array.isArray(e.diagnostics) || !Array.isArray(e.omissions)) unavailable();
|
|
106
|
+
const expires = this.now() + this.ttl, expiresAt = this.wallNow() + this.ttl, handleRecords = [], ids = new Map();
|
|
107
|
+
const content = structuredClone(e.content);
|
|
108
|
+
if (Object.hasOwn(content, "expansion_handles")) {
|
|
109
|
+
if (!Array.isArray(content.expansion_handles)) unavailable();
|
|
110
|
+
content.expansion_handles = content.expansion_handles.map(h => {
|
|
111
|
+
if (!exact(h, handleKeys) || h.binding_kind !== "retained_section_snapshot" || h.origin?.snapshot_id !== e.snapshot_id || h.host_id !== e.receipt.host_id || h.host_epoch !== e.receipt.host_epoch || encode(h.asset) !== encode(e.asset) || encode(h.tuple) !== encode(e.tuple) || !Array.isArray(h.scope) || !Number.isSafeInteger(h.expires_at) || !Number.isSafeInteger(h.issued_at)) unavailable();
|
|
112
|
+
const ref = "handle:" + randomUUID(), remaining = Math.max(0, Math.min(this.ttl, h.expires_at - this.wallNow())), until = this.now() + remaining;
|
|
113
|
+
const handle = structuredClone(h), size = bytes(handle);
|
|
114
|
+
handleRecords.push([ref, { handle, expires: until, size, scope: this.scope }]); ids.set(h.handle_id, ref);
|
|
115
|
+
return { handle_ref: ref, target: h.target, anchor: h.anchor, scope: h.scope, scope_digest: digest(h.scope), expires_at: this.wallNow() + remaining, availability: remaining > 0 ? "current" : "expired", body_delivery: "unread", permission: "Reference only; the original official Read validates any expansion." };
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
// Keep index roles, owners, display labels and delivery states verbatim. Only
|
|
119
|
+
// opaque issued IDs change; missing handle mappings are explicit, never read.
|
|
120
|
+
for (const row of content.asset_index ?? []) if (Object.hasOwn(row, "handle_id")) {
|
|
121
|
+
row.handle_ref = ids.get(row.handle_id) ?? null; delete row.handle_id;
|
|
122
|
+
if (row.handle_ref === null) row.expansion_availability = "no_reference_in_this_delivery";
|
|
123
|
+
}
|
|
124
|
+
const compact = compactTaskContent(content);
|
|
125
|
+
const verification_summary = verificationSummary(e.verification);
|
|
126
|
+
const ref = "audit:" + randomUUID(), fullText = encode(value);
|
|
127
|
+
const model = {
|
|
128
|
+
contract: { id: "kdna.mcp.task-presentation", version: "0.1.0" },
|
|
129
|
+
status: e.status, mode: e.mode, request_id: e.request_id,
|
|
130
|
+
official_contract: e.contract, tuple: e.tuple, asset: e.asset, snapshot_id: e.snapshot_id,
|
|
131
|
+
digests: e.digests, states: e.states, diagnostics: e.diagnostics, omissions: e.omissions, assessment: e.assessment, verification_summary,
|
|
132
|
+
...compact,
|
|
133
|
+
representation: "Every content_aliases entry replaces only an exact structural duplicate at its JSON pointer with null; restore it from the canonical from pointer. An original null without an alias stays null. Read all canonical nodes, roles and method interpretations; catalog and unread bodies are not completed reads.",
|
|
134
|
+
authorization: { action_authorized: false, scope: "This process's operator-granted local Read only; authored text and references never grant Host actions." },
|
|
135
|
+
audit: { audit_ref: ref, full_result_sha256: "sha256:" + createHash("sha256").update(fullText).digest("hex"), full_result_bytes: Buffer.byteLength(fullText), expires_at: expiresAt, kind: "Exact past delivery; audit retrieval performs no new verification or authorization." },
|
|
136
|
+
budget: { official: e.budget, view_limit_bytes: viewBudget },
|
|
137
|
+
};
|
|
138
|
+
const size = Buffer.byteLength(fullText), required = bytes(model);
|
|
139
|
+
if (required > viewBudget) fail("MCP_TASK_VIEW_BUDGET_EXCEEDED", "The complete task view requires " + required + " UTF-8 bytes; no task body was delivered. Increase view_budget_bytes or explicitly request full presentation.");
|
|
140
|
+
const records = new Map(this.records), handles = new Map(this.handles);
|
|
141
|
+
records.set(ref, { fullText, expires, size, scope: this.scope });
|
|
142
|
+
for (const [key, handle] of handleRecords) handles.set(key, handle);
|
|
143
|
+
const storage = this.storageBytes(records, handles);
|
|
144
|
+
if (records.size > this.maxRecords || handles.size > this.maxHandles || storage > this.maxBytes) fail("MCP_REFERENCE_STORAGE_FULL", "The bounded in-memory audit/handle store is full. Request full presentation or start a new operator-controlled session.");
|
|
145
|
+
this.records = records; this.handles = handles; this.totalBytes = storage;
|
|
146
|
+
return model;
|
|
147
|
+
}
|
|
148
|
+
audit(ref, budget) {
|
|
149
|
+
this.assertLive(); this.prune();
|
|
150
|
+
const record = this.records.get(ref);
|
|
151
|
+
if (!record || record.scope !== this.scope) stale();
|
|
152
|
+
if (record.size > budget) fail("MCP_AUDIT_BUDGET_EXCEEDED", "The exact past result requires " + record.size + " UTF-8 bytes; no partial audit was delivered.");
|
|
153
|
+
return JSON.parse(record.fullText);
|
|
154
|
+
}
|
|
155
|
+
expand(ref) {
|
|
156
|
+
this.assertLive(); this.prune();
|
|
157
|
+
const record = this.handles.get(ref);
|
|
158
|
+
if (!record || record.scope !== this.scope) stale();
|
|
159
|
+
return structuredClone(record.handle);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
|
|
3
|
+
// This only changes the adapter's representation of already-complete Read
|
|
4
|
+
// content. Aliases are outside authored JSON; null without an alias stays null.
|
|
5
|
+
const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
6
|
+
const canonicalRoles = new Set(["result", "result_contract", "method_component"]);
|
|
7
|
+
const escaped = value => String(value).replaceAll("~", "~0").replaceAll("/", "~1");
|
|
8
|
+
const pointer = parts => "/" + parts.map(escaped).join("/");
|
|
9
|
+
const prefix = (parent, child) => parent.length <= child.length && parent.every((part, index) => part === child[index]);
|
|
10
|
+
const fail = message => { throw new TypeError("Invalid task content aliases: " + message); };
|
|
11
|
+
|
|
12
|
+
function parts(value) {
|
|
13
|
+
if (typeof value !== "string" || !value.startsWith("/") || /~(?![01])/u.test(value)) fail("invalid JSON pointer");
|
|
14
|
+
return value.slice(1).split("/").map(part => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
15
|
+
}
|
|
16
|
+
function own(value, key) {
|
|
17
|
+
if ((!object(value) && !Array.isArray(value)) || !Object.hasOwn(value, key)) fail("pointer target is absent");
|
|
18
|
+
if (Array.isArray(value) && (!/^(0|[1-9]\d*)$/u.test(key) || Number(key) >= value.length)) fail("invalid array index");
|
|
19
|
+
return value[key];
|
|
20
|
+
}
|
|
21
|
+
function get(value, path) {
|
|
22
|
+
for (const key of path) value = own(value, key);
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
function put(value, path, replacement) {
|
|
26
|
+
const parent = get(value, path.slice(0, -1));
|
|
27
|
+
own(parent, path.at(-1));
|
|
28
|
+
Object.defineProperty(parent, path.at(-1), { value: replacement, enumerable: true, configurable: true, writable: true });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function validRoute(content, alias) {
|
|
32
|
+
const from = alias.fromParts, at = alias.atParts;
|
|
33
|
+
if (from[0] !== "closure" || from.length < 2) fail("source is not a closure node");
|
|
34
|
+
const node = get(content, from.slice(0, 2));
|
|
35
|
+
if (!object(node) || node.id !== alias.node_id || node.role !== alias.role) fail("canonical identity does not match");
|
|
36
|
+
if (from.length === 2) {
|
|
37
|
+
if (!(at.length === 2 && at[0] === "declarations") && !(at.length === 3 && at[0] === "provenance" && at[1] === "declarations")) fail("unsupported node-copy target");
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (from.length === 3 && from[2] === "value" && canonicalRoles.has(node.role)) {
|
|
41
|
+
if (at[0] !== "closure" || at[1] === from[1] || at[2] !== "value") fail("unsupported value-copy target");
|
|
42
|
+
const owner = get(content, at.slice(0, 2));
|
|
43
|
+
if (owner.role !== "judgment") fail("value-copy target is not a judgment");
|
|
44
|
+
const allowed = (node.role === "result" && at.length === 4 && at[3] === "result") ||
|
|
45
|
+
(node.role === "result_contract" && at.length === 4 && at[3] === "result_contract") ||
|
|
46
|
+
(node.role === "method_component" && at.length === 6 && at[3] === "method" && at[4] === "components");
|
|
47
|
+
if (!allowed) fail("unsupported author-copy path");
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (node.role === "judgment" && from.length === 4 && from[2] === "value" && from[3] === "method" && at.length === 4 && at[0] === "closure" && at[1] === from[1] && at[2] === "method_interpretation" && at[3] === "declaration") return;
|
|
51
|
+
fail("unsupported canonical source");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function compactTaskContent(original) {
|
|
55
|
+
if (!object(original)) throw new TypeError("Task content must be a JSON object.");
|
|
56
|
+
const content = structuredClone(original), content_aliases = [];
|
|
57
|
+
if (!Array.isArray(original.closure)) return { content, content_aliases };
|
|
58
|
+
const closure = original.closure;
|
|
59
|
+
const canonical = closure.map((node, index) => ({ node, index })).filter(({ node }) => object(node) && typeof node.id === "string" && typeof node.role === "string");
|
|
60
|
+
const add = (at, from, node) => {
|
|
61
|
+
// Never alias scalars, authored prose, explicit null, or a partial object.
|
|
62
|
+
const before = get(original, at), source = get(original, from);
|
|
63
|
+
if (!object(before) || !object(source) || !isDeepStrictEqual(before, source)) return;
|
|
64
|
+
content_aliases.push({ at: pointer(at), from: pointer(from), node_id: node.id, role: node.role });
|
|
65
|
+
};
|
|
66
|
+
const nodeCopies = (entries, at) => {
|
|
67
|
+
if (!Array.isArray(entries)) return;
|
|
68
|
+
entries.forEach((entry, index) => {
|
|
69
|
+
const source = canonical.find(({ node }) => isDeepStrictEqual(entry, node));
|
|
70
|
+
if (source) add([...at, index], ["closure", source.index], source.node);
|
|
71
|
+
});
|
|
72
|
+
};
|
|
73
|
+
nodeCopies(original.declarations, ["declarations"]);
|
|
74
|
+
nodeCopies(original.provenance?.declarations, ["provenance", "declarations"]);
|
|
75
|
+
const copyValue = (at, role) => {
|
|
76
|
+
const value = get(original, at);
|
|
77
|
+
const source = canonical.find(({ node }) => node.role === role && object(node.value) && isDeepStrictEqual(value, node.value));
|
|
78
|
+
if (source) add(at, ["closure", source.index, "value"], source.node);
|
|
79
|
+
};
|
|
80
|
+
canonical.forEach(({ node, index }) => {
|
|
81
|
+
if (node.role !== "judgment" || !object(node.value)) return;
|
|
82
|
+
const base = ["closure", index, "value"];
|
|
83
|
+
if (Object.hasOwn(node.value, "result")) copyValue([...base, "result"], "result");
|
|
84
|
+
if (Object.hasOwn(node.value, "result_contract")) copyValue([...base, "result_contract"], "result_contract");
|
|
85
|
+
if (Array.isArray(node.value.method?.components)) node.value.method.components.forEach((_, component) => copyValue([...base, "method", "components", component], "method_component"));
|
|
86
|
+
if (Object.hasOwn(node.value, "method") && object(node.method_interpretation) && Object.hasOwn(node.method_interpretation, "declaration")) add(["closure", index, "method_interpretation", "declaration"], [...base, "method"], node);
|
|
87
|
+
});
|
|
88
|
+
// A source may contain placeholders that are restored first, but must never
|
|
89
|
+
// be inside a removed subtree. These finite routes do not overlap targets.
|
|
90
|
+
const aliases = content_aliases.map(alias => ({ ...alias, atParts: parts(alias.at), fromParts: parts(alias.from) }));
|
|
91
|
+
for (const alias of aliases) {
|
|
92
|
+
validRoute(content, alias);
|
|
93
|
+
if (aliases.some(other => prefix(other.atParts, alias.fromParts))) fail("canonical source would be removed");
|
|
94
|
+
put(content, alias.atParts, null);
|
|
95
|
+
}
|
|
96
|
+
return { content, content_aliases };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function reconstructTaskContent(representation) {
|
|
100
|
+
if (!object(representation) || !object(representation.content) || !Array.isArray(representation.content_aliases)) throw new TypeError("Task representation requires content and content_aliases.");
|
|
101
|
+
const content = structuredClone(representation.content);
|
|
102
|
+
const aliases = representation.content_aliases.map(alias => {
|
|
103
|
+
if (!object(alias) || Object.keys(alias).length !== 4 || !["at", "from", "node_id", "role"].every(key => Object.hasOwn(alias, key)) || typeof alias.node_id !== "string" || typeof alias.role !== "string") fail("invalid alias fields");
|
|
104
|
+
return { ...alias, atParts: parts(alias.at), fromParts: parts(alias.from) };
|
|
105
|
+
});
|
|
106
|
+
for (const alias of aliases) {
|
|
107
|
+
validRoute(content, alias);
|
|
108
|
+
if (get(content, alias.atParts) !== null) fail("target is not a null placeholder");
|
|
109
|
+
if (prefix(alias.fromParts, alias.atParts)) fail("source contains its own target");
|
|
110
|
+
if (aliases.some(other => prefix(other.atParts, alias.fromParts))) fail("canonical source is removed");
|
|
111
|
+
if (aliases.some(other => other !== alias && (prefix(other.atParts, alias.atParts) || prefix(alias.atParts, other.atParts)))) fail("overlapping targets");
|
|
112
|
+
}
|
|
113
|
+
const pending = new Set(aliases);
|
|
114
|
+
while (pending.size) {
|
|
115
|
+
const next = [...pending].find(alias => ![...pending].some(other => other !== alias && prefix(alias.fromParts, other.atParts)));
|
|
116
|
+
if (!next) fail("cyclic alias dependencies");
|
|
117
|
+
const source = get(content, next.fromParts);
|
|
118
|
+
if (!object(source)) fail("source is not a complete object");
|
|
119
|
+
put(content, next.atParts, structuredClone(source));
|
|
120
|
+
pending.delete(next);
|
|
121
|
+
}
|
|
122
|
+
return content;
|
|
123
|
+
}
|